<!-- @desc:角色管理  @auth:周兴  @time:2024/1/30 9:21 -->
<template>
  <div class="main-div" ref="mainDiv">
    <loading :loading="loading" v-if="!modalVisible"></loading>
    <!--按钮区-->
    <BaseIndexButtonGroup id="BaseIndexButtonGroup">
      <template #left>
        <!--    查询    -->
        <BaseIndexButton ref="search" name="search"></BaseIndexButton>
        <!--    清空条件    -->
        <BaseIndexButton ref="clear" name="clear"></BaseIndexButton>
        <!--    编辑    -->
        <BaseIndexButton ref="edit" name="edit"></BaseIndexButton>
        <!--    功能权限    -->
        <BaseIndexButton ref="moduleRights" name="moduleRights"></BaseIndexButton>
        <!--    敏感权限    -->
        <BaseIndexButton ref="sensitive" name="sensitive"></BaseIndexButton>
        <!--    启用    -->
        <BaseIndexButton ref="enable" name="enable"></BaseIndexButton>
        <!--    停用    -->
        <BaseIndexButton ref="disable" name="disable"></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"
                    :search-content="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="roleId"
                 @pageChange="pageSizeChange"
                 :page-size-opts="pageSizeOpts"
                 :page-size="pageInfo.pageSize">
          <DkTableColumn field="roleCode"></DkTableColumn>
          <DkTableColumn field="roleName" type="link"
                         @on-link="handleLink(Object.assign($event,{button:'edit'}))"></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="roleName" :required="true">
          <InputPop v-model="formData.roleName"/>
        </DkFormItem>
        <!--   备注     -->
        <DkFormItem prop="remarks">
          <InputPop v-model="formData.remarks" textareaFlag/>
        </DkFormItem>
      </DkForm>
    </DkModal>

    <!--敏感字段-->
    <DkModal
      :loading="loading"
      ref="modal_function"
      v-model="sensitiveModal"
      @modalOk="updateSensitive"
      @modalCancel="clearFunction"
      :saveFlag="true"
      :title="sensitiveTitle"
    >
      <div class="main-class">
        <DkTree :data="sensitiveList" ref="menuTree" :height="400" :loading="loading" :onlyChild="false"
                :columns="columns" :nodeWidth="200" @switch-change="onSwitchChange"
                :expand-mode="this.$config.expandMode.all" show-expand-button
                id="itemCode" parent-id="parentCode" tree-node-name="itemName" node-title="敏感字段">
        </DkTree>
      </div>
    </DkModal>
  </div>
</template>

<script>
import {indexMixin} from "@/mixins";

