<!-- @desc:员工范围权限  @auth:洪旭东  @time:2022-04-26 -->
<template>
  <div class="main-div">

    <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 !== '订单-查看-制单员'" style="width: 200px;margin-left: 10px;" v-model="orgName[tabsModel]" label="部门名称" @on-clear="clearOrgName"></InputPop>
                <Button v-if="item.name !== '订单-查看-制单员'" type="primary" style="margin-left: 10px;" size="small" @click="searchTable(orgName[tabsModel])">查询</Button>
              </div>

              <DkTree v-if="item.name !== '订单-查看-制单员'" :ref="'treeOrg'+item.name" :data="tableData[item.name]" style="margin-top: 5px"
                      show-checkbox show-expand-button show-choose-button expand-mode="all" @on-checkbox-change-row="changeCheckbox"
                      id="orgId" parent-id="parentId" tree-node-name="orgName" :height="tableHeight-110"></DkTree>

              <div v-else>

                <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 - 200"
                  primaryKey="userId"
                  :data="staffList">
                  <DkTableColumn type="checkbox" width="40"></DkTableColumn>
                  <DkTableColumn type="seq" title="序号" width="60"></DkTableColumn>
                  <DkTableColumn field="userCode" :title="$t('userCode')"></DkTableColumn>
                  <DkTableColumn field="userName" :title="$t('userName')"></DkTableColumn>
                  <DkTableColumn field="orgName" :title="$t('orgName')"></DkTableColumn>
                  <DkTableColumn field="jobName" :title="$t('jobName')"></DkTableColumn>
                  <DkTableColumn field="postName" :title="$t('postName')"></DkTableColumn>
                </DkTable>

                <SelectMagnifier ref="staff-m" style="display: none;" v-model="staffIds" :type="$config.MagnifierType.staff" searchType="M" @on-ok="staffOk"/>
              </div>

            </div>

          </el-tab-pane>
        </el-tabs >
<!--        <DkTabs ref="dkTabs" v-model="tabsModel" :options="tabsOptions" @on-click="tabsClick">-->
<!--          <div v-for="(item, index) of tabsOptions" :key="index" :slot="item.name">-->
<!--            <div style="margin-top: 5px">-->
<!--              <span style="margin-right: 10px">{{$t('noLimit')}}</span>-->

<!--              <i-switch v-model="noLimit[item.name]"></i-switch>-->
<!--            </div>-->
<!--            <DkTree v-if="item.name !== '订单-查看-制单员'" :ref="'treeOrg'+item.name" :data="tableData[item.name]" style="margin-top: 5px"-->
<!--                    show-checkbox show-expand-button show-choose-button expand-mode="all"-->
<!--                    id="orgId" parent-id="parentId" tree-node-name="orgName" height="800"></DkTree>-->
<!--            <div v-else>-->

<!--              <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="600"-->
<!--                primaryKey="userId"-->
<!--                :data="staffList">-->
<!--                <DkTableColumn type="checkbox" width="40" title="选择"></DkTableColumn>-->
<!--                <DkTableColumn type="seq" title="序号" width="60"></DkTableColumn>-->
<!--                <DkTableColumn field="userCode" :title="$t('userCode')"></DkTableColumn>-->
<!--                <DkTableColumn field="userName" :title="$t('userName')"></DkTableColumn>-->
<!--                <DkTableColumn field="orgName" :title="$t('orgName')"></DkTableColumn>-->
<!--                <DkTableColumn field="jobName" :title="$t('jobName')"></DkTableColumn>-->
<!--                <DkTableColumn field="postName" :title="$t('postName')"></DkTableColumn>-->
<!--              </DkTable>-->

<!--              <SelectMagnifier ref="staff-m" style="display: none;" v-model="staffIds" :type="$config.MagnifierType.staff" searchType="M" @on-ok="staffOk"/>-->
<!--            </div>-->
<!--          </div>-->
<!--        </DkTabs>-->
      </div>


    </card>

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

  </div>
</template>

