<template>
  <div class="authority commonFont">
    <div>
      <div class="authority-main line-space">
        <div class="authority-main-header">
          <div class="comonTitle">智能绩效主管理员</div>
          <el-button
            type="primary"
            size="small"
            plain
            @click="handleChangeDirector"
          >更换智能绩效主管理员</el-button>
        </div>
        <div class="comonPrompt">绩效应用的主管理员，可由钉钉主管理员设置，绩效主管理员具有应用所有权限，且可以设置智能绩效应用子管理员</div>
        <div class="authority-main-info">
          <el-avatar
            icon="el-icon-user-solid"
            :size="40"
            :src="mainData.masterFirst.headerUrl?mainData.masterFirst.headerUrl:''"
          ></el-avatar>
          <div class="authority-main-info-name">{{mainData.masterFirst.name}}</div>
        </div>
      </div>
      <div class="authority-sub line-space">
        <div class="authority-sub-header">
          <div class="comonTitle">智能绩效子管理员</div>
          <el-button
            type="primary"
            size="small"
            @click="handleSubAdd"
            icon="el-icon-plus"
            plain
          >添加</el-button>
        </div>
        <div class="comonPrompt line-space">可把绩效应用的日常管理工作交给绩效子管理员，绩效子管理员可由绩效主管理员设置</div>
        <el-table
          :data="mainData.childPm.list"
          :header-cell-style="handleSubGetTableStyle"
          :cell-style="handleSubGetTableCellStyle"
          max-height="500px"
        >
          <el-table-column
            width="50px"
            align="center"
          >
            <template slot-scope="scope">
              <el-avatar
                icon="el-icon-user-solid"
                :size="40"
                :src="scope.row.headerUrl?scope.row.headerUrl:''"
              ></el-avatar>
            </template>
          </el-table-column>
          <el-table-column
            label="姓名"
            prop="name"
            align="left"
            width="100px"
          >
          </el-table-column>
          <el-table-column
            label="功能模块"
            align="center"
          >
            <template slot-scope="scope">
              {{handleGetChildeModel(scope.row.functionModel)}}
            </template>
          </el-table-column>
          <el-table-column
            label="管理范围"
            align="center"
          >
            <template slot-scope="scope">{{handleGetChildeMangeRange(scope.row)}}</template>
          </el-table-column>
          <el-table-column
            label="是否可见考核结果"
            align="center"
          > <template slot-scope="scope">{{scope.row.canSee===0?'不可见':'可见'}}</template></el-table-column>
          <el-table-column
            label="菜单权限"
            align="center"
          >
            <template slot-scope="scope">
              {{scope.row.menuId===0?'全部权限':'部分权限'}}
            </template>
          </el-table-column>
          <el-table-column
            label="管理考评组"
            align="center"
          >
            <template slot-scope="scope">
              {{scope.row.evaluationGroupId===0?'全部考评组权限':'特定考评组权限'}}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                @click="handleChildEdit(scope.row)"
                type="text"
                size="small"
              >编辑</el-button>
              <el-button
                @click="handleChildDelete(scope.row)"
                type="text"
                size="small"
              >删除</el-button>

            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          :hide-on-single-page="true"
          :current-page.sync="rqInfoParameter.currPage"
          :page-size="rqInfoParameter.pageSize"
          :total="rqInfoParameter.totalCount"
          :page-count="rqInfoParameter.totalPage"
          @current-change="handleCurrentChange"
          layout="total, prev, pager, next, jumper"
        ></el-pagination>

      </div>
      <div class="authority-ceo line-space comonPrompt">
        <div class="comonTitle line-space">企业负责人</div>
        <div>企业负责人可以看到全公司的绩效数据，可由钉钉主管理员在通讯录设置</div>
        <div
          v-if="mainData.boss.length>0"
          class="authority-ceo-info"
        >
          <div
            v-for="(item, index) in mainData.boss"
            :key="index"
            class="authority-ceo-info-item"
          >
            <el-avatar
              icon="el-icon-user-solid"
              :size="40"
              :src="item.headerUrl?item.headerUrl :''"
            ></el-avatar>
            <span class="authority-main-info-name">{{item.name}}</span>
          </div>
        </div>
      </div>
      <div class="authority-department line-space">
        <div class="comonTitle line-space">部门主管</div>
        <div class="comonPrompt">部门主管可看到管理部门的绩效数据，可由钉钉管理员在钉钉通讯录设置</div>
      </div>
      <div class="authority-employee line-space">
        <div class="comonTitle line-space">员工</div>
        <div class="comonPrompt">员工仅可见自己的绩效数据</div>
      </div>
    </div>

    <dialog-personnel
      v-if="showDialogPersonnel"
      :title="dialogPersonnelTitle"
      :len=1
      :isShow.sync='showDialogPersonnel'
      @cb="handleDialogSubmitDepart"
    ></dialog-personnel>
    <dialog-depart
      v-if="showDialogDepart"
      :isShow.sync='showDialogDepart'
      :showDataList.sync='popupFromSub.shwoDepartData'
    />
    <popup-right
      v-if="showPopupAddSub"
      @cancel="showPopupAddSub = false"
      @submit="handlePopupAddSubSubmit"
      title="智能绩效子管理员设置"
      class="popup"
    >
      <div slot="content">
        <el-form
          :model="popupFromSub"
          label-width="110px"
          label-suffix="："
          label-position="left"
          size="small"
        >
          <el-form-item label="子管理员">
            <div
              v-if="popupFromSub.subPersonData"
              class="line-space"
            >
              <el-tag size="small">{{popupFromSub.subPersonData.title}}</el-tag>
            </div>
            <div v-if="!popupSubMngEdit">
              <el-button
                type="primary"
                size="small"
                plain
                @click="handlePopupChooseSub"
              >请选择</el-button>
            </div>
          </el-form-item>
          <el-form-item
            label="功能模块"
            label-width="90px"
          >
            <el-col :span="1">
              <el-tooltip
                class="item"
                effect="dark"
                content="分别控制管理员有1.发起绩效考核的权限"
                placement="bottom"
              >
                <i class="el-icon-info" />
              </el-tooltip>
            </el-col>
            <el-col :span="11">
              <el-checkbox
                v-model="popupFromSub.featuresCheck"
                @change="popupFromSub.featuresCheck=true"
              >绩效考核</el-checkbox>
              <!-- <el-checkbox-group
                v-model="popupFromSub.featuresChckList"
                @change="handlePopupCheckModel"
              >
                <el-checkbox label="0">OKR</el-checkbox>
                <el-checkbox label="1">绩效考核</el-checkbox>
              </el-checkbox-group> -->
            </el-col>
          </el-form-item>
          <div v-if="popupFromSub.showChoosePerformance">
            <el-form-item
              label="管理范围"
              label-width="90px"
            >
              <el-col :span="1">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="管理员能查看和管理那些员工的绩效考核（非OKR）"
                  placement="bottom"
                >
                  <i class="el-icon-info" />
                </el-tooltip>
              </el-col>
              <el-col :span="23">
                <el-col :span="10">
                  <el-radio-group v-model="popupFromSub.radioScope">
                    <el-radio :label="0">全公司</el-radio>
                    <el-radio :label="1">所在部门及以下部门</el-radio>
                    <el-radio :label="2">特定部门</el-radio>
                  </el-radio-group>
                </el-col>
                <el-col
                  :span="24"
                  v-if="popupFromSub.radioScope===2"
                >
                  <el-tag
                    v-for="tag in popupFromSub.shwoDepartData.list"
                    :key="tag.departmentId"
                    closable
                    @close="handleDeleteScopeSubDepte"
                    size="small"
                  >
                    {{tag.departmentName}}
                  </el-tag>
                </el-col>
                <el-col
                  :span="10"
                  v-if="popupFromSub.radioScope===2"
                >
                  <el-button
                    type="primary"
                    plain
                    size="small"
                    @click="showDialogDepart = true"
                  >请选择</el-button>
                </el-col>
              </el-col>
            </el-form-item>
            <!-- <el-form-item label="是否可见考核结果">
              <el-switch v-model="popupFromSub.resultsVisible"></el-switch>
            </el-form-item> -->
            <el-form-item label="菜单权限">
              <div>
                <el-checkbox
                  v-model="popupFromSub.menuCheckAllState"
                  @change="handleMenuCheckAllChange"
                >全部权限</el-checkbox>
              </div>
              <el-checkbox-group
                v-model="popupFromSub.menuCheckData"
                @change="handleMenuChange"
              >
                <div>
                  <el-checkbox
                    @change="handleMenuMngCheckAllChange"
                    :label="2"
                  >考核管理</el-checkbox>
                  <el-checkbox-group
                    class="popup-menu-mange-group"
                    v-model="popupFromSub.menuMngCheck"
                  >
                    <el-checkbox
                      :label="15"
                      :disabled="popupFromSub.menuCheckData.indexOf(2)<0?true:false"
                    >发起考核</el-checkbox>
                    <el-checkbox
                      :label="16"
                      :disabled="popupFromSub.menuCheckData.indexOf(2)<0?true:false"
                    >开始评分</el-checkbox>
                  </el-checkbox-group>
                </div>
                <div>
                  <el-checkbox :label="21">考评组</el-checkbox>
                </div>
                <div>
                  <el-checkbox :label="23">绩效报表</el-checkbox>
                </div>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item
              v-if="popupFromSub.menuCheckData.indexOf(2)>-1"
              label="考评组权限"
            >
              <div>
                <el-radio
                  v-model="popupFromSub.groupRadio"
                  label="0"
                >全部考评组</el-radio>
              </div>
              <div>
                <el-radio
                  v-model="popupFromSub.groupRadio"
                  label="1"
                >特定考评组</el-radio>
              </div>
              <div v-if="popupFromSub.groupRadio ==='1'">
                <div class="line-space">
                  <el-tag
                    v-for="item in popupFromSub.assessmentList"
                    :key="item.id"
                    closable
                    @close="handlePopupCloseAssessment"
                    size="small"
                  >
                    {{item.name}}
                  </el-tag>
                </div>
                <div>
                  <el-button
                    type="primary"
                    plain
                    @click="dialogVisibleTeamFilter = true"
                  >请选择</el-button>
                </div>
              </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </popup-right>
    <ChooseInitiate
      @cb='handleCallBackChoose'
      popupRightTitle='选择考评组'
      :oldSelectedList='popupFromSub.assessmentList'
      :showChooseList.sync="dialogVisibleTeamFilter"
    />
  </div>
