<!-- @desc:用户新建/编辑  @auth:周兴  @time:2022/3/30 10:29 -->
<template>
  <div class="main-div" ref="mainDiv" >
    <!--加载中-->
    <loading :loading="loading" v-if="!modalVisible"></loading>
    <DkPageButton :total="editKeys?editKeys.length:0"
                  :current="editIndex"
                  v-if="editKeys && editKeys.length > 1"
                  @pageChange="editPageChange"></DkPageButton>
    <DkCollapse @on-change="changeCollapse" ref="collapse">
      <DkPanel prop="essentialInformation" >
        <!--  下拉区域  -->
        <DkForm slot="content" ref="formInline" v-model="formData" style="width: 95%">
          <!--用户编码-->
          <DkFormItem :required="true" prop="userCode">
            <InputPop ref="userCode" v-model="formData.userCode" :readonly="type == $config.formMode.edit || type === 'edit-staff'"/>
          </DkFormItem>

          <!--所属角色-->
          <DkFormItem prop="roleIds" :required="true"  :data-type="this.$config.dataType.array" :label="$t('roleName')">
            <SelectPop v-model="formData.roleIds" :multiple="true" :options="roleList" ref="roleIds" :disabled="type === 'edit-staff'"
                       labelKey="roleName"
                       valueKey=roleId>
            </SelectPop>
          </DkFormItem>
          <!--业务部门-->
          <DkFormItem :required="true" prop="orgId" :data-type="$config.dataType.number" :label="$t('organizationLevel')">
            <SelectMagnifier v-model="formData.orgId" :display-text="formData.levelName" :disabled="type === 'edit-staff'"
                             :type="this.$config.MagnifierType.organization"
                             :multiple="false"
                             title="业务部门"
                             @ok="chooseOrg"></SelectMagnifier>
          </DkFormItem>

          <!--生产工号【开关模式】-->
          <DkFormItem :label="$t('makeUserId')">
            <dk-switch v-model="prodUserFlag" :disabled="type === 'edit-staff'" @on-change="handleChangeProdUser"/>
          </DkFormItem>
          <!--业务员-->
          <DkFormItem prop="staffId" :data-type="$config.dataType.number" :label="prodUserFlag ? $t('staffId'):$t('staffNames')">
            <SelectMagnifier @ok="chooseStaff" v-model="formData.staffId" :display-text="formData.staffName" :disabled="type === 'edit-staff'"
                             :type="this.$config.MagnifierType.staff" :multiple="false"></SelectMagnifier>
          </DkFormItem>
          <!--备注-->
          <DkFormItem prop="remarks" :span="24">
            <InputPop ref="remarks" v-model="formData.remarks" textareaFlag :readonly="type === 'edit-staff'"/>
          </DkFormItem>
        </DkForm>
      </DkPanel>
      <DkPanel prop="staffRelation" v-if="prodUserFlag" >
        <div slot="content" :style="'height: ' + (tableHeight + 5) + 'px'">
          <DkSplit v-model="split">
            <!--左侧工种信息-->
            <EditTable slot="left" ref="jobTable" :data="formData.workTeamList"
                       :columns="jobColumns"
                       :height="tableHeight + 5"
                       :show-setting-flag="false"
                       :freeze="false"
                       :enabled-repeat-id="jobId"
                       :enabledRepeat="true"
                       @current-change="changeCurrentJob"
                       @chooseData="chooseData"
                       @addRow="addJobRow"
                       @delRow="delJobRow"></EditTable>
            <!--右侧员工信息-->
            <EditTable slot="right" ref="staffTable"
                       :columns="staffColumns"
                       :height="tableHeight + 5"
                       :show-setting-flag="false"
                       enabledRepeatId="staffId"
                       :enabledRepeat="false"
                       :freeze="false"
                       controlId="staffId"
                       :newRowFlag="showStaffList"
                       :data="formData.workTeamList
                                  &&formData.workTeamList.length>0
                                  &&formData.workTeamList[jobIndex]
                                  ?formData.workTeamList[jobIndex].staffList:[]"
                       @changeValue="changeValue"
                       @chooseData="chooseWorkTeamStaff"
                       @onBatchChoose="chooseWorkTeamStaff"
                       @delRow="delStaffRow"
                       @current-change="changeCurrentStaff"
            ></EditTable>
          </DkSplit>
        </div>
      </DkPanel>
    </DkCollapse>
    <!--      下部分按钮区域-->
    <DkSaveButton ref="saveButton" :loading="loading" @save="save" @close="close" v-if="type !== 'edit-staff'"></DkSaveButton>
  </div>
