<template>
  <div>
    <!-- 高级查询 -->
    <div v-show="['1', '2'].includes(curTabKey) && advSearchBtnActived" :class="$style.header">
      <span :class="$style['search-form']">
        <sdSearchForm
          ref="searchForm"
          :onl-list-column-defs="searchFields"
          @search="search"
          @close="() => (advSearchBtnActived = false)"
        />
      </span>
    </div>
    <div :class="$style.wrap">
      <div :class="$style.rightcontent">
        <a-card :class="$style['search-result']" force-render>
          <a-tabs v-model="curTabKey" @change="tabsChange">
            <a-tab-pane key="1" tab="全局角色列表">
              <sd-data-table
                ref="globalRolesTable"
                :data-url="globalRolesUrl"
                :actions="actions"
                :columns="columns"
                show-selection
                :filter-expressions="customFilterExpressions"
                :process-req="processReq"
                :row-key="'code'"
                :search-fields="showfuzzySearch ? ['name'] : []"
                :class="$style.fuzzyAdvSearch"
                @rowClick="rowClick"
                @update:selectedDatas="updateSelectedDatas"
              >
                <template slot="randerFirstLoginChangePwd" slot-scope="text, record">
                  {{ record.firstLoginChangePwd === true ? '是' : '否' }}
                </template>
                <!-- 高级查询 -->
                <template slot="headerPrefix">
                  <sd-select
                    v-model="hierarchy"
                    :options="hierarchyOptions"
                    :class="$style.select"
                    @change="hierarchyChange"
                  />
                  <SdAvanceSearchBtn
                    :actived="advSearchBtnActived"
                    :class="$style.advsearchbtn"
                    @click="switchSearch"
                  />
                </template>
              </sd-data-table>
            </a-tab-pane>
            <a-tab-pane v-if="orgGroupId !== '-1'" key="2" tab="本地角色列表">
              <sd-data-table
                ref="localRolesTable"
                :data-url="localRolesUrl"
                :actions="actions"
                :columns="columns"
                show-selection
                :filter-expressions="customFilterExpressions"
                :process-req="processReq"
                :row-key="'code'"
                :search-fields="showfuzzySearch ? ['name'] : []"
                :class="$style.fuzzyAdvSearch"
                @rowClick="rowClick"
                @update:selectedDatas="updateSelectedDatas"
              >
                <template slot="randerFirstLoginChangePwd" slot-scope="text, record">
                  {{ record.firstLoginChangePwd === true ? '是' : '否' }}
                </template>
                <!-- 高级查询 -->
                <template slot="headerPrefix">
                  <sd-select
                    v-model="hierarchy"
                    :options="hierarchyOptions"
                    :class="$style.select"
                    @change="hierarchyChange"
                  />
                  <SdAvanceSearchBtn
                    :actived="advSearchBtnActived"
                    :class="$style.advsearchbtn"
                    @click="switchSearch"
                  />
                </template>
              </sd-data-table>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </div>
      <sd-org-role
        ref="detailForm"
        :cur-parent="hierarchy[0]"
        :unid="clickedRow"
        @feedback="
          (res) => {
            if (res) {
              refresh()
            }
          }
        "
      ></sd-org-role>
      <sd-org-role-assign-user
        ref="assignUser"
        :unid="clickedRow"
        :cur-parent="hierarchy[0]"
      ></sd-org-role-assign-user>
      <sd-org-role-assign-role
        ref="assignRole"
        :unid="clickedRow"
        :group-id="orgGroupId"
      ></sd-org-role-assign-role>
      <sd-org-role-besigned-role
        ref="besignedRole"
        :unid="clickedRow"
        :group-id="orgGroupId"
      ></sd-org-role-besigned-role>
      <sd-org-import
        ref="importForm"
        :import-form-data="importFormData"
        :req-url="importDataUrl"
        :check-url="importDataCheckUrl"
        :bussiness-id="'role'"
        :process-param="
          (params) => {
            params.groupId = orgGroupId
            params.importUsers = params.importUsers === '1'
            return params
          }
        "
        :process-check-param="
          (params) => {
            params.groupId = orgGroupId
            params.importUsers = params.importUsers === '1'
            params.conflictStrategy = 0
            return params
          }
        "
        @feedback="
          (res) => {
            if (res) {
              refresh()
            }
          }
        "
      ></sd-org-import>
    </div>
  </div>
