<template>
  <Dialog
    :is-dialog-exist="showDialog"
    :dialog-style="dialogStyle"
    title="权限管理"
    @close-dialog="closeDialog"
  >
    <el-container>
      <el-form>
        <el-main>
          <!-- 权限管理table -->
          <el-table :data="permissionData"
                    border
                    :span-method="objectSpanMethod"
                    style="width: 100%; margin-top: 20px">
            <el-table-column label="一级标题"
                             width="170">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.parentCheckAll" style="color: #1890FF;" @change="handleOneCheckAllChange(scope.row)">{{ scope.row.title }}</el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="二级标题"
                             width="150">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.checkAll" @change="handleTwoCheckAllChange(scope.row)">{{ scope.row.subTitle }}</el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="权限">
              <template slot-scope="scope">
                <el-checkbox v-for="(item, index) in scope.row.permissionList" :key="index" v-model="item.check" :label="item.url" @change="handleCheckedItemChange">{{ item.title }}</el-checkbox>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
        <el-footer height="10%">
          <el-button type="primary" style=" margin-right: 27px;" @click="submitForm('selectItem')">确定</el-button>
          <el-button type="info" plain @click="resetForm('selectItem')">重置</el-button>
        </el-footer>
      </el-form>
    </el-container>

    <!--  短信校验  -->
    <VerifySmsDialog
      :dialog-show="isSafeDialogVisible"
      :get-sms-url="safeGetSmsUrl"
      @closeDialog="isSafeDialogVisible = false"
      @smsCodeCallBack="smsCodeCallBack"
    ></VerifySmsDialog>

  </Dialog>
</template>

<script>
import Dialog from '@/components/Dialog/index'
import VerifySmsDialog from '@/components/VerifySmsDialog/index'
import { fetchPermissionList, permissionSave } from '@/api/system-manage/permission-manage/permission-setting'

/**
 * 权限管理Dialog
 *
 * */
