<!-- @desc:员工范围权限  @auth:常皓宁  @time:2024-04-2 -->
<template>
  <div class="main-div">
    <card>
      <div style="display: flex">
        <div style="margin-right: 30px">
          用户编码：{{ staffCode }}
        </div>
        <div style="margin-right: 30px">
          用户名称：{{ staffName }}
        </div>
        <div>
          角色：{{ roleNames }}
        </div>
      </div>
    </card>

    <card ref="tableCard">
      <div class="quick-top-div">
        <el-tabs class="el-tabs-custom" v-model="tabsModel">
          <el-tab-pane :label="item.label" v-for="(item, index) of tabsOptions" :key="index" :name="item.name">
            <div>
              <div style="">
                <span style="margin-right: 10px">{{ $t('noLimit') }}</span>

                <i-switch v-model="noLimit[item.name]"></i-switch>

                <InputPop v-if="item.name !== 'PU10000003'"
                          style="width: 200px;margin-left: 10px;" v-model="orgName[tabsModel]" label="部门名称"
                          @on-clear="clearOrgName"
                          @on-keydown="(e)=>handleKeyDownPosition(e,orgName[tabsModel],item.name)"></InputPop>
                <Button v-if="item.name !== 'PU10000003'" type="primary"
                        style="margin-left: 10px;" size="small" @click="searchTable(orgName[tabsModel],item.name)">定位
                </Button>
              </div>

              <DkTree v-if="item.name !== 'PU10000003'" :ref="'treeOrg'+item.name"
                      :data="tableData[item.name]" style="margin-top: 5px"
                      show-checkbox show-expand-button show-choose-button expand-mode="all"
                      @checkbox-change="changeCheckboxRow"
                      id="orgId" parent-id="parentId" tree-node-name="orgName" :height="tableHeight-210"></DkTree>

              <div v-if="item.name == 'PU10000003'">

                <Button size="small" type="primary" @click="addStaff" style="margin: 10px 5px 10px 0">添加</Button>
                <Button size="small" type="error" @click="delStaff">删除</Button>

                <DkTable
                  ref="staff-table"
                  :pageFlag="false"
                  :height="tableHeight - 250"
                  primaryKey="staffId"
                  :data="staffList">
                  <DkTableColumn field="staffCode"></DkTableColumn>
                  <DkTableColumn field="staffName"></DkTableColumn>
                </DkTable>

                <SelectMagnifier ref="staff-m" style="display: none;" v-model="staffIds"
                                 :type="$config.MagnifierType.staff" searchType="M" @on-ok="staffOk"
                                 :other-condition="{flgValidAll: 1}"
                                 :initSearchFlag="true"/>
              </div>
            </div>

          </el-tab-pane>
        </el-tabs>
      </div>

    </card>

    <!--  下部分按钮区域  -->
    <DkSaveButton ref="saveButton" :loading="loading" @save="submitForm" @close="close"></DkSaveButton>
  </div>
</template>

<script>
// import {formMixin} from '@/mixins/form'
import {indexMixin} from '@/mixins'

