<template>
  <a-card>
    <a-tabs v-model="activeKey" @change="tagChange">
      <a-tab-pane key="all" tab="全局">
        <sd-data-table
          ref="dataTable"
          :actions="role ? actions : actionsSubAll"
          data-url="api/framework/v1/page/businessList"
          :process-req="processReq"
          show-selection
          :columns="computedColumns"
          :row-key="'id'"
          :search-fields="['regex', 'regexName']"
          @rowClick="rowClick"
        >
        </sd-data-table>
        <sd-detail-modal
          ref="verifyDetail"
          :record-id="recordId"
          page-id="comp/strvalid/weStrValidRule"
          :modal-props="{ width: 800 }"
          @saved="save"
        >
          <sd-form-item name="id" :hidden="true" />
          <sd-form-item name="regex" />
          <sd-form-item name="regexName" />
          <sd-form-item name="sortNum" />
          <sd-form-item name="status" />
        </sd-detail-modal>
      </a-tab-pane>
      <a-tab-pane v-if="!role" key="local" tab="本地">
        <sd-data-table
          ref="dataTableLocal"
          :actions="actions"
          data-url="api/framework/v1/page/businessList"
          :process-req="processReq"
          show-selection
          :columns="computedColumns"
          :row-key="'id'"
          :search-fields="['regex', 'regexName']"
          @rowClick="rowClick"
        >
          <template slot="headerPrefix">
            <sd-select
              v-model="hierarchy"
              :options="hierarchyOptions"
              :class="$style.select"
              @change="hierarchyChange"
            />
          </template>
        </sd-data-table>
        <sd-detail-modal
          ref="verifyDetail"
          :record-id="recordId"
          page-id="comp/strvalid/weStrValidRule"
          :modal-props="{ width: 800 }"
          @saved="save"
        >
          <sd-form-item name="id" :hidden="true" />
          <sd-form-item name="regex" />
          <sd-form-item name="regexName" />
          <sd-form-item name="sortNum" />
          <sd-form-item name="status" />
          <sd-form-item name="belongedOrgId" :hidden="true"> </sd-form-item>
        </sd-detail-modal>
      </a-tab-pane>
    </a-tabs>
  </a-card>
</template>

<script>
import { Modal, Message } from 'ant-design-vue'
import TableActionTypes from '@/common/services/table-action-types'
import { getUserInfo } from '@/common/store-mixin'
import WorkbenchService from '@/workbench/workbench-service'
import components from './_import-components/sd-verify-rule-manage-import'
const columns = [
  {
    dataIndex: 'id',
    title: 'ID',
    sdHidden: true,
  },
  {
    title: '正则表达式',
    dataIndex: 'regex',
  },
  {
    title: '正则表达式名称',
    dataIndex: 'regexName',
    sdClickable: true,
  },
  {
    title: '排序号',
    dataIndex: 'sortNum',
    defaultSortOrder: 'ascend',
  },
  {
    title: '状态',
    dataIndex: 'status',
  },
  {
    title: '所属分级机构ID',
    dataIndex: 'belongedOrgId',
    sdHidden: true,
  },
]
export default {
  name: 'SdVerifyRuleManage',
  metaInfo: {
    title: '校验规则维护',
  },
  components,
  data() {
    return {
      activeKey: 'all',
      columns,
      recordId: null,
      // 角色
      role: 0,
      actions: [
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.primary,
          permission: null,
          callback: () => {
            this.recordId = null
            return new Promise((resolve) => {
              this.$refs.verifyDetail.show()
              resolve()
            }).then((res) => {
              if (this.activeKey === 'local') {
                setTimeout(() => {
                  this.$refs.verifyDetail.setFieldValue('belongedOrgId', Number(this.orgGroupId))
                }, 1000)
              }
            })
          },
        },
        {
          label: '删除',
          id: 'delete',
          permission: null,
          type: TableActionTypes.batch,
          callback: (keys) => {
            this.delete(keys)
          },
        },
      ],
      // 下级管理员全局tab页隐藏新建等操作
      actionsSubAll: [],
      // 下级管理员兼职分级组织时分别查询
      hierarchy: [],
    }
  },
  computed: {
    computedColumns() {
      this.columns.map((col) => {
        if (col.dataIndex === 'regexName') {
          if (this.activeKey === 'all' && this.role === 0) {
            col.sdClickable = false
          } else col.sdClickable = true
        }
      })
      return this.columns
    },
    // 下拉框选项
    hierarchyOptions() {
      return (getUserInfo().belongedOrgIds || []).map((item) => ({
        id: item.id,
        name: item.text,
        title: item.text,
      }))
    },
    orgGroupId() {
      return this.hierarchy[0]?.id || '-1'
    },
  },
  created() {
    this.getRole()
    if (this.hierarchyOptions[0]) {
      this.hierarchy = [{ ...this.hierarchyOptions[0] }]
    }
  },
  methods: {
    hierarchyChange() {
      this.$refs.dataTableLocal.refresh()
    },
    rowClick(record) {
      this.recordId = record.id
      this.$refs.verifyDetail.show()
    },
    refresh() {
      this.tagChange(this.curTabKey)
    },
    getRole() {
      for (const item of getUserInfo().roles) {
        if (item.code === 'ADMINISTRATOR') {
          this.role = 1
          break
        } else this.role = 0
      }
    },
    processReq(req) {
      req.data.expressions = this.handleParams(req)
      req.data.formId = 'weStrValidRule'
      return req
    },
    handleParams(req) {
      const params = [...req.data.expressions]
      const isLocal = this.activeKey === 'all' ? '1' : '0'
      params.push({
        dataType: 'str',
        name: 'type',
        op: 'eq',
        stringValue: isLocal,
      })
      params.push({
        dataType: 'long',
        name: 'belongedOrgId',
        op: 'eq',
        longValue: Number(this.orgGroupId),
      })
      return params
    },
    tagChange(key) {
      this.activeKey = key
    },
    save() {
      if (this.activeKey === 'local') {
        this.$refs.verifyDetail.setFieldValue('belongedOrgId', Number(this.orgGroupId))
      }
      Message.success('保存成功')
      if (this.activeKey === 'all') this.$refs.dataTable.refresh()
      else this.$refs.dataTableLocal.refresh()
    },
    delete(keys) {
      Modal.confirm({
        title: '您确定删除这项内容吗？',
        content: '删除这条数据后，就无法恢复初始的状态。',
        okText: '删除',
        okType: 'danger',
        onOk: () => {
          WorkbenchService.deleteVerify({ ids: keys.join(',') }).then((result) => {
            if (result.data) {
              Message.success('删除成功！')
              if (this.activeKey === 'all') this.$refs.dataTable.refresh()
              else this.$refs.dataTableLocal.refresh()
            }
          })
        },
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.select {
  width: 150px;
}
</style>
