<!-- @desc:用户管理  @auth:宋扬  @time:2024-02-1 16:28 -->
<template>
  <div class="main-div" ref="mainDiv">
    <!--加载中-->
    <loading :loading="loading" v-if="!modalVisible"></loading>
    <BaseIndexButtonGroup id="BaseIndexButtonGroup">
      <template #left>
        <!--    查询    -->
        <BaseIndexButton right-button="user-select" ref="search" name="search"></BaseIndexButton>
        <!--    清空条件    -->
        <BaseIndexButton ref="clear" name="clear"></BaseIndexButton>
        <!--    编辑    -->
        <BaseIndexButton right-button="staff-edit" ref="edit" name="edit"></BaseIndexButton>
        <!--    重置密码    -->
        <BaseIndexButton right-button="user-resetpwd" ref="resetPassword" name="resetPassword"/>
        <!--    解锁    -->
        <BaseIndexButton right-button="user-unlock" ref="unLock" name="unLock"/>
        <!--    分配权限    -->
        <BaseIndexButton right-button="user-fun" ref="moduleRights" name="moduleRights"></BaseIndexButton>
        <!--    启用    -->
        <BaseIndexButton right-button="user-enable" ref="enable" name="enable"></BaseIndexButton>
        <!--    停用    -->
        <BaseIndexButton right-button="user-disable" ref="disable" name="disable"></BaseIndexButton>
      </template>
      <template #right>
        <!--   新建     -->
        <BaseIndexButton ref="add" name="add"></BaseIndexButton>
      </template>
    </BaseIndexButtonGroup>

    <!--  查询条件区域  -->
    <div id="search-cond-div" ref="search-cond-div" class="search-cond-class">
      <SearchCond ref="searchCond" v-model="searchCond"
                  @collapse-change="collapseChange" :setFlag="false"
                  :searchContent="searchContent"
      ></SearchCond>
    </div>
    <!--  表格部分  -->
    <div>
      <DkTable :id="'table-'+$options.name" ref="table-select" :data="tableData"
               :page-total="pageInfo.total"
               :current-page="pageInfo.currentPage"
               :height="tableHeight"
               primaryKey="staffId"
               :multiple="false"
               :choose-flag="false"
               @pageChange="pageSizeChange">
        <DkTableColumn field="staffCode"></DkTableColumn>
        <DkTableColumn field="staffName" type="link" @on-link="handleLink(Object.assign($event,{button:'edit'}))"></DkTableColumn>
        <DkTableColumn field="orgName"></DkTableColumn>
        <DkTableColumn field="roleNames"></DkTableColumn>
        <DkTableColumn field="flgValid" type="switch" @on-switch-change="onSwitchChange"
                       :switch-disabled="false"></DkTableColumn>
        <DkTableColumn field="remarks" width="auto"></DkTableColumn>
      </DkTable>
    </div>
    <!--新建编辑-->
    <DkModal
      :loading="loading"
      v-model="editAddModal"
      ref="modal_editAdd"
      @on-visible-change="handleVisibleModal"
      @modalOk="save"
      :saveFlag="true"
      :title="modalTitle"
    >
      <DkForm ref="formInline" v-model="formData" :col-count="1">
        <!--  供应商编码  -->
        <DkFormItem prop="员工编码" :required="true">
          <InputPop v-model="formData.userCode" />
        </DkFormItem>
        <!--  供应商名称  -->
        <DkFormItem prop="员工名称" :required="true">
          <InputPop v-model="formData.userName" />
        </DkFormItem>
        <!--  业务部门  -->
        <DkFormItem prop="组织机构" :data-type="$config.dataType.array">
          <SelectMagnifier v-model="formData.organization" :display-text="formData.purviewNames"
                           :type="this.$config.MagnifierType.organization"
                           :multiple="false"></SelectMagnifier>
        </DkFormItem>
        <!--  角色  -->
        <DkFormItem prop="角色名称" :data-type="$config.dataType.array">
          <SelectMagnifier v-model="formData.role" :display-text="formData.functionNames"
                           :type="this.$config.MagnifierType.organization"
                           :multiple="false"></SelectMagnifier>
        </DkFormItem>
        <!--   备注     -->
        <DkFormItem prop="remarks">
          <InputPop v-model="formData.remarks" textareaFlag/>
        </DkFormItem>
      </DkForm>
    </DkModal>

  </div>
</template>

<script>

import {indexMixin} from '@/mixins'

