<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
          :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.code]"
                v-model="checkAll[item.code]"
                @change="handleCheckAllChange($event,item)"
              >
              </el-checkbox>
            </td>
            <td>
              <el-checkbox-group
                v-model="resourceIdList"
              >
                <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="reset">
        重置
      </el-button>
      <el-button
        @click="submit"
        type="primary"
      >
        保存
      </el-button>
    </div>
  </el-form>
</template>

<script>
import { getPermissionTree, addRole } from '@/api/systemSetting/role'

export default {
  data () {
    return {
      visible: false, // 弹窗状态，由父集弹窗控制

      permissionList: [], // 权限列表
      resourceIdList: [], // 已选择权限
      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()
      // 清空权限
      this.resourceIdList = []
      this.isIndeterminateAll = false
      this.isAllChecked = false

      this.permissionList.forEach(item => {
        this.isIndeterminate[item.code] = false
        this.checkAll[item.code] = false
      })
    },
    submit () {
      if (this.resourceIdList.length === 0) {
        this.$message.error('请至少选择一个权限')
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.addRole()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    addRole () {
      this.form.resourceIdList = this.resourceIdList
      addRole(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.resourceIdList = val ? this.allPermissionID.slice(0) : []
      this.isIndeterminateAll = false

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

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

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

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

      this.checkAllStatus()
    },
    // 全选状态判断
    checkAllStatus () {
      // 全选判断
      this.isAllChecked = this.resourceIdList.length === this.allPermissionID.length
      // 全选不确定状态
      this.isIndeterminateAll = this.resourceIdList.length > 0 && this.resourceIdList.length < this.allPermissionID.length
    }
  },
  watch: {
    visible (val) {
      // 获取角色列表
      val && this.getPermissionList()
      // 重置表单
      this.reset()
    }
  }
}
</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>