</template>

<script>
import dialogPersonnel from '@/components/getPersonnel'
import popupRight from '@/components/PopupRight'
import dialogDepart from '@/components/getDepart'
import ChooseInitiate from '@/components/ChooseInitiate'

import { apiSetPermissionsInfo, apiSetPermissionsRoleChange, apiSetPermissionsRoleDelete, apiSetPermissionsRoleDetail } from '@/api/setPermissions'
import invokeThingService$ from 'dingtalk-jsapi/api/biz/iot/invokeThingService'

export default {
  components: {
    dialogPersonnel,
    popupRight,
    dialogDepart,
    ChooseInitiate
  },
  data () {
    return {
      dialogPersonnelTitle: '更换智能绩效主管理员',
      showDialogPersonnel: false, // 显示 变更/添加人员
      showPopupAddSub: false, // 显示添加子管理员
      showDialogDepart: false, // 选择部门
      dialogVisibleTeamFilter: false, // 选择考评组
      popupSubMngEdit: false, // 子管理员 false 添加 true 编辑
      menuCheckAllData: [2, 21, 23],
      menuMngCheckAll: [15, 16], // 考核管理全选
      // menuIdOrNameData: { '全部权限': 1, '考核管理': 2, '发起考核': 15, '开始评分': 16, '考评组': 21, '绩效报表': 23 },
      mainData: {
        masterFirst: {
          headerUrl: '',
          name: '',
          id: ''
        }, // 第一个主管理员
        childPm: [], // 子管理员
        masterPM: [], // 主管理员
        boss: []// 老板
      },
      popupFromSub: {
        id: '', // 权限id
        featuresCheck: true,
        subPersonData: null, // 选中要添加的子管理员
        shwoDepartData: {
          title: '',
          list: []
        }, // 指定部门
        featuresChckList: ['0', '1'], // 功能模块
        showChoosePerformance: true, // 绩效考核
        radioScope: 0, //  管理范围
        resultsVisible: true, // 结果是否可见
        menuCheckAllState: true, // 菜单权限是否全选
        menuCheckData: [], // 菜单选中
        menuMngCheck: [], // 考核管理
        groupRadio: '0', // 考评组选择  0 全部考评组 1 特定考评组
        assessmentList: [] // 选中的考评组
      },
      rqInfoParameter: {
        currPage: 1,
        pageSize: 10,
        totalCount: 1,
        totalPage: 1
      }
    }
  },
  created () {
    this.handleGetSetPageInfo()
  },
  watch: {
    'showPopupAddSub': function (newVal, oldVal) {
      console.log('showPopupAddSub==--===', newVal, oldVal)
      if (!newVal) {
        this.popupSubMngEdit = false
        this.popupFromSub = {
          id: '', // 权限id
          subPersonData: null, // 选中要添加的子管理员
          shwoDepartData: {
            title: '',
            list: []
          }, // 指定部门
          featuresCheck: true,
          featuresChckList: ['0', '1'], // 功能模块
          showChoosePerformance: true, // 绩效考核
          radioScope: 0, //  管理范围
          resultsVisible: true, // 结果是否可见
          menuCheckAllState: true, // 菜单权限是否全选
          menuCheckData: [], // 菜单选中
          menuMngCheck: [], // 考核管理
          groupRadio: '0', // 考评组选择  0 全部考评组 1 特定考评组
          assessmentList: [] // 选中的考评组
        }
      }
    }
  },
  methods: {
    handleGetChildeModel (type) {
      let modelStr = ''
      switch (type) {
        case 1:
          modelStr = '绩效考核'
          break
        default:
          break
      }
      return modelStr
    },
    handleGetChildeMangeRange (row) {
      let typeStr = ''
      switch (row.departmentId) {
        case 0:
          typeStr = '全公司'
          break
        case 1:
          typeStr = '所在部门及以下部门'
          break
        case 2:
          if (row.deparmentNames) {
            typeStr = row.deparmentNames.join()
          }
          break
        default:
          break
      }
      return typeStr
    },
    handleGetChildeGroupPermissions (type) {
      // 考评组权限
      let typeStr = ''
      switch (type) {
        case 0:
          typeStr = '全部考评组权限'
          break
        case 1:
          typeStr = '特定考评组权限'
          break
        default:
          break
      }
      return typeStr
    },
    handleSubGetTableStyle (row) {
      let alignStr = 'center'
      if (row.columnIndex === 1) {
        alignStr = 'left'
      }
      return { 'height': '40px', 'background-color': '#f5f4f5', 'text-align': alignStr }
    },
    handleSubGetTableCellStyle () {
      return { 'padding': '5px 0px !important' }
    },
    handleChangeDirector () {
      // 更换主管
      this.dialogPersonnelTitle = '更换智能绩效主管理员'
      this.showDialogPersonnel = true
    },
    handleChangeDirectorRg (val) {
      let msg = '是否将智能绩效主管理员变更为' + val.title
      this.$confirm(msg, '提示')
        .then(_ => {
          let dicPara = {
            departmentLevel: 'MASTER_PM',
            staffId: val.value
          }
          apiSetPermissionsRoleChange(dicPara).then(res => {
            if (res.code === 200) {
              this.showDialogPersonnel = false
              this.$router.push({ name: 'workbench-home' })
            } else {
              this.$message.error(res.msg)
            }
          })
        })
        .catch(_ => { })
    },
    // 更换主管理员/添加子管理员
    handleDialogSubmitDepart (val) {
      if (val.list.length <= 0) {
        let msg = this.showPopupAddSub ? '请选择子管理员' : '请选择主管理员'
        this.$message({
          showClose: true,
          message: msg,
          type: 'error'
        }); return
      }
      if (this.showPopupAddSub) {
        // 添加子管理员
        this.popupFromSub.subPersonData = val
        this.showDialogPersonnel = false
      } else {
        this.handleChangeDirectorRg(val)
      }
      console.log('handleDialogSubmitDepart==  ', val)
    },
    handleSubAdd () {
      this.popupFromSub.menuCheckData = this.menuCheckAllData
      this.popupFromSub.menuMngCheck = this.menuMngCheckAll
      this.showPopupAddSub = true
    },
    handleCurrentChange (val) {
      // 页面切换
      this.rqInfoParameter.currPage = val
      this.handleGetSetPageInfo()
    },
    handleChildEdit (row) {
      this.popupSubMngEdit = true
      this.showPopupAddSub = true
      // 获取权限列表
      console.log('编辑-----=====', row)
      apiSetPermissionsRoleDetail({ id: row.id }).then(res => {
        if (res.code !== 200) {
          return
        }
        this.showPopupAddSub = true
        const data = res.data
        this.popupFromSub.id = row.id
        this.popupFromSub.subPersonData = { title: row.name, value: row.staffId }
        this.popupFromSub.radioScope = data.departmentId // 管理范围
        this.popupFromSub.shwoDepartData.list = data.departmentInfos // 指定部门
        this.popupFromSub.evaluationGroupId = data.evaluationGroupId // 考评组
        this.popupFromSub.assessmentList = data.departmentInfos
        this.popupFromSub.menuCheckAllState = false //  全选中状态
        console.log('selectStaffMenuInfos====', data.selectStaffMenuInfos)
        let selectStaffMenuInfos = data.selectStaffMenuInfos ? data.selectStaffMenuInfos : []
        selectStaffMenuInfos.forEach(item => {
          switch (item) {
            case 1:
              this.popupFromSub.menuCheckAllState = true
              break
            case 2:
            case 21:
            case 23:
              console.log('item ======', item)
              if (this.popupFromSub.menuCheckData.indexOf(item) < 0) {
                this.popupFromSub.menuCheckData.push(item)
              }
              break
            case 15:
            case 16:
              if (this.popupFromSub.menuMngCheck.indexOf(item) < 0) {
                this.popupFromSub.menuMngCheck.push(item)
              }
              break
            default:
              break
          }
        })
        if (this.popupFromSub.menuCheckData.indexOf(2) < 0) {
          this.popupFromSub.menuMngCheck = []
        }
        console.log('编辑====', this.popupFromSub)
        // console.log('权限详情---', res)
      })
    },
    handleChildDelete (row) {
      // 删除子管理员
      this.$confirm('确认删除该管理员，删除后该子管理员将失去智能绩效的子管理员权限', '提示').then(_ => {
        console.log('删除子管理员', row)
        apiSetPermissionsRoleDelete({ id: row.id }).then(res => {
          if (res.code === 200) {
            // 删除成功
            this.$message({
              message: '删除子管理成功',
              type: 'success'
            }) // 刷新页面信息
            this.rqInfoParameter.currPage = 1
            this.handleGetSetPageInfo()
          }
        })
      }).catch(_ => {

      })
    },
    handlePopupAddSubSubmit () {
      if (!this.popupFromSub.subPersonData) {
        this.$message.error('请选择子管理员')
      } else if (this.popupFromSub.featuresChckList.length <= 0) {
        this.$message.error('至少选择一个权限类型')
      } else {
        // 数据正确    进行整理
        // 考评组id
        const assessmentIdsStr = this.popupFromSub.assessmentList.map((item, index) => {
          return item.id
        }).join(',')
        const departmentInfoStr = this.popupFromSub.shwoDepartData.list.map((item, index) => {
          return item.departmentId
        }).join(',')
        // 菜单id
        let menuIdStr = ''
        let menuCheckList = this.popupFromSub.menuCheckData.concat(this.popupFromSub.menuMngCheck)
        if (this.popupFromSub.menuCheckAllState) {
          //  添加权限
          menuCheckList.push('1')
        }
        menuIdStr = menuCheckList.join(',')
        let paraDic = {
          id: this.popupFromSub.id,
          staffId: this.popupFromSub.subPersonData.value,
          departmentId: this.popupFromSub.radioScope, // 管理范围
          departmentInfoStr: departmentInfoStr,
          evaluationGroupId: this.popupFromSub.groupRadio, // 考评组
          evaluationGroupInfoStr: assessmentIdsStr,
          selectStaffMenuInfoStr: menuIdStr, // 选中的菜单权限
          departmentLevel: 'CHILD_PM'
        }
        apiSetPermissionsRoleChange(paraDic).then(res => {
          if (res.code === 200) {
            this.showPopupAddSub = false
            // 管理员权限  修改成功
            this.handleGetSetPageInfo()
          }
        })
      }

      // this.popupFromSub.subPersonData
      // this.showPopupAddSub = false
    },
    handlePopupChooseSub () {
      //  选择子管理员
      this.dialogPersonnelTitle = '选择成员'
      this.showDialogPersonnel = true
    },
    handlePopupCheckModel (val) {
      console.log(val.indexOf('1'))
      this.popupFromSub.showChoosePerformance = val.indexOf('1') > -1
      // 功能模块
    },
    handleDeleteScopeSubDepte (tag) {
      // 移除选中部门
      this.popupFromSub.shwoDepartData.list.splice(this.popupFromSub.shwoDepartData.list.indexOf(tag), 1)
    },
    // 菜单权限
    handleMenuCheckAllChange (val) {
      // 菜单权限  是否权限
      this.popupFromSub.menuCheckData = val ? this.menuCheckAllData : []
      this.popupFromSub.menuMngCheck = val ? this.menuMngCheckAll : []
    },
    handleMenuChange (val) {
      // 菜单选项变更
      this.popupFromSub.menuCheckAllState = this.menuCheckAllData.length === this.popupFromSub.menuCheckData.length
    },
    handleMenuMngCheckAllChange (val) {
      // 考核管理  全选
      if (val) {
        // 选中
        this.popupFromSub.menuMngCheck = this.menuMngCheckAll
      } else {
        this.popupFromSub.menuMngCheck = []
      }
    },
    handleCallBackChoose (val) {
      // 特定考评组选择
      this.popupFromSub.assessmentList = val.list
      this.dialogVisibleTeamFilter = false
      console.log('特定考评组选择 ', val, this.dialogVisibleTeamFilter)
    },
    handlePopupCloseAssessment (item) {
      this.popupFromSub.assessmentList.splice(this.popupFromSub.assessmentList.indexOf(item), 1)
    },
    handleGetSetPageInfo () {
      let rqDic = {
        currPage: this.rqInfoParameter.currPage,
        pageSize: this.rqInfoParameter.pageSize
      }
      apiSetPermissionsInfo(rqDic).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.msg)
          return
        }
        this.rqInfoParameter.currPage = res.data.childPm.currPage
        this.rqInfoParameter.totalCount = res.data.childPm.totalCount
        this.rqInfoParameter.totalPage = res.data.childPm.totalPage
        this.mainData.masterFirst = res.data.masterPM.length > 0 ? res.data.masterPM[0] : {}
        this.mainData.childPm = res.data.childPm
        this.mainData.boss = res.data.boss
        this.masterPM = res.data.masterPM
        console.log('权限设置页面====---', res)
      })
    }
  }
}
</script>
<style lang="less" scoped>
.authority {
  background-color: white;
  padding-top: 40px;
  .line-space {
    margin-bottom: 10px;
  }
  &-main {
    &-header {
      display: flex;
      width: 100%;
      justify-content: space-between;
    }
    &-info {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      height: 72px;
      width: 100%;
      &-name {
        margin-left: 10px;
      }
    }
  }
  &-sub {
    &-header {
      display: flex;
      width: 100%;
      justify-content: space-between;
    }
    .el-pagination {
      margin-top: 10px;
      text-align: right;
    }
  }
  &-ceo {
    align-content: start;
    &-info {
      display: flex;
      height: 72px;
      &-item {
        display: flex;
        width: 100px;
        align-content: center;
        align-items: center;
      }
    }
  }
  .popup {
    .el-radio-group {
      line-height: inherit !important;
      padding-top: 5px;
    }
    .el-tag {
      margin-right: 10px;
      margin-bottom: 5px;
    }
  }
  .popup-menu-mange-group {
    width: 300px;
    padding: 5px 15px;
    background-color: #f9f9f9;
  }
}
</style>