export default {
  name: "staff",
  mixins: [indexMixin],
  data() {
    let self = this
    return {
      searchContent:
        [
          {
            itemCode: 'staffCode',
          },
          {
            itemCode: 'staffName',
          },
          {
            itemCode: 'hrStatus',
            valueFormat: {code: 'hrStatus', data: [
                {valueKey: 1, flgValid: '入职（在职）'},
                {valueKey: 2, flgValid: '离职'},
              ],
              valueKey: 'valueKey',
              labelKey: 'flgValid',
            },
            valueKind: 'S-CHOICE'
          },
          {
            itemCode: 'roleName',
            valueFormat: {code: 'roleIds', data: [], valueKey: 'roleId', labelKey: 'roleName',popType:'role'},
            valueKind: self.$config.docUserInput.mChoice
          },
          {
            itemCode: 'orgIds',
            itemName:self.$t('orgName'),
            valueFormat: {code: 'orgIds'},
            valueKind: 'M-SEARCH',
            magnifierType: self.$config.MagnifierType.org
          },
          self.$config.flgValidSearch
        ],
      // 表单
      formData: {
        userCode: '',
        userName: '',
        organization:null,
        role: null,
        remarks: ''
      },
      // 查询条件
      searchCond: {},
      // 功能列表
      featuresList: [],
      userRight: [], // 用于存放用户权限信息
      workTeam: [], // 用于存放班组信息
      userDetailTab: this.$config.userDetailTab.workTeam,
      detailOptions: [{label: self.$t('work_team'), name: 'workTeam'}, //班组信息
      ],
    }
  },
  methods: {

    // region 功能按钮操作
    /**
     * @desc   : 重置密码
     * @author : songy
     * @date   : 2022-04-25 17:09
     */
    resetPassword() {
      if (this.$refs['table-select'].batchKeys.length >= 1) {
        this.$IBMessage({
            content: this.$t('Q_002', {'param': this.$t('resetPassword')}),
            title: this.$t('systemQuestion')
          },
          {
            ok: () => {
              //选中userId集合
              let userIds = [];
              this.$refs['table-select'].batchRows.forEach((item, index) => {
                userIds.push(item.userId);
              });
              let params = {
                ftyId: this.$store.state.user.ftyId,
                //userIds: this.$refs['table-select'].batchRows[0].userId
                userIds: userIds
              }
              this.excute(this.$service.userService, this.$service.userService.resetPassword, params).then(res => {//调用api接口
                if (res.code === this.$config.SUCCESS_CODE) {
                  this.$Message.success(this.$t('I_001', {'param': this.$t('resetPassword')}))
                } else {
                  this.$Message.warning(res.message)
                }
              })
            },
          }
        )
      } else {
        this.$Message.warning(this.$t('W_013'))
      }
    }
    ,
    /**
     * @desc   : 解锁
     * @author : songy
     * @date   : 2022-04-25 17:14
     */
    unLock() {
      if (this.$refs['table-select'].batchKeys.length >= 1) {
        this.$IBMessage({
            content: this.$t('Q_002', {'param': this.$t('unLock')}),
            title: this.$t('systemQuestion')
          },
          {
            ok: () => {
              //选中userId集合
              let userIds = [];
              this.$refs['table-select'].batchRows.forEach((item, index) => {
                userIds.push(item.userId);
              });
              let params = {
                userIds: userIds
              }
              //调用api接口
              this.excute(this.$service.userService, this.$service.userService.unLock, params, false).then(res => {//调用api接口
                if (res.code === this.$config.SUCCESS_CODE) {
                  this.$Message.success(this.$t('I_001', {'param': this.$t('unLock')}))
                } else {
                  this.$Message.warning(res.message)
                }
              })
            },
          })
      } else {
        this.$Message.warning(this.$t('W_013'))
      }
    },

    /**
     * @desc   : 启用按钮
     * @author : songy
     * @date   : 2023/2/10 9:15
     */
    enable() {
      if (this.$refs['table-select'].batchKeys.length >= 1) {
        this.$IBMessage({
            content: this.$t('Q_002', {'param': this.$t('enable')}),
            title: this.$t('systemQuestion')
          },
          {
            ok: () => {
              //选中user集合
              let params = this.$refs['table-select'].batchRows
              //调用api接口
              this.excute(this.$service.userService, this.$service.userService.userEnable, params, false).then(res => {//调用api接口
                if (res.code === this.$config.SUCCESS_CODE) {
                  this.$Message.success(res.data)
                } else {
                  this.$Message.warning(res.message)
                }
              })
            },
          })
      } else {
        this.$Message.warning(this.$t('W_013'))
      }
    },
    /**
     * @desc   : 禁用
     * @author : songy
     * @date   : 2023/2/10 11:10
     */
    disable() {
      if (this.$refs['table-select'].batchKeys.length >= 1) {
        this.$IBMessage({
            content: this.$t('Q_002', {'param': this.$t('disable')}),
            title: this.$t('systemQuestion')
          },
          {
            ok: () => {
              //选中user集合
              let params = this.$refs['table-select'].batchRows
              //调用api接口
              this.excute(this.$service.userService, this.$service.userService.userDisable, params, false).then(res => {//调用api接口
                if (res.code === this.$config.SUCCESS_CODE) {
                  this.$Message.success(res.data)
                } else {
                  this.$Message.warning(res.message)
                }
              })
            },
          })
      } else {
        this.$Message.warning(this.$t('W_013'))
      }
    },
    /**
     * @desc   : 打开功能权限弹窗
     * @author : songy
     * @date   : 2023/2/2 15:28
     */
    moduleRights(rows) {
      if (!rows) {
        rows = [this.$refs['table-select'].getCurrentRow()]
      }
      let userId = 0;
      if (rows && rows.length > 0) {
        userId = rows[0].userId
      }
      let disabledFlag = false
      this.getUserRightList(userId).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.menuList = res.data;
          //判断选中用户是否拥有超级管理员权限
          if(rows[0].roleIds && rows[0].roleIds.length>0){
            if(rows[0].roleIds.filter(f =>f == -1).length>0){
              //用户有超级管理员角色时，功能权限不能修改
              disabledFlag = true
            }
          }
          this.$Function({title: this.$t('featuresList'), data: this.menuList, disabled: disabledFlag},
            {
              ok: (data,f) => {
                this.loading = true;
                // 更新功能权限
                this.updateFunction(data, userId).then(res => {
                  this.loading = false;
                  if(res.code === this.$config.SUCCESS_CODE){
                    // 关闭权限窗体
                    if(f){
                      f.visible = false;
                    }
                  }
                })
              },
            })
        }
      })
    }
    ,
    /**
     * @desc   : 保存功能权限
     * @author : songy
     * @date   : 2023/2/3 15:07
     */
    updateFunction(data, userId) {
      let self = this;
      this.formDataRight = [
        {
          ftyId: this.$store.state.user.ftyId,
          userId: userId,
          rightType: self.$config.rightType.addUser,
          funUuid: '',
          appCode: '',
        }
      ];
      for (let i of data) {
        if (i.funUuid != null && i.funUuid != '' && i.funUuid != 'undefined') {
          let params = {
            ftyId: this.$store.state.user.ftyId,
            userId: userId,
            rightType: self.$config.rightType.addUser,
            funUuid: i.funUuid,
            appCode: i.appCode,
          }
          this.formDataRight.push(params)
        }
      }
      this.params = this.formDataRight;
      return this.excute(this.$service.userService, this.$service.userService.saveUserRight, this.params, true, 'save')
    }
    ,
