<template>
  <div :class="[$style.wrapHeight, $style.dataclass]">
    <div :class="$style.rowHeight">
      <div :class="$style.rightcard">
        <a-card>
          <!-- 高级搜索组件 -->
          <audit-advanced-query
            :expand="expand"
            :search-data="formData"
            :ref-name="searchform"
            :search-style="{ height: '150px', left: '20px', top: '57px' }"
            :search-fun="handleSearch"
            @searchedClick="searchedClick"
          >
            <template>
              <a-col :span="12">
                <a-form-model-item :label="'业务名称'" prop="indexName">
                  <a-input v-model="formData.indexName" allow-clear />
                </a-form-model-item>
              </a-col>
            </template>
          </audit-advanced-query>
          <SdDataTableEx
            :key="key"
            ref="dataTable"
            :projectlist="true"
            :editnode="editnode"
            form-id="iamSearchCategoryidIndexname"
            page-id="audit\maintain\iamSearchCategoryidIndexname"
            :columns="columns"
            :actions="actions"
            :filter-expressions="expressions"
            :search-fields="['indexName']"
            :show-advance-query="true"
            :show-selection="(item) => item.editAndDeleteAuth !== 0"
            @searchbtnClick="searchbtnClick"
          >
            <template slot="categoryName" slot-scope="text, record">
              <a
                v-if="record.editAndDeleteAuth !== 0"
                @click="
                  () => {
                    $refs.dataTable.showDetailModal(record.id, pageId)
                  }
                "
                >{{ text }}</a
              >
              <span v-else>{{ text }}</span>
            </template>

            <!-- 详情表单 -->
            <template
              v-slot:form="{ model }"
              v-sd-watermark="waterMark"
              :modalProps="{ height: 800 }"
              @saved="onSaved"
            >
              <!-- 业务名称 -->
              <SdFormItem label="业务名称" name="indexName">
                <a-select
                  v-model="model.indexName"
                  show-search
                  :default-active-first-option="false"
                  :filter-option="false"
                  :not-found-content="null"
                  @search="getIndexNameList"
                  @change="searchedClick"
                >
                  <a-select-option
                    v-for="(item, i) in indexNameList"
                    :key="item.id"
                    class="selectoption"
                    :value="item.indexName"
                    >{{ item.indexName }}</a-select-option
                  >
                </a-select>
              </SdFormItem>
              <a-form-model-item label="业务编号">
                <a-input v-model="model.id" :disabled="true" />
              </a-form-model-item>
              <SdFormItem
                label="业务编码"
                name="id"
                :hidden="true"
                :input-props="{ disabled: true }"
              />
              <SdFormItem label="索引名称" name="indexRemark" :input-props="{ disabled: true }" />
              <SdFormItem label="系统名称" name="systemName" :input-props="{ disabled: true }" />
              <SdFormItem name="indexSource" :input-props="{ disabled: true }" />
              <SdFormItem name="type" :input-props="{ disabled: true }">
                <!-- 下拉框 -->
                <a-select :value="model.type" :disabled="true">
                  <a-select-option :value="0">非结构化</a-select-option>
                  <a-select-option :value="1">结构化</a-select-option>
                </a-select>
              </SdFormItem>
              <!-- 分类id -->
              <SdFormItem name="categoryId" :hidden="true" :input-props="{ disabled: true }" />
              <!--分类名称 -->
              <!-- systemId -->
              <SdFormItem name="systemId" :hidden="true" :input-props="{ disabled: true }" />
              <!-- id -->
            </template>
            <!-- 索引类型 0 非结构化  1 结构化 -->
            <template slot="type" slot-scope="text, record">
              <span v-if="record.type === 0 || record.type === '0'">非结构化</span>
              <span v-else>结构化</span>
            </template>
          </SdDataTableEx>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import { Modal, message } from 'ant-design-vue'
import axios from '@/common/services/axios-instance'
import auditAdvancedQuery from '../../components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '../../components/audit-advanced-query-mixins'
import auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import SdDataTableEx from '@/common/components/sd-data-table-ex.vue'
import SdFormItem from '@/common/components/sd-form-item.vue'
import dataService from './data-config'
import TableActionTypes from '@/common/services/table-action-types'