export default {
  name: 'staff-purview',
  mixins: [indexMixin],
  data() {
    let self = this
    return {
      staffCode:null,
      staffName:null,
      roleNames:null,
      staffId: null,
      chooseIds: {},
      orgName: {},
      staffIds: [],
      staffList: [],
      //不限制标识
      noLimit: {},
      tableData: {},
      //模式切换
      tabsModel: null,
      //模式切换
      tabsModelID: 0,
      //渠道
      channelTableData: [],
      //业务员
      staffTableData: [],
      //查看业务部门
      viewOrganizationData: [],
      brandCheckRowKeys: () => [],
      tableHeight: 755,
      //模式
      tabsOptions: [],
      //检索索引
      currentIndex: 0,
    }

  },
  methods: {
    clearOrgName() {
      this.searchTable('')
    },
    /**
     * @desc   : 键盘点击事件
     * @author : 付斌
     * @date   : 2023-11-22 17:13
     */
    handleKeyDownPosition(e, orgName, name) {
      if (e.code === 'Enter') {
        this.searchTable(orgName, name);
      }
    },
    /**
     * @desc   : 执行定位操作
     * @author : 付斌
     * @date   : 2023-11-22 17:16
     */
    searchTable(orgName, name) {
      orgName = orgName ? orgName : ''
      let isNotSearch = true;

      // 模糊查询
      this.currentIndex = this.currentIndex + 1
      for (this.currentIndex; this.currentIndex < this.tableData[this.tabsModel].length; this.currentIndex++) {
        let it = this.tableData[this.tabsModel][this.currentIndex];
        if (it.orgName.indexOf(orgName) > -1) {
          // 定位当前行
          if (this.$refs['treeOrg' + name] && this.$refs['treeOrg' + name].length > 0) {
            this.$refs['treeOrg' + name][0].setCurrentRow(it);
            this.$nextTick(() => {
              this.$refs['treeOrg' + name][0].scrollToRow(it);
            });
            isNotSearch = false;
            break;
          }
        }
      }
      // 如果没搜到，再从头来一遍
      if (isNotSearch) {
        this.currentIndex = 0;
        for (this.currentIndex; this.currentIndex < this.tableData[this.tabsModel].length; this.currentIndex++) {
          let it = this.tableData[this.tabsModel][this.currentIndex];
          if (it.orgName.indexOf(orgName) > -1) {
            // 定位当前行
            if (this.$refs['treeOrg' + name] && this.$refs['treeOrg' + name].length > 0) {
              this.$refs['treeOrg' + name][0].setCurrentRow(it);
              this.$nextTick(() => {
                this.$refs['treeOrg' + name][0].scrollToRow(it);
              });
              isNotSearch = false;
              break;
            }
          }
        }
      }
    },
    changeCheckboxRow({row, checked}) {
      if (checked) {
        console.log('row',row)
        // 如果有子级，把子级加入
        if (row.children && row.children.length > 0) {
          row.children.forEach(it => {
            if (!this.chooseIds[this.tabsModel].includes(it.id)) {
              this.chooseIds[this.tabsModel].push(it.id)
            }
          })
        } else {
          if (!this.chooseIds[this.tabsModel].includes(row.id)) {
            this.chooseIds[this.tabsModel].push(row.id)
          }
        }
      } else {
        // 如果有子级，去掉子级勾选
        if (row.children && row.children.length > 0) {
          row.children.forEach(it => {
            this.chooseIds[this.tabsModel].splice(this.chooseIds[this.tabsModel].indexOf(it.id), 1)
          })
        } else {
          this.chooseIds[this.tabsModel] = this.chooseIds[this.tabsModel].filter(it => it !== row.id)
        }
      }
      console.log('this.chooseIds',this.chooseIds)
      // console.log('rrr', this.chooseIds[this.tabsModel])
    },
    changeCheckbox(records) {
      if (records && records.records.length > 0) {
        records.records.forEach(it => {
          this.chooseIds[this.tabsModel].push(it.id)
        })
      } else {
        this.chooseIds[this.tabsModel] = []
      }
    },
    close() {
      this.closeTag(this.$route)
    },
    addStaff() {
      this.$refs['staff-m'][0].magnifierClick()
    },
    delStaff() {
      let arr = this.$refs['staff-table'][0].batchRows
      let arrIds = this.$refs['staff-table'][0].batchKeys
      this.staffList = this.staffList.filter(it => !arrIds.includes(it.staffId))
      this.staffIds = this.staffIds.filter(it => !arrIds.includes(it))
    },
    staffOk(e) {
      this.staffList = [...e]
    },

    /**
    * @desc   : 保存
    * @author : 常皓宁
    * @date   : 2024/4/3 10:34
    */
    submitForm() {
      let params = this.tabsOptions.map(m => {
        return {
          staffId: this.staffId,
          purviewCode: m.name,
          flgNolimit: this.noLimit[m.name],
          dataIds: m.name == 'PU10000003' ? this.staffIds: this.chooseIds[m.name],
          cpId: this.$store.state.user.cpId,
        }
      })
      params.staffId = this.staffId
      console.log('params',params)
      //保存
      this.excute(this.$service.staffPurviewService, this.$service.staffPurviewService.savePurview + '/' + this.staffId,params).then(res => {
        if (res.code === 200) {
          this.$Message.success(this.$t('I_001', {'param': this.$v('save')}))
          // this.closeTag(this.$route)
          this.getPurview()
        } else {
          this.$Message.error(res.message)
        }
      })
    },

    /**
     * @desc   : 查询部门范围权限
     * @author : 常皓宁
     * @date   : 2024/4/2 9:48
     */
    getOrg() {
      let params = {
        staffId: this.staffId,
      }
      this.excute(this.$service.orgService, this.$service.orgService.selectByCond, params).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          for (let it of this.tabsOptions) {
            this.$set(this.noLimit, it.name, false)
            this.$set(this.tableData, it.name, res.data.list)
          }
          //查询范围权限
          this.$nextTick(() => {
            //查询范围权限
            this.getStaff();
          })
        } else {
          this.$Message.error(res.message)
        }
        this.loading = false
      })
    },
    /**
     * @desc   : 查询员工范围权限
     * @author : 常皓宁
     * @date   : 2024/4/2 13:24
     */
    getStaff() {
      let id = this.staffId
      return this.excuteNoParam(this.$service.staffPurviewService, this.$service.staffPurviewService.getPurview, [id], false).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          for (let it of res.data) {
            this.noLimit[it.purviewCode] = it.flgNolimit
            if (it.purviewCode === 'PU10000003') {
              this.getStaffList(it.dataIds)
              this.staffIds = it.dataIds
              this.staffList = this.$refs['staff-table'][0].options.filter(it2 => this.staffIds.includes(it2.staffId))
            } else {
              this.$refs['treeOrg' + it.purviewCode][0].setCheckboxRowByKeys(it.dataIds, 'id')
              this.chooseIds[it.purviewCode] = it.dataIds
            }
          }
        } else {
          this.$Message.error(res.message)
        }
        this.loading = false
      })
    },

    /**
     * @desc   : 查询范围权限
     * @author : 常皓宁
     * @date   : 2024/4/2 9:33
     */
    getPurview() {
      // 查询数据
      let params = {
        cpId: this.$store.state.user.cpId
      }
      let excute = this.excute(this.$service.commonService, this.$service.commonService.getPurviewType, params)
      excute.then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.tabsOptions = res.data.map(m => {
            return {label: m.name, name: m.code}
          })
          res.data.forEach(it => {
            this.$set(this.chooseIds, it.code, [])
            this.$set(this.orgName, it.code, '')
          })
          this.tabsModel = this.tabsOptions && this.tabsOptions.length > 0 ? this.tabsOptions[0].name : ''
          //查询部门范围权限
          this.getOrg()
        } else {
          this.$Message.error(res.message)
        }
        this.loading = false
      })
    },

    /**
     * @desc   : 查询员工
     * @author : 常皓宁
     * @date   : 2024/4/2 15:27
     */
    getStaffList(idList) {
      let params = {
        cpId: this.$store.state.user.cpId,
      }
      let excute = this.excute(this.$service.commonService, this.$service.commonService.getStaff, params)
      excute.then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.staffList = res.data.filter(it => idList.includes(it.staffId))
        } else {
          this.$Message.error(res.message)
        }
      })
    },

    /**
    * @desc   : 查询当前员工
    * @author : 常皓宁
    * @date   : 2024/4/2 16:32
    */
    getStaffName(){
      let id = this.staffId
      return this.excuteNoParam(this.$service.staffService, this.$service.staffService.selectById, [id], false).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.staffCode = res.data.staffCode
          this.staffName = res.data.staffName
          this.roleNames = res.data.roleNames
        } else {
          this.$Message.error(res.message)
        }
        this.loading = false
      })
    },

  },
  created() {
    if (this.$route.params.id) {
      this.staffId = this.$route.params.id
      this.getStaffName();
      //查询范围权限
      this.getPurview()
    }
  },
}
</script>

<style lang="less" scoped>
/deep/ .el-tabs__item {
  height: 30px;
  border: 1px solid #dcdee2;
  padding-left: 10px !important;
  padding-right: 10px !important;
  display: inline-flex;
  align-items: center;
  background: #f8f8f9;
  border-radius: 5px 5px 0 0;
}

/deep/ .el-tabs__item:nth-child(n+1) {
  margin-left: 5px;
}

/deep/ .el-tabs__item.is-active {
  background: #409eff;
  color: #fff;
}

/deep/ .el-tabs__active-bar {
  display: none;
}

.staff-class {
  width: 80%;
}
</style>