// endregion

// region 其他操作
    /**
     * @desc   : 加载数据
     * @author : songy
     * @date   : 2023/1/29 11:03
     */
    initData() {
      // 获取角色数据
      this.getRole();
    }
    ,
    /**
     * @desc   : 获取角色数据
     * @author : songy
     * @date   : 2023/1/29 14:29
     */
    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) {
      //     let list = this.searchContent.filter(it => it.valueFormat.code == 'roleIds')
      //     if (list.length > 0) {
      //       list[0].valueFormat.data = res.data
      //     }
      //   }
      // })
    }
    ,
    /**
     * @desc   : switch停用启用
     * @author : songy
     * @date   : 2023/2/2 13:29
     */
    onSwitchChange(param) {
      if (param.flgValid) {
        this.excuteNoParam(this.$service.userService, this.$service.userService.enable, [param.userId])
      } else {
        this.excuteNoParam(this.$service.userService, this.$service.userService.disable, [param.userId])
      }
    }
    ,
    /**
     * @desc   : 获取用户权限
     * @author : songy
     * @date   : 2023/2/2 16:24
     */
    getUserRightList(userId) {
      let params = {
        ftyId: this.$store.state.user.ftyId,
        userId: userId,
      }
      return this.excute(this.$service.userService, this.$service.userService.getUserRight, params)
    }
    ,
    /**
     * @desc   : 获取用户权限
     * @author : songy
     * @date   : 2023/2/2 16:24
     */
    getUserRightSelectedList(userId) {
      let params = {
        ftyId: this.$store.state.user.ftyId,
        userId: userId,
      }
      return this.excute(this.$service.userService, this.$service.userService.getUserRightSelected, params)
    }
    ,
    /**
     * @desc   : 获取数据
     * @author : songy
     * @date   : 2023/1/29 11:11
     */
    getData(params) {
      // 查询数据
      return this.excute(this.$service.staffService, this.$service.staffService.selectByCond, params);
    }
    ,
    /**
     * @desc   : 给参数赋值
     * @author : songy
     * @date   : 2023/1/29 15:15
     */
    setParams() {
      this.params = this.formData
    }
    ,
    /**
     * @desc   : 用户行切换事件
     * @author : songy
     * @date   : 2023/2/7 9:04
     */
    currentChangeEvent({row}) {
      if (row != null) {
        // 获取用户权限信息
        this.getUserRightList(row.userId).then(res => {
          if (res.code === this.$config.SUCCESS_CODE) {
            let list = res.data.filter(it => it.checked)
            this.userRight = list;
          }
        });
        // 查询用户权限以及班组信息
        this.getWorkTeam(row.userId);
      }
    }
    ,
    /**
     * @desc   : 获取数据
     * @author : songy
     * @date   : 2023/1/29 11:11
     */
    getWorkTeam(userId) {
      // 查询数据
      return this.excuteNoParam(this.$service.userService, this.$service.userService.getWorkTeamByUserId, [userId], false).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.workTeam = res.data;
        }
      });
    }
    ,
    // endregion
  },
  created() {
    this.primaryKey = 'staffId'  // 设置主键Id
    this.routeObjName = 'staff'  // 设置路由名称
    this.initSearchFlag = true;
  }
}
</script>

