<!-- @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="staff-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="staff-resetpwd" ref="resetPassword" name="resetPassword"/>
        <!--    解锁    -->
        <BaseIndexButton right-button="staff-unlock" ref="unLock" name="unLock"/>
        <!--    分配权限    -->
        <BaseIndexButton right-button="staff-fun" ref="moduleRights" name="moduleRights"></BaseIndexButton>
        <!--    范围权限    -->
        <BaseIndexButton ref="scopeRights" name="scopeRights"></BaseIndexButton>
        <!--    购买用户    -->
        <BaseIndexButton ref="buyStaff" name="buyStaff"></BaseIndexButton>
      </template>
      <template #right>
        <!--   新建     -->
        <BaseIndexButton ref="add" name="add"></BaseIndexButton>
      </template>
    </BaseIndexButtonGroup>

    <!--  卡片区  -->
    <div class="index-card">
      <!--  查询条件区域  -->
      <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-30"
                 primaryKey="staffId"
                 :multiple="false"
                 :choose-flag="false"
                 @pageChange="pageSizeChange"
                 :page-size-opts="pageSizeOpts"
                 :page-size="pageInfo.pageSize">
          <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" :title="$t('roleName')"></DkTableColumn>
          <DkTableColumn field="flgValid" type="switch"></DkTableColumn>
          <DkTableColumn field="remarks" width="auto"></DkTableColumn>
        </DkTable>
      </div>
    </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="staffCode" :required="true">
          <InputPop v-model="formData.staffCode"/>
        </DkFormItem>
        <!--  员工名称  -->
        <DkFormItem prop="staffName" :required="true">
          <InputPop v-model="formData.staffName"/>
        </DkFormItem>
        <!--  员工电话  -->
        <DkFormItem prop="staffPhone" :required="true">
          <InputPop v-model="formData.staffPhone"/>
        </DkFormItem>
        <!--  业务部门  -->
        <DkFormItem prop="orgId" :label="$t('orgName')" :required="true">
          <SelectMagnifier v-model="formData.orgId" :display-text="formData.orgName"
                           :type="this.$config.MagnifierType.org"
                           :multiple="false"></SelectMagnifier>
        </DkFormItem>
        <!--登录标识-->
        <DkFormItem prop="flgCanLogin">
          <template>
            <i-switch v-model="formData.flgCanLogin">
              <span slot="open"></span>
              <span slot="close"></span>
            </i-switch>
          </template>
        </DkFormItem>
        <!--登录系统-->
        <DkFormItem prop="loginType"  v-if="formData.flgCanLogin">
          <SelectPop v-model="formData.loginType" ref="loginTypeId"
                     :options="loginTypeList"
                     :multiple="false"
                     labelKey="loginTypeName" valueKey="loginTypeId">
          </SelectPop>
        </DkFormItem>
        <!--  角色  -->
        <DkFormItem prop="roleIds" :label="$t('roleName')" :data-type="$config.dataType.array">
          <SelectPop v-model="formData.roleIds" ref="roleId"
                     :options="roleNamesList"
                     labelKey="roleName" valueKey="roleId">
          </SelectPop>
        </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 {
      //购买用户
      buyStaffModal:false,
      columns: [
        {field: 'orgName', type: 'disabled', width: 'auto'},
        {field: 'checked', type: 'switch'},
      ],
      purviewList: [],
      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'},
            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: {
        staffCode: '',
        staffName: '',
        staffPhone: '',
        orgId: null,
        orgName: null,
        roleIds: null,
        flgCanLogin:false,
        loginType:null,
        remarks: ''
      },
      // 查询条件
      searchCond: {},
      // 功能列表
      featuresList: [],
      // 角色
      roleNamesList: [],
      // 登录系统
      loginTypeList: [
        {
          loginTypeId: 0, loginTypeName: 'PC端'
        },
        {
          loginTypeId: 1, loginTypeName: '移动端'
        },
        {
          loginTypeId: 2, loginTypeName: 'PC+移动端'
        }
      ],
      userRight: [], // 用于存放用户权限信息
    }
  },
  methods: {

    // region 功能按钮操作
    /**
    * @desc   : 购买用户
    * @author : 常皓宁
    * @date   : 2024/5/24 11:12
    */
    buyStaff(){
      if (this.$refs['table-select'].batchKeys.length == 1) {
        if (!this.$refs['table-select'].batchRows[0].staffId) {
          this.$Message.error(this.$t('W_068'))
          return
        }
        this.buyStaffModal = true
        // 查询客户信息
        this.getCustomerInfo()
      } else {
        this.$Message.error(this.$t('W_013'))
      }
    },

    /**
     * @desc   : 重置密码
     * @author : 常皓宁
     * @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 : 常皓宁
     * @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 : 常皓宁
     * @date   : 2023/2/2 15:28
     */
    moduleRights(rows) {
      if (!rows) {
        rows = [this.$refs['table-select'].getCurrentRow()]
      }
      let staffId = 0;
      if (rows && rows.length > 0) {
        staffId = rows[0].staffId
      }
      let disabledFlag = false
      this.getStaffRightList(staffId).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
            }
          }
          console.log('this.menuList',this.menuList.list)
          this.$Function({title: this.$t('featuresList'), data: this.menuList.list, disabled: disabledFlag},
            {
              ok: (data, f) => {
                this.loading = true;
                // 更新功能权限
                this.updateFunction(data, staffId).then(res => {
                  this.loading = false;
                  if (res.code === this.$config.SUCCESS_CODE) {
                    // 关闭权限窗体
                    if (f) {
                      f.visible = false;
                    }
                  }
                })
              },
            })
        }
      })
    }
    ,
    /**
     * @desc   : 保存功能权限
     * @author : 常皓宁
     * @date   : 2023/2/3 15:07
     */
    updateFunction(data, staffId) {
      let self = this;
      this.params = {
        staffId:staffId
      }
      this.formDataRight = [
        {
          staffId: staffId,
          rightType: self.$config.rightType.addUser,
          funUuid: '',
          appCode: '',
        }
      ];
      for (let i of data) {
        if (i.funUuid != null && i.funUuid != '' && i.funUuid != 'undefined') {
          let params = {
            staffId: staffId,
            rightType: self.$config.rightType.addUser,
            funUuid: i.funUuid,
            appCode: i.appCode,
          }
          this.formDataRight.push(params)
        }
      }
      this.formDataRight = this.formDataRight.filter(it => it.funUuid != '')
      this.params.staffRightList = this.formDataRight;
      return this.excute(this.$service.staffService, this.$service.staffService.saveStaffRight, this.params, true, 'save')
    },

    /**
     * @desc   : 功能列表树结构change事件
     * @author : 常皓宁
     * @date   : 2024/3/8 9:28
     */
    onSwitchChange(colItem, row) {
      if (colItem.field == 'checked' && row.checked) {
        //同时展开对应的上级
        let pid = row.parentId
        for (let i = 1; i < row.levelNo; i++) {
          let parent = this.$refs.menuTree.treeData.filter(f => f.parentId == pid)
          if (parent && parent.length > 0) {
            parent[0].checked = true
            pid = parent[0].parentId
          }
        }
      }

      //同时展开对应的下级
      let children = this.$refs.menuTree.treeData.filter(f => f.levelCode && f.levelCode.indexOf(row.levelCode) === 0)
      for (let it of children) {
        it.checked = row.checked
      }
      //刷新数据
      this.$refs.menuTree.$refs.tree.reloadData(this.$refs.menuTree.treeData)
      this.$refs.menuTree.expandAll()
    },