export default {
  name: "role",
  mixins: [indexMixin],
  data() {
    let self = this
    return {
      roleId:null,
      columns: [
        {field: 'itemName', type: 'disabled', width: 'auto'},
        {field: 'checked', type: 'switch'},
      ],
      sensitiveTitle: '敏感字段',
      sensitiveModal: false,
      sensitiveList: [],
      formData: {
        id:null,
        roleName: null,
        displayNo: 0,
        remarks: ''
      },
      // 查询条件
      searchContent: [
        {
          itemCode: 'roleName',
        },
        self.$config.flgValidSearch // 有效标识
      ],
    }
  },
  methods: {

    /**
    * @desc   : 编辑角色校验
    * @author : 常皓宁
    * @date   : 2024/4/10 13:09
    */
    openValidData(btnName, rows) {
      //编辑
      if (rows && rows[0] && (btnName === 'edit' || btnName === 'disable') ) {
        if (rows[0].sysCode != null) {
          this.$Message.warning(this.$t('W_007', {'param': this.$t('W_120')}));
          return false;
        }
      }
      return true;
    },
    /**
     * @desc   : 打开功能权限弹窗
     * @author : 常皓宁
     * @date   : 2023/2/2 15:28
     */
    moduleRights(rows) {
      if (!rows) {
        rows = [this.$refs['table-select'].getCurrentRow()]
      }
      let roleId = 0;
      if (rows && rows.length > 0) {
        roleId = rows[0].roleId
      }
      let disabledFlag = false
      this.getRoleFunList(roleId).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, roleId).then(res => {
                  this.loading = false;
                  if (res.code === this.$config.SUCCESS_CODE) {
                    // 关闭权限窗体
                    if (f) {
                      f.visible = false;
                    }
                  }
                })
              },
            })
        }
      })
    },

    /**
     * @desc   : 敏感字段
     * @author : 常皓宁
     * @date   : 2024/3/7 13:20
     */
    sensitive(rows) {
      this.sensitiveModal = true
      if (!rows) {
        rows = [this.$refs['table-select'].getCurrentRow()]
      }
      let roleId = 0;
      if (rows && rows.length > 0) {
        roleId = rows[0].roleId
      }
      this.getRoleSensitiveList(roleId).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.sensitiveList = res.data.list;
          this.roleId = rows[0].roleId
        }
      })
    },

    /**
    * @desc   : 清空敏感字段
    * @author : 常皓宁
    * @date   : 2024/3/8 11:40
    */
    clearFunction() {
      console.log('sadasd')
      this.sensitiveList = []
      this.sensitiveModal = false
    },

    /**
    * @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.itemCode == 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()
    },

    /**
     * @desc   : 获取角色权限
     * @author : 常皓宁
     * @date   : 2024/3/7 9:09
     */
    getRoleFunList(roleId) {
      let params = {
        roleId: roleId,
      }
      return this.excute(this.$service.roleFunService, this.$service.roleFunService.getRoleFun, params)
    },

    /**
     * @desc   : 获取敏感字段
     * @author : 常皓宁
     * @date   : 2024/3/7 9:09
     */
    getRoleSensitiveList(roleId) {
      let params = {
        roleId: roleId,
      }
      return this.excute(this.$service.roleSensitiveService, this.$service.roleSensitiveService.getRoleSensitive, params)
    },

    /**
     * @desc   : 保存功能权限
     * @author : 常皓宁
     * @date   : 2024/3/7 9:11
     */
    updateFunction(data, roleId) {
      let self = this;
      this.params = {
        roleId: roleId
      }
      this.formDataRight = [
        {
          roleId: roleId,
          rightType: self.$config.rightType.addUser,
          funUuid: '',
          appCode: '',
        }
      ];
      for (let i of data) {
        if (i.funUuid != null && i.funUuid != '' && i.funUuid != 'undefined') {
          let params = {
            roleId: roleId,
            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.roleFunList = this.formDataRight;
      return this.excute(this.$service.roleFunService, this.$service.roleFunService.updateBatch, this.params, true, 'save')
    },

    /**
    * @desc   : 保存敏感字段
    * @author : 常皓宁
    * @date   : 2024/3/8 11:24
    */
    updateSensitive(){
      let self = this;
      let sensitiveList = self.sensitiveList
      this.params = {
        roleId: this.roleId
      }
      let roleSensitiveList = []
      for(let it of sensitiveList){
        if(it.checked){
          let list = {
            roleId : this.roleId,
            senItemCode : it.itemCode,
            flgShow:true,
          }
          roleSensitiveList.push(list)
        }
      }
      this.params.roleSensitiveList = roleSensitiveList;
      return this.excute(this.$service.roleSensitiveService, this.$service.roleSensitiveService.updateBatch, this.params, true, 'save')
    },

    /**
     * @desc   : 获取数据
     * @author : 常皓宁
     * @date   : 2024/3/6 16:01
     */
    getData(params) {
      // 查询数据
      return this.excute(this.$service.roleService, this.$service.roleService.selectByCond, params);
    },

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

    /**
     * @desc   : 通过id查询
     * @author : 常皓宁
     * @date   : 2024/2/29 8:49
     */
    detail(id) {
      return this.excuteNoParam(this.$service.roleService, this.$service.roleService.selectById, [id], false)
    },

  },
  created() {
    this.primaryKey = 'roleId'  // 设置主键Id
    this.routeObjName = 'role'  // 设置路由名称
    this.comHandleEnableFlag = true; //开启启用停用功能
  }
}
</script>

<style scoped>

</style>
