<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="80px">
      <el-form-item label="员工姓名">
        <el-select v-model="dataForm.staffId" prop="staffId" placeholder="请选择" clearable filterable>
          <el-option
            v-for="item in staffs"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="员工角色">
        <el-select v-model="dataForm.departmentLevel" placeholder="请选择" clearable filterable>
          <el-option
            v-for="item in departmentLevels"
            :key="item.id"
            :label="item.departmentLevel"
            :value="item.departmentLevel">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="审批目标角色">
        <el-select v-model="dataForm.targetRole" placeholder="请选择" clearable filterable>
          <el-option
            v-for="item in targetRoles"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="审批业绩角色">
        <el-select v-model="dataForm.resultRole" placeholder="请选择" clearable filterable>
          <el-option
            v-for="item in resultRoles"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item size="mini" label="授权">
        <el-tree
          :data="menuList"
          :props="menuListTreeProps"
          node-key="menuId"
          ref="menuListTree"
          :default-expand-all="true"
          :default-checked-keys="defaultCheckedKeys"
          :filter-node-method="filterNode"
          show-checkbox
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
          </span>
        </el-tree>
      </el-form-item>


    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>


<script>
import {apiSysRoleInfo, apiSysMenuList, apiSysRoleList, apiSysRoleConfirm} from '@/api/api_staff_role'
import {treeDataTranslate} from '@/utils'

export default {
  data () {
    return {
      visible: false,
      staffs: [],
      targetRoles: [],
      resultRoles: [],
      departmentLevels: [{
        id: 1,
        departmentLevel: 'HR'
      }, {
        id: 2,
        departmentLevel: 'BOSS'
      }],
      lzStaffRole: {},
      menuList: [],
      menuListTreeProps: {
        label: 'name',
        children: 'children'
      },
      tempKey: -666666, // 临时key, 用于解决tree半选中状态项不能传给后台接口问题. # 待优化
      defaultCheckedKeys: [],
      dataForm: {
        staffId: '',
        departmentLevel: '',
        targetRole: '',
        resultRole: ''
      },
      dataRule: {
        staffId: [
          { required: true, message: '员工名称不能为空', trigger: 'blur' }
        ],
        departmentLevel: [
          { required: true, message: '请选择HR或BOSS', trigger: 'blur' }
        ],
        targetRole: [
          { required: true, message: '请选择目标角色', trigger: 'blur' }
        ],
        resultRole: [
          { required: true, message: '请选择月未总结角色', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async init (id) {
      this.dataForm.id = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.dataForm.staffId = ''
        this.dataForm.departmentLevel = ''
        this.dataForm.targetRole = ''
        this.dataForm.resultRole = ''
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getDataList()
        }
      })
      await this.handleGetSysMenuList()
      await this.handleEdit()
    },
    // 获取数据列表
    async getDataList () {
      const data = await apiSysRoleInfo(this.dataForm.id)
      if (data && data.code === 0) {
        this.staffs = data.staffs
        this.lzStaffRole = data.lzStaffRole
        this.dataForm.staffId = data.lzStaffRole.staffId
        this.dataForm.departmentLevel = data.lzStaffRole.departmentLevel
        this.targetRoles = data.targetRoles
        this.resultRoles = data.targetRoles
        let d = JSON.parse(data.lzStaffRole.typeRoleIds)
        this.dataForm.targetRole = d.type1
        this.dataForm.resultRole = d.type2
      }
    },
    // 获取权限列表
    async handleGetSysMenuList () {
      let res = await apiSysMenuList({})
      this.menuList = treeDataTranslate(res, 'menuId')
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.$refs.menuListTree.setCheckedKeys([])
      })
    },
    filterNode (value, data) {
      data.disabled = true
      return value.includes(data.menuId)
    },
    // 编辑
    handleEdit () {
      apiSysRoleList({}, `/${this.dataForm.id}`).then(res => {
        if (res && res.code === 0) {
          this.dataForm = Object.assign({}, this.dataForm, res.role)
          var idx = res.role.menuIdList.indexOf(this.tempKey)
          if (idx !== -1) {
            res.role.menuIdList.splice(idx, res.role.menuIdList.length - idx)
          }
          if (this.disable) {
            this.$refs.menuListTree.filter(res.role.menuIdList)
          }
          this.defaultCheckedKeys = res.role.menuIdList
        }
      })
    },
    // 提交
    dataFormSubmit () {
      if (this.disable) {
        this.visible = false
        return
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let params = {
            'id': this.dataForm.id,
            'menuIdList': [].concat(this.$refs.menuListTree.getCheckedKeys(), [this.tempKey], this.$refs.menuListTree.getHalfCheckedKeys()),
            'staffId': this.dataForm.staffId,
            'departmentLevel': this.dataForm.departmentLevel,
            'targetRole': this.dataForm.targetRole,
            'resultRole': this.dataForm.resultRole
          }
          apiSysRoleConfirm(params, this.apiType).then(res => {
            if (res && res.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    }
  }
}
</script>