// endregion

// region 其他操作
    /**
     * @desc   : 加载数据
     * @author : 常皓宁
     * @date   : 2023/1/29 11:03
     */
    initData() {
      // 获取角色数据
      this.getRole();
    },

    /**
    * @desc   : 获取用户权限
    * @author : 常皓宁
    * @date   : 2024/3/6 10:08
    */
    getStaffRightList(staffId) {
      let params = {
        staffId: staffId,
      }
      return this.excute(this.$service.staffRightService, this.$service.staffRightService.getStaffRightWeb, params)
    },

    /**
     * @desc   : 保存范围权限
     * @author : 常皓宁
     * @date   : 2024/3/8 11:24
     */
    updatePurview(){
      let self = this;
      let purviewList = self.purviewList
      this.params = {
        roleId: purviewList.roleId
      }
      let staffPurviewList = []
      for(let it of purviewList){
        if(it.checked){
          let list = {
            roleId : purviewList.roleId,
            senItemCode : it.itemCode,
            flgShow:true,
          }
          staffPurviewList.push(list)
        }
      }
      this.params.staffPurviewList = staffPurviewList;
      return this.excute(this.$service.roleSensitiveService, this.$service.roleSensitiveService.updateBatch, this.params, true, 'save')
    },

    /**
     * @desc   : 获取角色数据
     * @author : 常皓宁
     * @date   : 2023/1/29 14:29
     */
    getRole() {
      let params = {
        cpId: this.$store.state.user.cpId
      }
      this.excute(this.$service.commonService, this.$service.commonService.getRole, params).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.roleNamesList = res.data
          let list = this.searchContent.filter(it => it.valueFormat.code == 'roleIds')
          if (list.length > 0) {
            list[0].valueFormat.data = res.data
          }
        }
      })
    },

    /**
     * @desc   : 获取数据
     * @author : 常皓宁
     * @date   : 2023/1/29 11:11
     */
    getData(params) {
      // 查询数据
      return this.excute(this.$service.staffService, this.$service.staffService.selectByCond, params);
    },

    /**
     * @desc   : 提交事件
     * @author : 常皓宁
     * @date   : 2024/3/5 14:19
     */
    saveData() {
      console.log('this.params', this.params)
      if (this.modalParams.button === this.$config.formMode.add) {
        delete this.params.staffId // 解决提示主键重复的问题，删除主键代码
        return this.excute(this.$service.staffService, this.$service.staffService.insert, this.params)
      } else {
        return this.excute(this.$service.staffService, this.$service.staffService.update, this.params)
      }
    },

    /**
    * @desc   : 新建完毕后清空窗体
    * @author : 常皓宁
    * @date   : 2024/5/17 9:07
    */
    clear() {
      this.formData.staffCode = null
      this.formData.staffName = null
      this.formData.staffPhone = null
      this.formData.orgId = null
      this.formData.orgName = null
      this.formData.roleIds = null
      this.formData.flgCanLogin = false
      this.formData.loginType = null
      this.formData.remarks = null
    },

    /**
     * @desc   : 通过id查询
     * @author : 常皓宁
     * @date   : 2024/2/29 8:49
     */
    detail(id) {
      return this.excuteNoParam(this.$service.staffService, this.$service.staffService.selectById, [id], false)
    },
    // endregion
  },
  created() {
    this.primaryKey = 'staffId'  // 设置主键Id
    this.routeObjName = 'staff'  // 设置路由名称
    // this.initSearchFlag = true;
  }
}
</script>