export default {
  name: 'AuditClassIndex',
  metaInfo: {
    title: '审搜索引',
  },
  components: {
    SdDataTableEx,
    SdFormItem,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins, auditAdvancedGroupMixins],
  data() {
    return {
      editnode: true,
      key: 0,
      searchform: 'searchform',
      formData: {
        indexName: '',
        categoryId: '',
      },
      pageId: 'audit' + '/' + 'maintain' + '/' + 'iamSearchCategoryidIndexname',
      auditOrgId: null,
      parentId: 0,
      parentCategoryId: '000000',
      level: 1,
      isEnd: null,
      indexNameList: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '业务编号',
          dataIndex: 'id',
        },
        {
          title: '索引名',
          dataIndex: 'indexName',
        },
        {
          title: '索引说明',
          dataIndex: 'indexRemark',
        },
        {
          title: '系统名称',
          dataIndex: 'systemName',
        },
        {
          title: '系统来源名称',
          dataIndex: 'indexSource',
        },
        {
          title: '索引类型',
          dataIndex: 'type',
          scopedSlots: { customRender: 'type' },
        },
        {
          title: '归属分类名称',
          dataIndex: 'categoryName',
        },
        // 分类id
        {
          title: '分类编码',
          dataIndex: 'categoryId',
          sdHidden: true,
        },
      ],
      actions: [
        {
          label: '添加审搜索引',
          permission: 'create',
          id: 'new',
          type: TableActionTypes.primary,
          callback: this.create,
        },

        {
          label: '解绑',
          id: 'delete',
          permission: 'delete',
          // type: TableActionTypes.ex.delete, // 删除按钮，不需要回调，会自动处理（对sd-data-table无效）
          callback: () => {
            const ids = this.$refs.dataTable.getSelectedRowKeys()
            const idJson = ids.join(',')
            if (ids.length === 0) {
              return message.warning('请选择要解绑的数据')
            }
            Modal.confirm({
              title: '提示',
              content: '确认解除绑定？',
              onOk: () => {
                dataService.unbindIndex(idJson).then((res) => {
                  if (res.data.length === 0) {
                    message.success('解绑成功')
                    this.$refs.dataTable.refresh()
                  } else {
                    Modal.confirm({
                      title: '提示',
                      content:
                        res.data.join(',') +
                        '已有授权操作无法进行解绑，请重新选择要解绑的索引后重试。',
                      okText: '确定',
                      cancelText: '',
                    })
                  }
                })
              },
            })
          },
        },
      ],
      expressions: [],
      isroot: true,
      className: '',
      onSaveForm: {
        id: '',
        indexName: '',
        indexRemark: '',
        systemName: '',
        indexSource: '',
        type: '',
        categoryName: '',
        categoryId: '',
      },
      onIndex: '',
    }
  },
  created() {
    this.formData.categoryId = this.$route.query.classId
    //
    this.handleSearch()
    this.getIndexNameList()
  },
  methods: {
    // 选中
    searchedClick(val) {
      // 根据val获取对应列表里的数据
      const indexAttr = this.indexNameList.find((item) => item.indexName === val)
      // 如果已经categoryid 不为空或者null则提示该索引已绑定其他分类
      if (indexAttr.categoryId === null || indexAttr.categoryId === '') {
        //
        this.$refs.dataTable.getDetailModal().SdForm.model = {
          ...this.$refs.dataTable.getDetailModal().SdForm.model,
        }
        // 如果model内有indexAttr同名字段则重新赋值
        for (const key in indexAttr) {
          if (Object.keys(this.$refs.dataTable.getDetailModal().SdForm.model).includes(key)) {
            this.$refs.dataTable.getDetailModal().SdForm.model[key] = indexAttr[key]
          }
        }
        // categoryid 为分类id categoryNmae 为分类名称
        this.$refs.dataTable.getDetailModal().SdForm.model.categoryId = this.$route.query.classId
        this.$refs.dataTable.getDetailModal().SdForm.model.categoryName = this.$route.query.className
      } else {
        // 清空indexName
        this.$refs.dataTable.getDetailModal().SdForm.model.indexName = ''
        return message.warning('该索引已绑定其他分类')
      }
      // 如果
      // 获取表单详情
    },
    getIndexNameList(value = '') {
      const params = {
        columns:
          'sortNum,id,indexName,indexRemark,systemName,indexSource,type,categoryName,categoryId,systemId',
        maxResults: 9999,
        startPosition: 0,
        expressions: [
          {
            dataType: 'str',
            name: 'indexName',
            op: 'like',
            stringValue: '%' + value + '%',
          },
        ],
        buttonExpressions: [],
        formId: 'iamSearchCategoryidIndexname',
      }
      dataService.findIndexList(params).then((res) => {
        this.indexNameList = res.data.data
        // 过滤掉已经绑定的索引
        this.indexNameList = this.indexNameList.filter((item) => {
          return item.categoryId === null || item.categoryId === ''
        })
      })
    },
    handleSearch() {
      this.expressions = []

      // 业务名称
      this.formData.indexName &&
        this.expressions.push({
          dataType: 'str',
          name: 'indexName',
          op: 'like',
          stringValue: '%' + this.formData.indexName + '%',
        })
      // 分类id
      this.formData.categoryId &&
        this.expressions.push({
          dataType: 'str',
          name: 'categoryId',
          op: 'like',
          stringValue: `%${this.formData.categoryId}%`,
        })
    },

    // 新增
    create() {
      this.key++
      this.getIndexNameList()
      this.$nextTick(() => {
        this.$refs.dataTable.showDetailModal(null, 'audit/maintain/iamSearchCategoryidIndexname')
      })
    },

    refresh() {
      this.$refs.dataTable.refresh()
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.wrap-height {
  height: 100%;

  .row-height {
    display: flex;
    flex: auto;
    height: 100%;

    .rightcard {
      flex: 1;
      width: calc(100% - 20%);
      height: 100%;
    }
  }
}

.dataclass {
  :global(.projectlist .ant-table-empty .ant-table-body) {
    overflow-x: hidden !important;
  }

  :global(span > .ant-btn:nth-child(2)) {
    color: #fff;
    background-color: #1890ff;
    border-color: #1890ff;
  }

  // :global(.ant-table-placeholder) {
  //   width: auto;
  // }
}
</style>