<script>
import { indexMixin } from '@/mixins'
export default {
  name: 'user-purview',
  mixins: [indexMixin],
  data() {
    let self = this
    return {
      tableInit:{},
      chooseIds:{},
      currentTag:null,
      orgName:{},
      staffIds:[],
      staffList:[],
      //不限制标识
      noLimit: {},
      tableData:{},
      //模式切换
      tabsModel: null,
      //模式切换
      tabsModelID: 0,
      //品牌
      brandTableData: [],
      //渠道
      channelTableData: [],
      //客户
      customerTableData: [],
      //业务员
      staffTableData: [],
      //操作业务部门
      operatingOrganizationData: [],
      //查看业务部门
      viewOrganizationData: [],
      //销售库区
      salesWarehouseData: [],
      //操作库区
      operateWarehouseData: [],
      //查看库区
      viewWarehouseData: [],
      //员工组
      staffTeamTableData: [],
      staffsTableData: [],
      //供应商
      supplierTableData: [],
      //资金账户
      capitalAccountTableData: [],
      //文件级别
      fileLevelTableData: [],
      brandCheckRowKeys: () => [],
      errMessage: {},
      tableHeight: 755,
      //模式
      tabsOptions: [
      ],
    }

  },
  methods: {
    clearOrgName(){
      this.searchTable('')
    },
    searchTable(orgName){
      orgName = orgName?orgName:''
      this.tableData[this.tabsModel] = this.tableInit[this.tabsModel].filter(it=>it.orgName.indexOf(orgName)>-1)
      const TABLE = this.$refs['treeOrg'+this.tabsModel][0].$refs['tree']
      this.chooseIds[this.tabsModel].forEach(it=>{
        let row = this.tableInit[this.tabsModel].filter(fit=>fit.id === it)[0];
        TABLE.setCheckboxRow(row,true)
      })
    },
    changeCheckbox({row,checked}){
      // console.log(this.$refs['treeOrg'+this.tabsModel][0].getDataChecked().map(m => m.orgId))
      this.chooseIds[this.tabsModel] = this.$refs['treeOrg'+this.tabsModel][0].getDataChecked().map(m => m.orgId)
      // if(checked){
      //   console.log(this.chooseIds[this.tabsModel])
      //   this.chooseIds[this.tabsModel].push(row.id)
      // }else{
      //   this.chooseIds[this.tabsModel] = this.chooseIds[this.tabsModel].filter(it=>it !== row.id)
      // }
      // console.log('看看',this.chooseIds)
    },
    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.userId))
      this.staffIds = this.staffIds.filter(it=>!arrIds.includes(it))
    },
    staffOk(e){
      this.staffList = [...e]
    },
    /**
     * @desc   : 保存
     * @author : 洪旭东
     * @date   : 2022/4/22 13:25
     */
    submitForm() {
      let param = this.tabsOptions.map(m =>{
        return {
          userId: this.$route.query.userId,
          purviewCode: m.name,
          flgNoLimit: this.noLimit[m.name],
          dataIds: m.name !== '订单-查看-制单员'?this.chooseIds[m.name]:this.staffIds,
          sysId: this.$store.state.user.sysId,
          cpId: this.$store.state.user.cpId,
        }
      })

      //保存
      service.savePurview(this.$route.query.userId, param).then(res => {
        if (res.code === 200) {
          this.$Message.success(this.$t('I_001', { 'param': this.$t('save') }))
          // this.closeTag(this.$route)
          this.getPurview()
        } else {
          this.$Message.warning(res.message)
        }
      })
    },
    /**
     * @desc   : 获取参数
     * @author : 洪旭东
     * @date   : 2022/4/22 13:47
     */
    getParams() {
      let params = []
      //品牌
      let brandKeys = this.$refs['brandTable'].batchKeys
      if (brandKeys.length > 0) {
        params.push({
          soId: this.$store.state.user.soId,
          userId: parseInt(this.$route.query.userId),
          purviewCode: '品牌',
          purviewIds: brandKeys,
          flgNoLimit: false
        })
      }
      //渠道
      let channelKeys = this.$refs['channelTable'].batchKeys
      if (channelKeys.length > 0) {
        params.push({
          soId: this.$store.state.user.soId,
          userId: parseInt(this.$route.query.userId),
          purviewCode: '渠道',
          purviewCodes: channelKeys,
          flgNoLimit: false
        })
      }
      //销售库区
      let salesWarehouseKeys = this.$refs['salesWarehouseTable'].batchKeys
      if (salesWarehouseKeys.length > 0) {
        params.push({
          soId: this.$store.state.user.soId,
          userId: parseInt(this.$route.query.userId),
          purviewCode: '销售库区',
          purviewIds: salesWarehouseKeys,
          flgNoLimit: false
        })
      }
      //操作库区
      let operateWarehouseKeys = this.$refs['operateWarehouseTable'].batchKeys
      if (operateWarehouseKeys.length > 0) {
        params.push({
          soId: this.$store.state.user.soId,
          userId: parseInt(this.$route.query.userId),
          purviewCode: '操作库区',
          purviewIds: operateWarehouseKeys,
          flgNoLimit: false
        })
      }
      //查看库区
      let viewWarehouseKeys = this.$refs['viewWarehouseTable'].batchKeys
      if (viewWarehouseKeys.length > 0) {
        params.push({
          soId: this.$store.state.user.soId,
          userId: parseInt(this.$route.query.userId),
          purviewCode: '查看库区',
          purviewIds: viewWarehouseKeys,
          flgNoLimit: false
        })
      }
      //客户
      let customerKeys = this.$refs['customerTable'].batchKeys
      if (customerKeys.length > 0) {
        params.push({
          soId: this.$store.state.user.soId,
          userId: parseInt(this.$route.query.userId),
          purviewCode: '客户',
          purviewIds: customerKeys,
          flgNoLimit: false
        })
      }
      //业务员
      let staffKeys = this.$refs['staffTable'].batchKeys
      if (staffKeys.length > 0) {
        params.push({
          soId: this.$store.state.user.soId,
          userId: parseInt(this.$route.query.userId),
          purviewCode: '业务员',
          purviewIds: staffKeys,
          flgNoLimit: false
        })
      }
      //员工组
      let staffTeamKeys = this.$refs['staffTeamTable'].batchKeys
      if (staffTeamKeys.length > 0) {
        params.push({
          soId: this.$store.state.user.soId,
          userId: parseInt(this.$route.query.userId),
          purviewCode: '员工组',
          purviewIds: staffTeamKeys,
          flgNoLimit: false
        })
      }
      //供应商
      let supplierKeys = this.$refs['supplierTable'].batchKeys
      if (supplierKeys.length > 0) {
        params.push({
          soId: this.$store.state.user.soId,
          userId: parseInt(this.$route.query.userId),
          purviewCode: '供应商',
          purviewIds: supplierKeys,
          flgNoLimit: false
        })
      }
      //资金账户
      let capitalAccountKeys = this.$refs['capitalAccountTable'].batchKeys
      if (capitalAccountKeys.length > 0) {
        params.push({
          soId: this.$store.state.user.soId,
          userId: parseInt(this.$route.query.userId),
          purviewCode: '资金账户',
          purviewIds: capitalAccountKeys,
          flgNoLimit: false
        })
      }
      //操作部门
      let operatingOrganization = this.$refs['operatingOrganization'].getDataChecked()
      let operationOrg = []
      if (operatingOrganization.length > 0) {
        for (let index = 0; index < operatingOrganization.length; index++) {
          operationOrg.push(operatingOrganization[index].orgId)
        }
      }
      if (operationOrg.length > 0) {
        params.push({
          soId: this.$store.state.user.soId,
          userId: parseInt(this.$route.query.userId),
          purviewCode: '操作部门',
          purviewIds: operationOrg,
          flgNoLimit: false
        })
      }

      //查看部门
      let viewOrganization = this.$refs['viewOrganization'].getDataChecked()
      let viewOrg = []
      if (viewOrganization.length > 0) {
        for (let index = 0; index < viewOrganization.length; index++) {
          viewOrg.push(viewOrganization[index].orgId)
        }
      }
      if (viewOrg.length > 0) {
        params.push({
          soId: this.$store.state.user.soId,
          userId: parseInt(this.$route.query.userId),
          purviewCode: '查看部门',
          purviewIds: viewOrg,
          flgNoLimit: false
        })
      }

      return params
    },
    /**
     * @desc   : 点击TAB进行切换
     * @author : 洪旭东
     * @date   : 2022/4/20 14:12
     */
    tabsClick(val, it) {
      //无数据发生变化
      this.tabsData(val, it)
    },
    /**
     * @desc   : 点击Tab切换查询
     * @author : 洪旭东
     * @date   : 2022/4/20 14:16
     */
    tabsData(val, it) {
      this.tabsModel = val
      this.tabsModelID = it.id
    },
    /**
     * @desc   : 员工组获取员工
     * @author : 洪旭东
     * @date   : 2022/4/21 14:24
     */
    currentChangeGetStaff({ row }) {
      let params = {}
      params.ids = row.staffIds
      params.soId = this.$store.state.user.soId
      params.currentPage = ''
      params.pageSize = ''
      let res = {
        'code': 200,
'message': '操作成功',
'exception': null,
'data': {
          'list': [{
            'pageSize': null,
            'currentPage': null,
            'start': null,
            'end': null,
            'soId': 1001,
            'aoId': 197,
            'aoCode': '22042401',
            'aoName': '霹雳',
            'aoType': 2,
            'contactName': null,
            'contactNo': '15645684865',
            'addressRange': null,
            'addressName': null,
            'addressNo': null,
            'addressGcj02': null,
            'creditLimit': null,
            'taxRate': null,
            'taxNo': null,
            'bankName': null,
            'bankAccount': null,
            'birthdate': null,
            'emailUrl': '',
            'trDataEx': null,
            'pageItemEx': null,
            'customTags': [],
            'remarks': '',
            'flgValid': true,
            'opCreateTime': null,
            'opCreateUserId': null,
            'opUpdateTime': null,
            'opUpdateUserId': null,
            'opAppId': null,
            'opApiId': null,
            'opTimestamp': null,
            'opDbUser': null,
            'userId': 1001,
            'orgId': 7,
            'postId': 35,
            'jobId': 13,
            'genderCode': null,
            'national': null,
            'maritalStatus': null,
            'politicalStatus': null,
            'educational': null,
            'graduateSchool': '',
            'speciality': '',
            'height': null,
            'weight': null,
            'nativePlace': '',
            'idCard': '',
            'imageId': null,
            'joinpartydate': null,
            'entrydate': null,
            'probation': null,
            'isDeformity': false,
            'ids': null,
            'staffCode': '22042401',
            'staffName': '霹雳',
            'orgName': '分销商2',
            'levelCode': null,
            'postName': '经理',
            'jobName': '装修工',
            'genderName': null,
            'nationalName': null,
            'maritalStatusName': null,
            'politicalStatusName': null,
            'educationalName': null,
            'userGrade': '操作用户',
            'createTimeStart': null,
            'createTimeEnd': null,
            'postIds': null,
            'jobIds': null,
            'educationals': null,
            'genderCodes': null,
            'maritalStatuss': null,
            'nationals': null,
            'politicalStatuss': null
          }, {
            'pageSize': null,
            'currentPage': null,
            'start': null,
            'end': null,
            'soId': 1001,
            'aoId': 186,
            'aoCode': 'zhangsan',
            'aoName': '张三',
            'aoType': 2,
            'contactName': null,
            'contactNo': '15902409627',
            'addressRange': null,
            'addressName': null,
            'addressNo': null,
            'addressGcj02': null,
            'creditLimit': null,
            'taxRate': null,
            'taxNo': null,
            'bankName': null,
            'bankAccount': null,
            'birthdate': null,
            'emailUrl': null,
            'trDataEx': null,
            'pageItemEx': null,
            'customTags': [],
            'remarks': '备注',
            'flgValid': true,
            'opCreateTime': null,
            'opCreateUserId': null,
            'opUpdateTime': null,
            'opUpdateUserId': null,
            'opAppId': null,
            'opApiId': null,
            'opTimestamp': null,
            'opDbUser': null,
            'userId': 1001,
            'orgId': 6,
            'postId': 12,
            'jobId': 13,
            'genderCode': '性别-无',
            'national': '民族-汉族',
            'maritalStatus': '婚姻状况-无',
            'politicalStatus': null,
            'educational': '学历-小学',
            'graduateSchool': '11',
            'speciality': '11',
            'height': 111.00,
            'weight': 11.00,
            'nativePlace': '1',
            'idCard': '11',
            'imageId': null,
            'joinpartydate': null,
            'entrydate': null,
            'probation': 11,
            'isDeformity': true,
            'ids': null,
            'staffCode': 'zhangsan',
            'staffName': '张三',
            'orgName': '分销商1',
            'levelCode': null,
            'postName': '运营中心',
            'jobName': '装修工',
            'genderName': '无',
            'nationalName': '汉族',
            'maritalStatusName': '无',
            'politicalStatusName': null,
            'educationalName': '小学',
            'userGrade': '操作用户',
            'createTimeStart': null,
            'createTimeEnd': null,
            'postIds': null,
            'jobIds': null,
            'educationals': null,
            'genderCodes': null,
            'maritalStatuss': null,
            'nationals': null,
            'politicalStatuss': null
          }],
'total': 7,
'pageSize': 0,
'currentPage': 0
        }
      }
      // staffService.selectByCond(params).then(res => {//调用api接口
      if (res.code === 200) {
        this.staffsTableData = res.data.list
      }
      // })
    },
    /**
     * @desc   : 取消
     * @author : 洪旭东
     * @date   : 2022-04-26 09:05
     */
    cancel() {
      this.closeTag(this.$route)
    },
    /**
     * @desc   : 查询部门
     * @author : 洪旭东
     * @date   : 2022-06-09 20:15
     */
    getData() {
      let params = {
        cpId: this.$store.state.user.cpId,
        flgValid: true
      }
      //调用后台查询方法
      orgService.selectByCond(params).then(res => {
        if (res.code === 200) {
          for (let it of this.tabsOptions) {
            this.$set(this.noLimit, it.name, false)
            this.$set(this.tableData, it.name, res.data.list)
            this.$set(this.tableInit, it.name, res.data.list)
          }
          //查询范围权限
          this.$nextTick(()=>{
            //查询范围权限
            this.getByUser()
          })
        } else {
          this.$Message.warning(res.message)
        }
        this.loading = false
      })
    },
    /**
     * @desc   : 查询范围权限
     * @author : 洪旭东
     * @date   : 2022-06-21 13:43
     */
    getByUser(){
      service.getPurview(this.$route.query.userId).then(res=>{
        if (res.code == 200) {
          for (let it of res.data) {
            this.noLimit[it.purviewCode] = it.flgNoLimit

            if(it.purviewCode === '订单-查看-制单员'){
              this.getStaffList(it.dataIds)
              this.staffIds = it.dataIds
              this.staffList = this.$refs['staff-table'][0].options.filter(it2=>this.staffIds.includes(it2.userId))
            }else{
              this.$refs['treeOrg'+it.purviewCode][0].setCheckboxRowByKeys(it.dataIds, 'orgId')
              this.chooseIds[it.purviewCode] = it.dataIds
            }

          }
        } else {
          this.$Message.warning(res.message)
        }
      })
    },
    /**
     * @desc   : 查询范围权限
     * @author : 洪旭东
     * @date   : 2022-06-21 10:21
     */
    getPurview(){
      purviewService.selectByCond({ flgValid: true, sysId: this.$store.state.user.sysId, lan: this.$store.state.app.local_lan }).then(res => {
        if (res.code === 200) {
          this.tabsOptions = res.data.list.map(m => {
            return { label: m.purviewName, name:  m.purviewCode}
          })

          res.data.list.forEach(it=>{
            this.$set(this.chooseIds,it.purviewCode,[])
            this.$set(this.orgName,it.purviewCode,'')
          })

          this.tabsModel = this.tabsOptions && this.tabsOptions.length>0?this.tabsOptions[0].name:''
          // this.$refs.dkTabs.model = this.tabsOptions[0].name
          //查询所有tab页所有数据源
          this.getData()
        } else {
          this.$Message.warning(res.message)
        }
        this.loading = false
      })
    },
    getStaffList(idList){
      let param = {
        cpId: this.$store.state.user.cpId,
        docCode: "",
        leafFlag: false,
        sysId: this.$store.state.user.sysId,
        userId: this.$store.state.user.userId
      }
      CommonService.getStaff(param).then(res=>{
        if(res.code === 200){
          this.staffList = res.data.filter(it=>idList.includes(it.userId))
        } else {
          this.$Message.warning(res.message)
        }
      })
    }



  },
  created() {
    if (this.$route.query.userId) {
      //查询范围权限
      this.getPurview()
    }
  },
  activated() {

  },
  mounted() {

  }
}
</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;
  }
</style>