</template>

<script>

import {formMixin} from '@/mixins/form'

export default {
  components: {},
  mixins: [formMixin],
  props: {
    userId: {
      type: Number
    },
    dismissStaffIdList: {
      type: Array
    },
  },
  data() {
    let self = this
    return {
      staffList: [],
      jobList: [], // 工种
      jobId: null,// 当前工种
      roleList: [],// 角色
      tableHeight: 600,
      split: 0.3,
      jobIndex: -1, // 工种当前行号
      showStaffList:false,// 是否显示员工新行
      // 画面表单数据
      formData: {
        userId : '',
        userCode: '',
        userName: '',
        orgId: null,
        orgName:'',
        roleIds: [],
        staffId: null,
        staffName:'',
        remarks: null,
        userType: self.$config.userType.staffUser,
        ftyId: this.$store.state.user.ftyId,
        workTeamList: [],// 班组信息
        levelName:'',//部门全称
      },
      formDataStaff: {
        staffIds: [],
        staffNames: '',
      },
      // 工种列表
      jobColumns: [
        // 工种
        {
          field: 'jobId',
          type: 'select',
          options: () => self.jobList,
          labelKey: 'jobName',
          valueKey: 'jobId',
          width: 'auto'
        },
        // 备注
        {
          field: 'remarks',
          type: 'text',
          width: 'auto'
        },
      ],
      // 业务员列表
      staffColumns: [
        {
          field: 'staffName',
          title:self.$t('staff'),
          width: 255,
          sortBoolean: false,
          controlId: 'staffId',
          type: 'tableSelect',
          initParam: () => {
            return {
              jobIds: {default: [(self.formData.workTeamList && self.formData.workTeamList[self.jobIndex])
                ? parseInt(self.formData.workTeamList[self.jobIndex].jobId) : null,
                (self.formData.workTeamList && self.formData.workTeamList[self.jobIndex])
                  ? self.formData.workTeamList[self.jobIndex].jobId_Name: null],
              valueKind:self.$config.docUserInput.mSearch},
            }
          },
          //z:不关联工种了
          // param: () => {
          //   return {
          //     jobId: (self.formData.workTeamList && self.formData.workTeamList[self.jobIndex])
          //       ? parseInt(self.formData.workTeamList[self.jobIndex].jobId) : null
          //   }
          // },
          dataType: self.$config.tableSelectType.staff,
          fieldUpdate: self.$updateColumns.userChooseStaff,
        },
        // 默认员工
        {field: 'flgDefaultStaff', type: 'switch', width: 'auto'},
      ],
      prodUserFlag: false
    }
  },

  methods: {
    // region 列表
    /**
     * @desc   : 切换工种当前行
     * @author : 周兴
     * @date   : 2023/2/2 11:46
     */
    changeCurrentJob(e) {
      let staffTable = this.$refs.staffTable.getTableDataFilter()
      let oldRowIndex = e.oldRowIndex ? e.oldRowIndex : 0;
      // 记录之前行的数据
      if (this.formData.workTeamList[oldRowIndex]) {
        this.$set(this.formData.workTeamList[oldRowIndex], 'staffList', staffTable)
      }
      // 取当前行的数据
      if (!this.formData.workTeamList[e.rowIndex].staffList) {
        this.formData.workTeamList[e.rowIndex].staffList = []
      }
      this.jobIndex = 0
      this.jobIndex = e.rowIndex
      // 显示员工新行
      this.checkIsShowStaffList();
    },
    /**
     * @desc   : 是否显示员工新行
     * @author : 周兴
     * @date   : 2023/2/2 16:58
     */
    checkIsShowStaffList(){
      if( this.formData.workTeamList[this.jobIndex] && this.formData.workTeamList[this.jobIndex].jobId){
        this.showStaffList = true;
      }else{
        this.showStaffList = false;
      }
    },
    /**
     * @desc   : 选择工种
     * @author : 周兴
     * @date   : 2023/2/2 11:46
     */
    chooseData(e) {
      if (!this.formData.workTeamList || this.formData.workTeamList.length == 0) {
        let item = {}
        item.staffList = [];
        this.formData.workTeamList.push(item)
      }
      if (!this.jobIndex || this.jobIndex === -1) {
        this.jobIndex = 0;
      }
      this.formData.workTeamList[this.jobIndex].staffList = []
      // 显示员工新行
      this.checkIsShowStaffList();
    },
    /**
     * @desc   : 增加工种行数据
     * @author : 周兴
     * @date   : 2023/2/2 15:16
     */
    addJobRow(rowIndex) {
      // 先记录下已经存在的数据
      let staffTable = this.$refs.staffTable ? this.$refs.staffTable.getTableDataFilter() : []
      // 记录之前行的数据
      if (rowIndex < this.jobIndex) {
        // 说明加在前面
        this.jobIndex = this.jobIndex + 1
      }
      // 如果为空，赋值新行
      if (!this.formData.workTeamList || this.formData.workTeamList.length == 0) {
        let item = {}
        item.staffList = [];
        this.formData.workTeamList.push(item)
      }
      // 给原始行赋值
      if (this.formData.workTeamList[this.jobIndex]) {
        this.$set(this.formData.workTeamList[this.jobIndex], 'staffList', staffTable)
      }
      // 设置空行的初始值
      if (this.formData.workTeamList) {
        this.formData.workTeamList.forEach(it => {
          if (!it.jobId || this.jobId == 0) {
            it.staffList = []
          }
        })
      }
    },
    /**
     * @desc   : 删除工种行数据
     * @author : 周兴
     * @date   : 2023/2/2 15:17
     */
    delJobRow(row) {
      // 先记录下已经存在的数据
      let staffTable = this.$refs.staffTable.getTableDataFilter()
      // 记录之前行的数据
      if (this.formData.workTeamList[this.jobIndex]) {
        this.$set(this.formData.workTeamList[this.jobIndex], 'staffList', staffTable)
      }
      if (this.formData.workTeamList && this.formData.workTeamList.length > 1) {
        let delIndex = this.formData.workTeamList.findIndex(item => item._X_ID === row._X_ID)
        this.formData.workTeamList[delIndex].staffList = []
        this.formData.workTeamList.splice(delIndex, 1)
      } else {
        this.formData.workTeamList = [
          {
            jobId: null,
            jobName: null,
            staffList: [],
          }
        ]
      }
    },
    /**
     * @desc   : 选择员工
     * @author : 周兴
     * @date   : 2023/2/2 13:23
     */
    chooseWorkTeamStaff() {
      this.$nextTick(() => {
        // 记录当前数据
        let staffTable = this.$refs.staffTable.getTableDataFilter()
        // 设置第一条的默认员工为true,其他为false
        for (let index in staffTable){
          let it = staffTable[index]
          if(!it.staffId || index > 0){
              it.flgDefaultStaff = false
          }
        }
        // 记录之前行的数据
        if (this.formData.workTeamList[this.jobIndex]) {
          this.$set(this.formData.workTeamList[this.jobIndex], 'staffList', staffTable)
        }
      })
    },
    /**
     * @desc   : 删除员工
     * @author : 周兴
     * @date   : 2023/2/2 15:14
     */
    delStaffRow(row) {
      if (this.formData.workTeamList[this.jobIndex] && this.formData.workTeamList[this.jobIndex].staffList) {
        this.formData.workTeamList[this.jobIndex].staffList.splice(
          this.formData.workTeamList[this.jobIndex].staffList.findIndex(item => item._X_ID === row._X_ID), 1)
      }
    },
   /**
    * @desc   : 值改变
    * @author : 姜宁
    * @date   : 2023/3/24 17:27
    */
    changeValue(field, row, rowIndex, val) {
      // 如果默认员工标识打开，那么其他行数据的默认标识要关闭
      if (field === 'flgDefaultStaff') {
        if (row[field]) {
          if (this.formData.workTeamList[this.jobIndex] && this.formData.workTeamList[this.jobIndex].staffList) {
           for (let index in this.formData.workTeamList[this.jobIndex].staffList){
             if (parseInt(index) === rowIndex){
               continue;
             }
             this.$set(this.formData.workTeamList[this.jobIndex].staffList[index], 'flgDefaultStaff', false);
           }
          }
        }
      }
    },
    /**
     * @desc   : 打开后调整表格的
     * @author : 周兴
     * @date   : 2023/5/26 8:49
     */
    handleChangeProdUser(e){
      if(e){
        this.resizeTable();
      }
    },
    // endregion

    // region 查询基础数据
    /**
     * @desc   : 加载数据
     * @author : 姜宁
     * @date   : 2023/1/29 16:33
     */
    initData() {
      // 获取角色数据
      this.getRole();
      // 加载组织部门数据源
      //this.getOrg();
      // 加载工种信息
      this.getJob();
    },
    /**
     * @desc   : 获取资金账号数据
     * @author : song
     * @date   : 2024/3/1 16:33
     */
    getRole() {
      let params = {
        ftyId: this.$store.state.user.ftyId
      }
      this.excute(this.$service.commonService, this.$service.commonService.getRole, params).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.roleList = res.data;
        }
      })
    },
    /**
     * @desc   : 获取工种信息
     * @author : 姜宁
     * @date   : 2023/2/2 11:07
     */
    getJob() {
      let params = {
        ftyId: this.$store.state.user.ftyId
      }
      this.excute(this.$service.commonService, this.$service.commonService.getJob, params).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.jobList = res.data;
        }
      })
    },
    /**
     * @desc   : 放大镜控件绑定值--业务部门
     * @author : 姜宁
     * @date   : 2023/2/1 15:13
     */
    chooseOrg(rows) {
      if (rows){
         this.formData.orgId = rows[0].orgId;
        this.formData.orgName = rows[0].orgName;
        this.formData.levelName = rows[0].levelName
      }
     else{
         this.formData.orgId = null;
        this.formData.orgName = '';
        this.formData.orgName ='';
      }
    },
    /**
     * @desc   : 放大镜控件绑定值--业务员
     * @author : 姜宁
     * @date   : 2023/2/2 8:49
     */
    chooseStaff(rows) {
      if (rows){
        this.formData.staffId = rows[0].staffId;
        this.formData.staffName = rows[0].staffName;
      }
      else{
        this.formData.staffId = null;
        this.formData.staffName = '';
      }
    },
    /**
     * @desc   : 通过id查询
     * @author : 姜宁
     * @date   : 2023/2/3 11:50
     */
    detail(id) {
      return this.excuteNoParam(this.$service.userService, this.$service.userService.selectById, [parseInt(id)]);
    },

    /**
     * @desc   : 编辑页面赋值
     * @author : 姜宁
     * @date   : 2023/2/3 11:49
     */
    setValuesByEdit(data) {
      this.formData.userId = data.userId
      this.formData.userCode = data.userCode
      this.formData.userName = data.userName
      this.formData.orgId = data.orgId
      this.formData.roleIds = data.roleIds
      this.formData.staffId = data.staffId
      this.formData.remarks = data.remarks
      this.formData.userType = data.userType
      this.formData.ftyId = data.ftyId
      this.formData.workTeamList = data.workTeamList
      this.formData.staffName = data.staffName
      this.formData.orgName = data.orgName
      this.formData.levelName = data.orgLevelName
      this.jobIndex = 0;
      //生产工号开关
      this.prodUserFlag = data.workTeamList && data.workTeamList.length > 0
      //清除离职员工
      if (this.dismissStaffIdList && this.dismissStaffIdList.length > 0 && data.workTeamList && data.workTeamList.length > 0) {
        for (let it of data.workTeamList) {
          it.staffIds = it.staffIds.filter(f => this.dismissStaffIdList.indexOf(f) === -1)
          it.staffList = it.staffList.filter(f => this.dismissStaffIdList.indexOf(f.staffId) === -1)
        }
      }
    },
    // endregion

    // region 保存方法
    /**
     * @desc   : 校验数据是否全
     * @author : 周兴
     * @date   : 2023/2/2 15:57
     */
    validData() {
      // 判断是否有工种信息
      if (this.prodUserFlag && (!this.formData.workTeamList || this.formData.workTeamList.filter(f=>f.jobId).length === 0)) {
       this.$Message.warning(this.$t('W_093', {param: this.$t('job')}))
       return false;
      }
      // 判断工种对应的员工信息是否为空
      for (let index in this.formData.workTeamList){
        let it = this.formData.workTeamList[index]
        let rows = 1 + parseInt(index);
        if(it.jobId > 0 && (!it.staffList || it.staffList.length === 0)){
          this.$Message.warning(this.$t('W_089', {
            'param1': rows + this.$t('rowNo') ,
            'param2': this.$t('staffNames')
          }))
          this.setErrToRow(it, this.$t('W_093', {
            'param': this.$t('staffNames')
          }));// 给行增加错误提示信息
          return false;
        }
        // 是否设置有效的默认员工
        if (it.jobId > 0 && it.staffList){
          let list = it.staffList.filter(item=>item.flgDefaultStaff);
          if (!list || list.length != 1){
            this.$Message.warning(this.$t('W_069', {
              'param': this.$t('sequence') + rows + this.$t('rowNo') + this.$t('flgDefaultStaff')
            }))
            this.setErrToRow(it, this.$t('W_093', {
              'param': this.$t('flgDefaultStaff')
            }));// 给行增加错误提示信息
            return false;
          }
        }
      }
      return true;
    },
    /**
     * @desc   : 保存数据
     * @author : 姜宁
     * @date   : 2023/2/1 15:21
     */
    saveData() {
      if (this.type === this.$config.formMode.add){
        return this.excute(this.$service.userService, this.$service.userService.insert, this.params)
      }
      else{
        return this.excute(this.$service.userService, this.$service.userService.update, this.params)
      }
    },
    /**
     * @desc   : 给参数赋值
     * @author : 姜宁
     * @date   : 2023/2/1 15:28
     */
    setParams() {
      this.params = {...this.formData}
      if (this.prodUserFlag) {
        // 处理班组中的员工Id串
        this.params.workTeamList = this.params.workTeamList.filter(item => item.jobId > 0)
        this.params.workTeamList?.forEach(it => {
          it.staffIds = it.staffList.map(item => item.staffId)
          let list = it.staffList.filter(item=>item.flgDefaultStaff);
          it.staffId = list[0].staffId
        })
      } else {
        this.params.workTeamList = []
      }
    },
    /**
     * @desc   : 清空表单
     * @author : 姜宁
     * @date   : 2023/1/28 15:40
     */
    clear() {
      this.staffList = [];
    },
    // endregion

  },
  /**
   * @desc   : 在实例创建完成后被立即同步调用
   * @author : 周兴
   * @date   : 2022/3/3 10:32
   */
  created() {
    this.focusItem = 'userCode';    // 给第一个组件赋值，可以在混入中自动去聚焦
    this.primaryKey = 'userId'  // 设置主键Id
    if (this.type === 'edit-staff'){
      this._detail(this.userId)
    }
    this.resizeTableFlag = true;
  },
}
</script>

<style lang="less" scoped>
</style>