</template>

<script>
import storeMixin from '@/common/store-mixin'
import TableActionTypes from '@/common/services/table-action-types'
import { sdLocalStorage } from '@/common/services/storage-service'
import download from '@/common/services/download'
import { Modal } from '@/common/one-ui'
import { message } from 'ant-design-vue'
import SdAvanceSearchBtn from '@/application-manage/sd-advance-search-btn.vue'
import sdSearchForm from './sd-org-list-search.vue'
import OrgService from './org-service'
import components from './_import-components/sd-org-role-list-import'

export default {
  name: 'SdOrgRoleList',
  metaInfo: {
    title: 'SdOrgRoleList',
  },
  components: { ...components, sdSearchForm, SdAvanceSearchBtn },
  mixins: [storeMixin],
  data() {
    return {
      importFormData: [
        {
          name: 'data',
          dataType: 'attachment',
          caption: '数据文件',
          readonly: false,
          required: true,
          attr: {
            allowType: '.xls',
            maxLength: 1,
            uploadable: true,
          },
        },
        {
          name: 'importUsers',
          dataType: 'selectlist',
          caption: '导入角色用户',
          readonly: false,
          required: false,
          attr: {
            defaultValue: '0',
            multiple: 'false',
            selectListItem: [
              {
                label: '否',
                value: '0',
              },
              {
                label: '是',
                value: '1',
              },
            ],
          },
        },
      ],
      importDataUrl: `api/framework/v1/role-manager/import`,
      importDataCheckUrl: `api/framework/v1/role-manager/roles/check`,
      customFilterExpressions: [],
      hierarchy: [],
      localRolesSelectedRowKeys: [],
      globalRolesSelectedRowKeys: [],
      searchFields: [
        {
          fieldId: 'code',
          fieldName: '代码',
          fieldType: 'string',
          dataType: 'string',
          search: true,
        },
        {
          fieldId: 'name',
          fieldName: '名称',
          fieldType: 'string',
          dataType: 'string',
          search: true,
        },
      ],
      columns: [
        {
          title: '代码',
          dataIndex: 'code',
        },
        {
          title: '名字',
          dataIndex: 'name',
          sdClickable: true,
        },
        {
          title: '优先级',
          dataIndex: 'index',
        },
        {
          title: '描述信息',
          dataIndex: 'description',
        },
      ],

      globalRolesUrl: `api/framework/v1/role-manager/query/roles`,
      localRolesUrl: `api/framework/v1/role-manager/query/local-roles`,
      clickedRow: null,
      visible: false,
      loadingMsg: null,
      curTabKey: '1',
      showfuzzySearch: true,
      advSearchBtnActived: false,
    }
  },
  computed: {
    hierarchyOptions() {
      return (this.userInfo.belongedOrgIds || []).map((item) => ({
        id: item.id,
        name: item.text,
        title: item.text,
      }))
    },
    isConfiger() {
      const openSecret = JSON.parse(sdLocalStorage.getItem('commonConfig') || '{}').openSecret
      // 开启三员，安全管理员能维护；未开启三员，系统管理员可以维护
      const roleCode = openSecret ? 'SECURITYADMINISTRATOR' : 'ADMINISTRATOR'
      return this.userInfo.roles.findIndex((r) => r.code === roleCode) !== -1
    },
    orgGroupId() {
      return this.hierarchy[0]?.id || '-1'
    },
    showAction() {
      return (
        (this.curTabKey === '1' && this.orgGroupId === '-1' && this.isConfiger) ||
        this.curTabKey !== '1'
      )
    },
    disbaledStatus() {
      return this.curTabKey === '1'
        ? !this.globalRolesSelectedRowKeys.length
        : !this.localRolesSelectedRowKeys.length
    },
    actions() {
      let actions = []
      if (this.showAction && this.curTabKey !== '3') {
        actions = actions.concat([
          {
            label: '删除',
            id: 'delete',
            permission: null,
            type: TableActionTypes.batch,
            callback: this.deleteDocs,
          },
          {
            label: '成员用户',
            id: 'listUser',
            permission: null,
            type: TableActionTypes.inline,
            callback: this.listUser,
          },
          {
            label: '成员角色',
            id: 'listRole',
            permission: null,
            type: TableActionTypes.inline,
            callback: this.listRole,
          },
          {
            label: '授予',
            id: 'listAuthRole',
            permission: null,
            type: TableActionTypes.inline,
            callback: this.listAuthRole,
          },
          {
            label: '导入',
            id: 'import',
            permission: null,
            callback: () => {},
            children: [
              {
                label: '导入压缩包',
                id: 'importgz',
                permission: null,
                callback: () => {
                  this.importData('1')
                },
              },
              {
                label: '导入Excel',
                id: 'importexcel',
                permission: null,
                callback: () => {
                  this.importData('2')
                },
              },
            ],
          },
          {
            label: '导出',
            id: 'export',
            permission: null,
            type: TableActionTypes.batch,
            callback: () => {},
            children: [
              {
                label: '导出压缩包',
                id: 'exportgz',
                permission: null,
                callback: () => {
                  return this.exportData('1')
                },
              },
              {
                label: '导出Excel',
                id: 'exportexcel',
                permission: null,
                callback: () => {
                  return this.exportData('2')
                },
              },
            ],
          },
          {
            label: '新建',
            id: 'new',
            permission: null,
            type: 'primary',
            callback: this.addDoc,
          },
        ])
      } else if (!this.showAction && this.curTabKey !== '3') {
        actions.push({
          label: '成员用户',
          id: 'listUser',
          permission: null,
          type: TableActionTypes.inline,
          callback: this.listUser,
        })
      }
      return actions
    },
  },
  created() {
    if (this.hierarchyOptions[0]) {
      this.hierarchy = [{ ...this.hierarchyOptions[0] }]
    }
  },

  methods: {
    getSelectRowKeys() {
      let selectedRowKeys = []
      if (this.curTabKey === '1') {
        selectedRowKeys = this.$refs.globalRolesTable.getSelectedRowKeys()
      } else {
        selectedRowKeys = this.$refs.localRolesTable.getSelectedRowKeys()
      }
      return selectedRowKeys
    },
    hierarchyChange() {
      this.refresh()
    },
    tabsChange(key) {
      if (key === '1' && this.$refs.globalRolesTable) {
        this.$refs.globalRolesTable.clearSelection(true)
        this.$refs.globalRolesTable.refresh()
      } else if (key === '2' && this.$refs.localRolesTable) {
        this.$refs.localRolesTable.clearSelection(true)
        this.$refs.localRolesTable.refresh()
      } else if (key === '3') {
        this.$refs.rolesTree.init()
      }
    },
    processReq(req) {
      req.data.groupId = this.orgGroupId
      return req
    },
    search(value) {
      if (this.curTabKey === '1') {
        this.$refs.globalRolesTable.clearSelection(true)
      } else {
        this.$refs.localRolesTable.clearSelection(true)
      }

      this.customFilterExpressions = value
    },
    rowClick(record) {
      this.clickedRow = record.code.toString()
      const roleCode = record.code.toString()
      if (
        roleCode === 'SECURITYADMINISTRATOR' ||
        roleCode === 'ADMINISTRATOR' ||
        roleCode === 'SECURITYAUDITOR'
      ) {
        message.error('不能编辑系统内置管理员角色')
        return
      }

      this.$refs.detailForm.show(
        '角色管理',
        (this.curTabKey === '1' && this.orgGroupId === '-1' && this.isConfiger) ||
          this.curTabKey !== '1',
        this.clickedRow
      )
    },
    addDoc() {
      this.clickedRow = null
      this.depParent = this.parent
      this.$refs.detailForm.show('新建角色', true)
    },
    refresh() {
      this.tabsChange(this.curTabKey)
    },
    deleteDocs() {
      const selectedRowKeys = this.getSelectRowKeys()
      let containsEmbededRols = false
      for (let i = 0; i < selectedRowKeys.length; i++) {
        if (selectedRowKeys[i].substring(0, 3) !== 'G-1') {
          containsEmbededRols = true
          break
        }
      }

      if (containsEmbededRols === true) {
        message.error('不能删除系统内置角色')
        return
      }
      return new Promise((resolve) => {
        Modal.confirm({
          title: '您确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          okType: 'danger',
          onOk: () => {
            this.loadingMsg = message.loading({
              key: this.msgKey,
              content: '处理中...',
              duration: 0,
            })
            OrgService.roles.deleteDocs(selectedRowKeys).then((res) => {
              this.refresh()
              this.loadingMsg?.()
              resolve()
            })
          },
          onCancel: () => {
            resolve()
          },
        })
      })
    },
    listUser(record) {
      this.clickedRow = record.code
      this.$refs.assignUser.show(`成员用户列表-[${record.name}/${record.code}]`, this.curTabKey)
    },
    listRole(record) {
      this.clickedRow = record.code
      this.$refs.assignRole.show(`成员角色列表-[${record.name}/${record.code}]`, record.code)
    },
    listAuthRole(record) {
      this.clickedRow = record.code
      this.$refs.besignedRole.show(`角色列表-[${record.name}/${record.code}]`, record.code)
    },
    importData(key) {
      if (key === '1') {
        this.importDataUrl = `api/framework/v1/role-manager/import`
        this.importFormData[0].attr.allowType = '.gz'
        this.$refs.importForm.show(`导入压缩包`)
      } else {
        this.importDataUrl = `api/framework/v1/role-manager/import-excel`
        this.importFormData[0].attr.allowType = '.xls'
        this.$refs.importForm.show(`导入角色-excel`)
      }
    },

    exportData(key) {
      const selectedRowKeys = this.getSelectRowKeys()
      if (selectedRowKeys.length === 0) {
        message.error('请选择数据')
        return
      }
      if (key === '1') {
        return OrgService.roles.exportZip(selectedRowKeys).then((res) => {
          return download(
            `api/framework/v1/tmp-file/download/${res.data.id}`,
            `${res.data.name}`,
            true
          )
        })
      } else {
        return OrgService.roles.exportExcel(selectedRowKeys).then((res) => {
          return download(
            `api/framework/v1/tmp-file/download/${res.data.id}`,
            `${res.data.name}`,
            true
          )
        })
      }
    },
    save() {
      this.$refs.detailForm.save().then((success) => {
        if (success) {
          this.$refs.dataTable.clearSelection(true)
          this.$refs.dataTable.refresh()
          this.visible = false
        }
      })
    },
    init() {},
    updateSelectedDatas(record) {
      if (this.curTabKey === '1') {
        this.globalRolesSelectedRowKeys = record.map((item) => item.code)
      } else {
        this.localRolesSelectedRowKeys = record.map((item) => item.code)
      }
    },
    // 切换查询（高级查询、模糊查询）
    switchSearch() {
      if (this.advSearchBtnActived) {
        // 显示了高级查询，则重置
        this.$refs.searchForm.reset()
      } else {
        // 未显示高级查询，则置空模糊查询
        this.showfuzzySearch = false
        this.$refs.globalRolesTable?.onSearchChange('')
        this.$refs.localRolesTable?.onSearchChange('')
        this.$nextTick(() => {
          this.showfuzzySearch = true
        })
      }
      this.advSearchBtnActived = !this.advSearchBtnActived
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
@import '@/application-manage/advance-search.scss';
.header {
  margin-bottom: 10px;
}
.wrap {
  display: flex;
  height: 100%;

  .rightcontent {
    position: relative;
    width: 100%;
    height: 100%;
    overflow-y: auto;
    .group-switch {
      position: absolute;
      top: 24px;
      z-index: 2;
      display: inline-block;
    }
    .groupswitch {
      width: 150px;
      padding-top: 20px;
    }
    .search-form {
      display: inline-block;
      width: calc(100% - 150px);
    }
  }
}
.no-action {
  :global(.ant-modal-footer) {
    display: none;
  }
}
.searcharea {
  :global .ant-input-search {
    width: 200px;
    margin-left: 10px;
  }
}
.select {
  width: 150px;
}
.fuzzy-adv-search {
  .advsearchbtn {
    left: 360px;
  }
}
</style>
