<!-- @desc:用户管理  @auth:洪旭东  @time:2022-04-25 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="user-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>
        <!--    操作日志    -->
        <BaseIndexButton right-button="role-log" ref="log" name="log"></BaseIndexButton>
      </template>
      <template #right>
        <!--   新建     -->
        <BaseIndexButton right-button="user-add" 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>
    <!--  表格部分  -->
    <DkSplit v-model="split" :height="tableHeight + 32">
      <DkTable slot="left" :id="'table-'+$options.name" ref="table-select" :data="tableData" multiple
               :height="tableHeight + 2" primaryKey="userId" @pageChange="pageSizeChange"
               :pageFlag="true"
               :page-total="pageInfo.total"
               :current-page="pageInfo.currentPage"
               @current-change="currentChangeEvent($event)">
        <DkTableColumn field="userCode" type="link" @on-link="handleLink(Object.assign($event,{button:'edit'}))"></DkTableColumn>
        <DkTableColumn field="userName"></DkTableColumn>
        <DkTableColumn field="roleName" type="link" @on-link="moduleRights()"></DkTableColumn>
        <DkTableColumn field="orgLevelName" width="300px" :title="$t('organizationLevel')"></DkTableColumn>
        <!--        <DkTableColumn field="userTypeName" :title="$t('userType')"></DkTableColumn>-->
        <DkTableColumn field="staffName" :title="$t('staffId')"></DkTableColumn>
        <DkTableColumn field="flgValid" type="switch" @on-switch-change="onSwitchChange"
                       :switch-disabled="false"></DkTableColumn>
        <DkTableColumn field="remarks" width="auto"></DkTableColumn>
      </DkTable>

      <div slot="right">
        <!--班组信息-->
        <DkTable v-show="userDetailTab === this.$config.userDetailTab.workTeam" :pageFlag="false"
                 :pageTotalFlag="false"
                 primaryKey="teamId"
                 :id="'table-'+$options.name"
                 :height="tableHeight + 32"
                 name="table"
                 ref="workTeam-select"
                 :choose-flag="false"
                 :data="workTeam">
          <DkTableColumn field="jobName" width="200px"></DkTableColumn>
          <DkTableColumn field="staffNames" width="400px" :title="$t('staffRelation')"></DkTableColumn>
<!--          <DkTableColumn field="staffName" :title="$t('flgDefaultStaff')" width="200px"></DkTableColumn>-->
        </DkTable>
      </div>
    </DkSplit>
  </div>
</template>

<script>

import {indexMixin} from '@/mixins'

export default {
  name: 'user',
  mixins: [indexMixin],
  data() {
    let self = this
    return {
      searchContent:
        [
          {
            itemCode: 'userCode',
          },
          {
            itemCode: 'userName',
          },
          {
            itemCode: 'roleName',
            valueFormat: {code: 'roleIds', data: [], valueKey: 'roleId', labelKey: 'roleName',popType:'role'},
            valueKind: self.$config.docUserInput.mChoice
          },
          {
            itemCode: 'orgIds',
            itemName:self.$t('organizationLevel'),
            valueFormat: {code: 'orgIds'},
            valueKind: self.$config.docUserInput.mSearch,
            magnifierType: self.$config.MagnifierType.organization
          },
          self.$config.flgValidSearch
        ],
      // 表单
      formData: {},
      // 查询条件
      searchCond: {},
      // 功能列表
      featuresList: [],
      userRight: [], // 用于存放用户权限信息
      workTeam: [], // 用于存放班组信息
      userDetailTab: this.$config.userDetailTab.workTeam,
      detailOptions: [{label: self.$t('work_team'), name: 'workTeam'}, //班组信息
      ],
    }
  },
  methods: {

    // region 功能按钮操作
    /**
     * @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/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 : 夏常明
     * @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 : 姜宁
     * @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 : 姜宁
     * @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 : 姜宁
     * @date   : 2023/1/29 11:03
     */
    initData() {
      // 获取角色数据
      this.getRole();
      // 加载组织部门数据源
      this.getOrg();
    }
    ,
    /**
     * @desc   : 获取角色数据
     * @author : 姜宁
     * @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   : 获取组织部门数据源
     * @author : 姜宁
     * @date   : 2023/1/29 11:03
     */
    getOrg() {
      let params = {
        ftyId: this.$store.state.user.ftyId
      }
      this.excute(this.$service.commonService, this.$service.commonService.getOrg, params).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          let list = this.searchContent.filter(it => it.valueFormat.code == 'orgIds')
          if (list.length > 0) {
            list[0].valueFormat.data = res.data
          }
        }
      })
    }
    ,
    /**
     * @desc   : switch停用启用
     * @author : 姜宁
     * @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 : 姜宁
     * @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 : 姜宁
     * @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 : 姜宁
     * @date   : 2023/1/29 11:11
     */
    getData(params) {
      // 查询数据
      return this.excute(this.$service.userService, this.$service.userService.selectByCond, params);
    }
    ,
    /**
     * @desc   : 给参数赋值
     * @author : 姜宁
     * @date   : 2023/1/29 15:15
     */
    setParams() {
      this.params = this.formData
    }
    ,
    /**
     * @desc   : 用户行切换事件
     * @author : 姜宁
     * @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 : 姜宁
     * @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 = 'userId'  // 设置主键Id
    this.routeObjName = 'user'  // 设置路由名称
  }
}
</script>

<style lang="less" scoped>
/deep/ .ivu-tree-title {
  width: 100%;
}

/deep/ .flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

/deep/ .ivu-tree li ul {
  padding: 0 6px 0 18px;
}

/deep/ .ivu-checkbox-disabled > .ivu-checkbox-inner {
  background-color: #7ba0d3;
}

/deep/ .ivu-checkbox-disabled > .ivu-checkbox-inner:after {
  color: #fff;
}
</style>
