<template>
  <div class="full-size" style="display: flex;flex-direction: column;">
    <div style="display: flex; justify-content: center; margin-bottom: 10px;">
      <el-radio-group v-model="principleType">
        <el-radio-button label="group">继承策略的权限</el-radio-button>
        <el-radio-button label="user"><span style="display: inline-block;width: 100px;">个人权限</span></el-radio-button>
      </el-radio-group>
    </div>
    <div v-if="principleType === 'user'">
      <el-button v-permission="'user:CreatePolicyAttachment | policy-attachment:CreateInstancesToUser'" type="primary" style="margin-bottom: 10px;" @click="toAddPolicy">添加权限</el-button>
    </div>
    <div style="display: flex; flex-direction: column; flex: 1; overflow: hidden">
      <template v-if="principleType === 'group'">
        <el-table
          key="listGroupPolicesTable"
          :data="groupPolices"
          class="table-height-auto"
        >
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="principalId" label="所属组"  min-width="250">
            <template slot-scope="scope">
              {{ scope.row.principalId.split('@')[0] }}
            </template>
          </el-table-column>
          <el-table-column prop="policyName" label="权限策略名称" min-width="180"></el-table-column>
          <el-table-column prop="policyType" label="权限策略类型" min-width="180">
            <template slot-scope="scope">
              {{ scope.row.policyType | filterPolicyType }}
            </template>
          </el-table-column>
          <el-table-column prop="comments" label="备注"></el-table-column>
        </el-table>
      </template>
      <template v-if="principleType === 'user'">
        <el-table
          key="listUserPolicesTable"
          :data="userPolices"
          class="table-height-auto"
        >
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="policyName" label="权限策略名称"></el-table-column>
          <el-table-column prop="policyType" label="权限策略类型">
            <template slot-scope="scope">
              {{ scope.row.policyType | filterPolicyType }}
            </template>
          </el-table-column>
          <el-table-column prop="comments" label="备注"></el-table-column>
          <el-table-column prop="attachTime" label="授权时间"></el-table-column>
          <el-table-column
            label="操作"
            min-width="80">
            <template slot-scope="scope">
              <el-button v-permission="'user:DeletePolicyAttachment | policy-attachment:DeleteInstanceFromUser'" type="text" @click="removePolicy(scope.$index)" >移除权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </div>

    <!-- 添加权限 -->
    <el-dialog :append-to-body="true" style="min-height: 400px" title="添加权限" :modal="true" top="100px" :close-on-click-modal="false" v-if="showAddPolicy" :visible.sync="showAddPolicy">
      <div slot="title" class="custom-el-dialog-header-title">
        <span>添加权限</span>
        <div class="plain-button" @click="savePolicyAttachment">
          <i class="font_family icon-save plain-button-icon"></i><span class="plain-button-text">&nbsp;保存</span>
        </div>
      </div>
      <el-select v-model="policyType" placeholder="权限策略类型" style="margin-bottom: 15px; margin-top: -10px;">
        <el-option label="全部" value="all"></el-option>
        <el-option label="系统策略" value="system"></el-option>
        <el-option label="自定义策略" value="custom"></el-option>
      </el-select>
      <el-table
        ref="addPolicyTable"
        :data="availablePolicyList"
        class="table-height-auto"
      >
        <el-table-column type="selection" width="45"></el-table-column>
        <el-table-column prop="policyName" label="权限策略名称" min-width="250"></el-table-column>
        <el-table-column prop="policyType" label="权限策略类型" min-width="180">
          <template slot-scope="scope">
            {{ scope.row.policyType | filterPolicyType }}
          </template>
        </el-table-column>
        <el-table-column prop="comments" label="备注" min-width="180">
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'UserPolicySelector',
  props: {
    userId: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      principleType: 'group',
      groupPolices: [],
      userPolices: [],
      allPolicyList: [],
      showAddPolicy: false,
      policyType: 'all'
    }
  },
  computed: {
    availablePolicyList: function () {
      const policySet = new Set(this.userPolices.map(p => p.policyId))
      return this.allPolicyList.filter(p => !policySet.has(p.policyId))
        .filter(p => this.policyType === 'all' || this.policyType === p.policyType)
    }
  },
  filters: {
    filterPolicyType: function (value) {
      return value === 'system' ? '系统策略' : '自定义策略'
    }
  },
  created () {
  },
  mounted () {
    // 加载用户所在组
    this.loadUserAllPolicies()
  },
  methods: {
    // 供外部刷新通知使用
    refresh () {
      this.loadUserAllPolicies()
    },
    loadAllPolicy () {
      this.$http.get(this.$apiUrl('listAllPolicy'))
        .then(response => {
          this.allPolicyList = response.data.data
          this.allPolicyList.forEach(p => { p.policyId = p.id })
        })
        .catch((error) => {
          this.$message.error(error.message)
        })
    },
    loadUserAllPolicies () {
      // 加载指定用户的策略信息
      if (typeof (this.userId) === 'string') {
        this.$http.get(this.$apiUrl('getPoliciesOfUser') + `?id=${this.userId}`).then((response) => {
          const allPolices = response.data.data
          this.userPolices = allPolices.filter(p => p.principalType === 'user')
          this.groupPolices = allPolices.filter(p => p.principalType === 'group')
        }).catch((response) => {
          console.log('获取策略列表失败', response)
          this.$message.error(response.message)
        })
      }
    },
    toAddPolicy () {
      this.showAddPolicy = true
      if (this.allPolicyList.length === 0) {
        this.loadAllPolicy()
      }
    },
    // 保存添加组
    savePolicyAttachment () {
      const selectionGroup = this.$refs.addPolicyTable.selection
      const policyId = selectionGroup.map(policy => policy.id)
      if (policyId.length === 0) {
        return this.$message.warning('请选择策略')
      }
      // this.$qs.stringify(this.userForm)
      this.$http.post(this.$apiUrl('createPolicyOfUser'), { userId: this.userId, policyId })
        .then(response => {
          this.$message.success('添加策略成功')
          this.userPolices.push(...selectionGroup)
          this.showAddPolicy = false
          console.log(this.userPolices)
        })
        .catch(error => {
          this.$message.error(`创建失败! ${error.message}`)
        })
        .always(() => {
        })
    },
    removePolicy (index) {
      const policyId = [this.userPolices[index].policyId]
      const url = this.$apiUrl('deletePolicyOfUser') + '?' + this.$qs.stringify({ userId: this.userId, policyId })
      this.$http.delete(url)
        .then(response => {
          this.$message.success('移除策略成功')
          this.userPolices.splice(index, 1).map(group => group.id)
          console.log(this.userPolices)
        })
        .catch(error => {
          this.$message.error(`移除策略失败! ${error.message}`)
        })
    }
  }
}
</script>
<style lang="scss" scoped>
  @import '../../style/mixin';
</style>