export default {
  components: {
    Dialog,
    VerifySmsDialog
  },
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    dialogStyle: {
      type: Object,
      default: () => {}
    },
    selectItem: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      isSafeDialogVisible: false,
      safeGetSmsUrl: '/admin/Role/sendSms',
      tempIndex: [],
      permissionData: [
        // 数据格式
        // {
        //   title: '', // 一级标题
        //   key: '',   // 一级标题的key
        //   subTitle: '',  // 二级标题
        //   subKey: '',  //  二级标题的key
        //   permissionList: [
        //    title: '',
        //    url: '',
        //    check: false
        //   ], // 权限展示
        //   // 是否全部选中
        //   checkAll: false,   // 二级标题是否全选
        //   isIndeterminate: false,
        //   parentCheckAll: false,  // 一级标题是否全选
        //   parentIsIndeterminate: false,
        //   // 选中的item
        //   permissionCheckList: []  // 选中的权限
        // }
      ]
    }
  },
  watch: {
    // 用于更新每次打开Dialog
    selectItem: function(val) {
      this.updateData()
    }
  },
  created() {
    console.log('permission manage create')
    this.fetchBaseInfo()
  },
  methods: {
    // 一级标题全选
    handleOneCheckAllChange(row) {
      console.log('一级标题全选 = ' + row.parentCheckAll)
      // 修改一级标题下的所有选中状态
      this.permissionData.map(firstItem => {
        if (firstItem.key === row.key) {
          firstItem.permissionList.map(secondItem => {
            secondItem.check = row.parentCheckAll
          })
          firstItem.checkAll = row.parentCheckAll
          firstItem.parentCheckAll = row.parentCheckAll
        }
      })
    },
    // 二级标题全选
    handleTwoCheckAllChange(row) {
      console.log('二级标题全选' + row.subKey + ', title' + row.subTitle + ', 二级标题是否全选 = ' + row.checkAll)
      const selectSubKey = row.subKey
      // 修改子选项选中状态
      this.permissionData.map(firstItem => {
        if (firstItem.subKey === selectSubKey) {
          firstItem.permissionList.map(secondItem => {
            secondItem.check = row.checkAll
          })
        }
      })
      // 修改一级标题选中状态
      this._updateFirstTitleCheckState()
    },
    // 权限单选
    handleCheckedItemChange() {
      console.log('权限单选')
      this._updateSecondTitleCheckState()
      this._updateFirstTitleCheckState()
    },
    // 验证码返回
    smsCodeCallBack(smsCode) {
      this.save(smsCode)
    },
    // 提交表单，保存
    submitForm() {
      this.save(null)
    },
    // 重置表单
    resetForm(formName) {
      this.updateData()
    },
    // 关闭dialog
    closeDialog() {
      this.$emit('closeDialog')
    },
    // 操作成功
    successCallBack() {
      this.$emit('successCallBack')
    },
    // 更新数据
    updateData() {
      const tempSelectPermission = this.selectItem.permission !== null && this.selectItem.permission !== undefined && this.selectItem.permission.length > 0 ? JSON.parse(this.selectItem.permission) : []
      console.log('传进来的数据 = ' + tempSelectPermission.length)
      this.permissionData.map(firstItem => {
        firstItem.permissionList.map(secondItem => {
          secondItem.check = tempSelectPermission.length > 0 ? tempSelectPermission.filter(filterItem => filterItem === secondItem.url).length > 0 : false
        })
      })
      // 二级标题是否全选
      this._updateSecondTitleCheckState()
      // 一级标题是否全选
      this._updateFirstTitleCheckState()
    },
    // 修改二级标题选中状态
    _updateSecondTitleCheckState() {
      this.permissionData.map(firstItem => {
        let subTitleSelectCount = 0
        firstItem.permissionList.map(secondItem => {
          subTitleSelectCount = secondItem.check ? subTitleSelectCount + 1 : subTitleSelectCount
        })
        firstItem.checkAll = subTitleSelectCount === firstItem.permissionList.length
      })
    },
    // 修改一级标题的选中状态
    _updateFirstTitleCheckState() {
      const firstTitleAllCheckState = {}
      // 一级标题子项选中的个数
      let tempFirstSelectCount = 0
      // 一级标题总共的个数
      let tempFirstCount = 0
      let lastKey = null
      this.permissionData.forEach(firstItem => {
        if (lastKey !== firstItem.key) {
          tempFirstSelectCount = 0
          tempFirstCount = 0
        }
        lastKey = firstItem.key
        firstItem.permissionList.forEach(secondItem => {
          tempFirstSelectCount = secondItem.check ? tempFirstSelectCount + 1 : tempFirstSelectCount
          tempFirstCount++
          firstTitleAllCheckState[lastKey] = [tempFirstSelectCount, tempFirstCount]
        })
      })
      this.permissionData.map(firstItem => {
        const firstTitleItemCheckState = firstTitleAllCheckState[firstItem.key]
        firstItem.parentCheckAll = firstTitleItemCheckState[0] === firstTitleItemCheckState[1]
      })
    },
    // 合并算法
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) { // 用于合并的列
        // 合并开始的行号
        return {
          rowspan: this.tempIndex[rowIndex],
          colspan: 1
        }
      }
    },
    // 保存
    save(smsCode) {
      console.log('保存 roleId = ' + this.selectItem.id)
      const reqPermissionList = []
      this.permissionData.forEach(firstItem => {
        firstItem.permissionList.forEach(secondItem => {
          if (secondItem.check) {
            reqPermissionList.push(secondItem.url)
          }
        })
      })
      const request = {
        code: smsCode,
        roleId: this.selectItem.id,
        permissionList: reqPermissionList
      }
      permissionSave(request).then(resp => {
        if (parseInt(resp.code) === 0) {
          this.isSafeDialogVisible = false
          this.$message.success('操作成功')
          this.successCallBack()
        } else if (parseInt(resp.code) === 401) {
          this.$message.error(resp.msg)
          this.isSafeDialogVisible = true
        } else {
          this.$message.error(resp.msg)
        }
      })
    },
    // 获取基础数据
    fetchBaseInfo() {
      // 当前的数据
      this.permissionData = []
      fetchPermissionList().then(resp => {
        if (parseInt(resp.code) === 0) {
          resp.data.forEach((item) => {
            item.groupList.forEach((groupItem) => {
              const tempPermissionList = []
              groupItem.permissionList.forEach((permissionItem) => {
                tempPermissionList.push({
                  title: permissionItem.title,
                  url: permissionItem.url.toString().toLowerCase(),
                  check: false
                })
              })

              const obj = {
                title: item.title,
                key: item.key,
                subTitle: groupItem.title,
                subKey: groupItem.key,
                permissionList: tempPermissionList,
                // 是否全部选中
                checkAll: false,
                isIndeterminate: false,
                parentCheckAll: false,
                parentIsIndeterminate: false,
                // 选中的item
                permissionCheckList: []
              }
              this.permissionData.push(obj)
            })
          })

          // 处理合并行数 每个key的第一行都会合并，合并的行数等于key的总条数，其它情况不合并
          this.tempIndex = []
          let pos
          this.permissionData.forEach((item, index) => {
            if (index === 0) {
              this.tempIndex.push(1)
              pos = 0
            } else {
              if (item.key === this.permissionData[index - 1].key) {
                this.tempIndex[pos] += 1
                this.tempIndex.push(0)
              } else {
                this.tempIndex.push(1)
                pos = index
              }
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-container {
    width: 100%;
    height: 100%;
    .el-form {
      height: 100%;
      width: 100%;
      /*background: yellow;*/
      .el-main {
        height: 90%;
        /*.el-checkbox__input.is-checked + .el-checkbox__label {*/
        /*  color: #606266;*/
        /*}*/

      }
      .el-footer {
        /*background: red;*/
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
</style>
