<template>
  <CusDialog
    :show="show"
    title="索引构成"
    @onClose="$emit('update:show', false)"
    width="90%"
    height="90%"
    :show-submit="false"
    :loading="state.loading"
  >
    <div class="__cus-manage_content">
      <div class="__cus-manage_content-filters" v-loading="state.loadingIndex">
        <el-row>
          <CusFormColumn
            :span="2"
            v-model:param="state.type"
            link="select"
            :options="DictionaryStore.serviceTypeList"
            @change="initIndex"
            :clearable="false"
          />
          <el-col :span="22">
            <el-autocomplete
              ref="ref_search"
              v-model="state.indexSelect"
              :fetch-suggestions="fetchSuggestions"
              clearable
              placeholder="搜索添加索引"
              @select="handleSelect"
              :select-when-unmatched="true"
            >
              <template #default="{ item }">
                <div class="index-item" v-html="item.html"/>
              </template>
            </el-autocomplete>
          </el-col>
        </el-row>
      </div>
      <div class="__cus-manage_content-main" v-loading="state.query.loading">
        <CusTable
          :data="state.query.result.data"
          :table-head="state.query.tableHead"
          :no-page="true"
        >
          <template #type-column-value="{scope}">
            {{DictionaryStore.serviceTypeMap.get(scope.row.type)}}
          </template>
          <template #isMain-column-value="{scope}">
            {{DictionaryStore.isMainIndexMap.get(scope.row.isMain)}}
          </template>
          <template #do-column-value="{scope}">
            <CusButton v-if="scope.row.isMain == 1" type="table-add" icon="text" title="主配置" @click="onMain(scope.row)"/>
            <CusButton v-if="scope.row.type === 'inner_index'" type="table-add" icon="text" title="列配置" @click="onText(scope.row)"/>
            <CusButton type="table-edit" @click="onEdit(scope.row)"/>
            <CusButton type="table-del" @click="onDel(scope.row)"/>
          </template>
        </CusTable>
      </div>
    </div>
    <RelationDetailCom v-model:show="state.relationDetail.show" :transfer="state.relationDetail.transfer" @refresh="initRelation"/>
    <RelationColumnCom v-model:show="state.relationColumn.show" :transfer="state.relationColumn.transfer" @refresh="initRelation"/>
    <RelationMainCom v-model:show="state.relationMain.show" :transfer="state.relationMain.transfer" @refresh="initRelation"/>
  </CusDialog>
</template>

<script setup lang="ts">
import {computed, getCurrentInstance, nextTick, reactive, ref, watch} from "vue";
import {useDictionaryStore} from "@/stores";
import {ElMessage, ElMessageBox} from "element-plus";
import RelationDetailCom from "./relation-detail.vue";
import RelationColumnCom from "./relation-column.vue";
import RelationMainCom from "./relation-main.vue";
import {
  sysLabelDeleteLink,
  sysLabelGetAllIndexsByKey
} from "@/api/modules/manage/type";
import {sysThemeFind, sysThemeIndexDelete, sysThemeIndexFindAll} from "@/api/modules/manage/theme";

const emit = defineEmits(['update:show', 'refresh'])
const {proxy} = getCurrentInstance()
const DictionaryStore = useDictionaryStore()
const props = defineProps({
  show: {default: false},
  transfer: {}
 })
