<template>
  <el-form
    inline
    :model="form"
    :rules="rules"
    ref="form"
    class="form-wrap"
    label-width="100px"
  >
    <div class="table-box">
      <el-form-item
        label="角色名"
        prop="name"
      >
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <div class="permissionList">
        <div class="block-title">
          角色权限
        </div>
        <table
          v-loading="loading"
          :data="permissionList"
          class="table"
        >
          <tr
            v-for="(item,index) in permissionList"
            :key="index"
          >
            <td class="td-title">
              <!-- 全选 -->
              <b>{{ item.name }}</b>
              <el-checkbox
                :indeterminate="isIndeterminate[item.id]"
                v-model="checkAll[item.id]"
                @change="handleCheckAllChange($event,item)"
              >
              </el-checkbox>
            </td>
            <td>
              <el-checkbox-group
                v-model="selectPermission"
              >
                <el-checkbox
                  v-for="i in item.permissions"
                  :label="i.id"
                  :key="i.id"
                  @change="handleCheckedChange($event,item)"
                >
                  {{ i.name }}
                </el-checkbox>
              </el-checkbox-group>
            </td>
          </tr>
          <tr>
            <td class="td-title">
              <b>全选</b>
              <el-checkbox
                v-model="isAllChecked"
                :indeterminate="isIndeterminateAll"
                @change="handleCheckAll"
              ></el-checkbox>
            </td>
            <td></td>
          </tr>
        </table>
      </div>
    </div>

    <div class="dialog-btn-wrap">
      <el-button @click="handleClose">
        关闭
      </el-button>
      <el-button
        @click="submit"
        type="primary"
      >
        保存
      </el-button>
    </div>
  </el-form>
</template>

<script>
import { cloneDeep, map } from 'lodash'
import { getPermissionTree, editRole } from '@/api/systemSetting/role'

export default {
  props: {
    roleItem: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      loading: true,
      visible: false, // 弹窗状态，由父集弹窗控制

      permissionList: [], // 权限列表
      selectPermission: [], // 已选择权限
      isIndeterminate: {}, // 所有模块不确定状态合集
      checkAll: {}, // 所有模块对应权限合集

      allPermissionID: [], // 所有权限id
      isAllChecked: false, // 全选
      isIndeterminateAll: false, // 全选状态
      form: {
        name: '',
        resourceIdList: []
      },
      rules: {
        name: [
          { required: true, message: '不能为空', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    handleClose () {
      this.$parent.handleClose()
    },
    reset () {
      this.$refs.form.resetFields()
    },
    submit () {
      if (this.selectPermission.length === 0) {
        this.$message.error('请至少选择一个权限')
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.editRole()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    editRole () {
      this.form.resourceIdList = this.selectPermission

      editRole(this.form).then(res => {
        this.$message.success('修改成功')
        this.reset()
        this.handleClose()
        this.$emit('updateList')
      })
    },
    async getPermissionList () {
      this.loading = true
      this.allPermissionID = []
      this.permissionList = []
      const res = await getPermissionTree()
      if (res && res.data) {
        res.data.forEach(item => {
          this.permissionList.push(item)
          item.permissions = item.children || []
          this.allPermissionID.push(item.id)
          this.allPermissionID.push(...item.permissions.map(i => i.id))
        })
      }
      this.loading = false
    },
    // 所有模块全选
    handleCheckAll (val) {
      this.selectPermission = val ? this.allPermissionID.slice(0) : []
      this.isIndeterminateAll = false

      this.permissionList.forEach(item => {
        this.isIndeterminate[item.id] = false
        this.checkAll[item.id] = val
      })
    },
    // 单模块全选
    handleCheckAllChange (val, module) {
      if (val) { // 全选
        module.permissions.forEach(item => {
          let idx = this.selectPermission.indexOf(item.id)

          if (idx < 0) {
            this.selectPermission.push(item.id)
          }
        })
      } else { // 全不选
        module.permissions.forEach(item => {
          let idx = this.selectPermission.indexOf(item.id)

          if (idx >= 0) {
            this.selectPermission.splice(idx, 1)
          }
        })
      }
      this.isIndeterminate[module.id] = false

      this.checkAllStatus()
    },
    handleCheckedChange (val, module) {
      // 交集
      let intersection = this.selectPermission.filter(val => {
        let list = module.permissions.map(i => {
          return i.id
        })
        return list.indexOf(val) >= 0
      })
      let checkedCount = intersection.length
      // 单模块全选
      this.checkAll[module.id] = checkedCount === module.permissions.length
      // 单模块不确定状态
      this.isIndeterminate[module.id] = checkedCount > 0 && checkedCount < module.permissions.length

      this.checkAllStatus()
    },
    // 全选状态判断
    checkAllStatus () {
      // 全选判断
      this.isAllChecked = this.selectPermission.length === this.allPermissionID.length
      // 全选不确定状态
      this.isIndeterminateAll = this.selectPermission.length > 0 && this.selectPermission.length < this.allPermissionID.length
    }
  },
  watch: {
    async visible (val) {
      // 获取角色列表，需要先获取所有权限再初始化状态
      val && await this.getPermissionList()
      // 重置表单
      this.reset()

      if (val && this.roleItem) {
        this.form = cloneDeep(this.roleItem)
        const { resourceList } = this.roleItem
        this.selectPermission = map(resourceList, 'id')

        this.permissionList.forEach(item => {
          const cLength = item.children ? item.children.length : 0

          if (cLength > 0) {
            // 交集
            const hasOne = item.children.some(i => this.selectPermission.includes(i.id))
            const hasAll = item.children.every(i => this.selectPermission.includes(i.id))
            // 单模块全选
            this.checkAll[item.id] = !!hasAll
            // 单模块不确定状态
            this.isIndeterminate[item.id] = !hasAll && hasOne
          }
        })

        this.checkAllStatus()
      }
    }
  }
}
</script>

<style lang="scss" scoped>

.table {
  border-collapse: collapse; width: 100%; margin-bottom: 20px;
  td {
    border: 1px solid #ddd; padding:10px 20px;
  }
  .td-title{
    text-align: right; width: 100px;
  }
}

</style>