const state: any = reactive({
  loading: false,
  type: 'inner_index',  // outside_service
  query: {
    loading: false,
    tableHead: [
      {value: "type", label: "数据类型", width: 120},
      {value: "indexTableName", label: "索引英文", popover: true},
      {value: "indexName", label: "数据名称"},
      {value: "indexNameShort", label: "数据简称"},
      {value: "isMain", label: "主数据"},
      {value: "weight", label: "权重"},
      {value: "fieldName", label: "关联数据"},
      {value: "description", label: "关系描述"},
      // {value: "indexName", label: "索引名称"},
      // {value: "indexNameShort", label: "索引简称"},
      // {value: "isMain", label: "主索引"},
      // {value: "fieldName", label: "关联索引"},
      // {value: "weight", label: "权重"},
      // {value: "description", label: "关系描述"},
      {value: "do", label: "操作", width: 360, fixed: 'right'},
    ],
    result: {
      data: []
    }
  },
  form: {},
  loadingIndex: false,
  indexList: [],
  indexSelect: '',
  relationDetail: {
    transfer: {},
    show: false
  },
  relationColumn: {
    transfer: {},
    show: false
  },
  relationMain: {
    transfer: {},
    show: false
  }
})
const ref_search = ref()
const fetchSuggestions = (queryString: string, cb: any) => {
  const arr = state.indexList.filter(v => state.query.result.data.every(s => s.indexId != v.id))
  const results = queryString
    ? arr.filter(v => [v.indexName, v.indexTableName].some(s => s.includes(queryString)))
    : arr
  results.map(v => {
    const str1 = queryString ? v.indexName.replace(new RegExp(queryString, 'g'), `<em>${queryString}</em>`) : v.indexName
    const str2 = queryString ? v.indexTableName.replace(new RegExp(queryString, 'g'), `<em>${queryString}</em>`) : v.indexTableName
    v.html = `${str1}<span style="margin-right: 20px;"></span>${str2}`
    return v
  })
  cb(results)
}
const handleSelect = (item) => {
  state.relationDetail.transfer = {
    type: state.type,
    mode: 'add',
    indexId: item.id,
    indexTableName: item.indexTableName,
    indexName: item.indexName,
    themeId: props.transfer.id,
    conditionOptions: state.form.themeParam,
    relationOptions: state.query.result.data.map(v => ({dictLabel: v.indexName, dictValue: v.id})),
    hasMain: state.query.result.data.some(v => v.isMain == 1) || state.type !== 'inner_index'
  }
  state.relationDetail.show = true
}
const initIndex = () => {
  state.loadingIndex = true
  setTimeout(() => {
    sysLabelGetAllIndexsByKey(proxy.$util.formatGetParam({type: state.type})).then(res => {
      state.indexList = res.data
      state.loadingIndex = false
    })
  }, 100)
}
const initRelation = () => {
  state.query.loading = true
  sysThemeIndexFindAll(props.transfer.id).then(res => {
    state.query.result.data = res.data
    state.query.loading = false
  })
}
const onMain = (row) => {
  state.relationMain.transfer = {
    indexId: row.indexId,
    id: row.id,
    indexStyle: row.indexStyle
  }
  state.relationMain.show = true
}
const onText = (row) => {
  state.relationColumn.transfer = {
    indexId: row.indexId,
    themeId: props.transfer.id
  }
  state.relationColumn.show = true
}
const onEdit = (row) => {
  let hasMain = false
  state.query.result.data.forEach(v => {
    if (v.isMain == 1) {
      if (v.id != row.id) {
        hasMain = true
      }
    }
  })
  state.relationDetail.transfer = {
    type: row.type,
    mode: 'edit',
    id: row.id,
    indexTableName: row.indexTableName,
    indexName: row.indexName,
    conditionOptions: state.form.themeParam,
    relationOptions: state.query.result.data.filter(v => v.id !== row.id).map(v => ({dictLabel: v.indexName, dictValue: v.id})),
    hasMain: hasMain || row.type !== 'inner_index'
  }
  state.relationDetail.show = true
}
const onDel = (row) => {
  ElMessageBox.confirm(`请确认是否删除${row.indexName}?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  } as any).then(() => {
    state.loading = true
    sysThemeIndexDelete(row.id).then(res => {
      ElMessage.success('删除成功！')
      emit('refresh')
      state.loading = false
      initRelation()
    })
  }).catch(() => {})
}
const initDetail = () => {
  state.loading = true
  sysThemeFind(props.transfer.id).then(res => {
    state.form = res.data
    if (state.form.themeType == '2') {
      state.form.themeParam = state.form.themeParam.split(',')
    }
    state.loading = false
  })
}
watch(() => props.show, (n) => {
  initDictionary()
  if (n) {
    initIndex()
    initRelation()
    initDetail()
  }
})
const initDictionary = () => {
  DictionaryStore.initDict('is_main_index')
  DictionaryStore.initDict('service_type')
}
</script>

<style lang="scss" scoped>
.__cus-manage_content {
  margin-bottom: 0;
  height: calc(100% - 24px);
}
</style>
