<template>
  <div class="bm-main-box">
    <div class="flex items-center">
      <div class="bm-main-box-title">问答</div>
    </div>
    <CzrContent
      v-model:tableHead="state.query.head"
      @handleReset="onReset"
      @handleSearch="onSearch"
    >
      <template #tableTitle>
        <div class="flex gap-[var(--czr-gap)]">
          <CzrButton type="add" title="创建问题" @click="onAdd" />
          <CzrButton title="迁移" icon="move" @click="onKnowledge()" />
          <CzrButton type="del" title="删除" icon="czr_del" @click="onDel()" />
        </div>
      </template>
      <template #buttons>
        <div class="flex items-center gap-[var(--czr-gap)]">
          <CzrForm class="bm-filter" label-width="0px" @handleEnter="onSearch">
            <CzrFormColumn
              width="15.63rem"
              class="__czr-table-form-column"
              :span="24"
              label-width="0px"
              v-model:param="state.text"
              placeholder="按问答名称搜索"
              :prefix-icon="Search"
            />
          </CzrForm>
        </div>
      </template>
      <template #table>
        <CzrTable
          v-loading="state.query.loading"
          :data="state.query.result.data"
          :head="state.query.head"
          :total="state.query.result.total"
          :page="state.query.page.pageNum"
          :pageSize="state.query.page.pageSize"
          @handlePage="onPage"
          v-model:selected="state.query.selected"
        >
          <template #caozuo-column-value="{ scope }">
            <div class="__czr-table-operations">
              <CzrButton
                type="table"
                title="重命名"
                @click="onRename(scope.row)"
              />
              <CzrButton
                type="table"
                title="迁移"
                @click="onKnowledge(scope.row)"
              />
              <CzrButton type="table" title="编辑" @click="onEdit(scope.row)" />
              <CzrButton type="table-del" @click="onDel(scope.row)" />
            </div>
          </template>
        </CzrTable>
      </template>
    </CzrContent>
    <detailCom
      v-model:show="state.detail.show"
      :transfer="state.detail.transfer"
      @refresh="onSearch"
    />
    <renameCom
      v-model:show="state.rename.show"
      :transfer="state.rename.transfer"
      @refresh="onSearch"
    />
    <knowledgeSelectCom
      v-model:show="state.knowledge.show"
      :transfer="state.knowledge.transfer"
      @refresh="onSearch"
    />
  </div>
</template>

<script setup lang="ts">
import {
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  ref,
  watch,
} from 'vue'
import { Search } from '@element-plus/icons-vue'
import { debounce } from 'lodash'
import { useDialogStore, useDictionaryStore } from '@/stores'
import { ElMessage } from 'element-plus'
import detailCom from './detail.vue'
import renameCom from './rename.vue'
import knowledgeSelectCom from '../document/knowledge-select.vue'
import { qaGetQaPage, qaQaDocsDelete } from '@/api/modules/knowledge/qa'

const DialogStore = useDialogStore()
const DictionaryStore = useDictionaryStore()
const emit = defineEmits([])
const props = defineProps({
  knowledge: <any>{},
})
const { proxy }: any = getCurrentInstance()
const ID = inject('ID')
const state: any = reactive({
  text: '',
  query: {
    init: false,
    loading: false,
    head: [
      { value: 'name', label: '文件名称', show: true },
      {
        value: 'createTime',
        label: '创建时间',
        show: true,
        width: 180,
        datetime: true,
      },
      {
        value: 'updateTime',
        label: '更新时间',
        show: true,
        width: 180,
        datetime: true,
      },
      {
        value: 'caozuo',
        label: '操作',
        show: true,
        width: 300,
        fixed: 'right',
        popover: false,
      },
    ],
    page: {
      pageNum: 1,
      pageSize: 20,
    },
    form: {},
    formReal: {},
    result: {
      total: 0,
      data: [],
    },
    selected: [],
  },
  detail: {
    show: false,
    transfer: {},
  },
  rename: {
    show: false,
    transfer: {},
  },
  knowledge: {
    show: false,
    transfer: {},
  },
})
const setText = debounce((v) => {
  state.query.form.name = v
}, 1000)
watch(
  () => state.text,
  (n) => {
    setText(n)
  },
)
watch(
  () => state.query.form,
  (n) => {
    if (state.query.init) {
      onSearch()
    }
  },
  { deep: true },
)
const onPage = (pageNum, pageSize) => {
  setTimeout(() => {
    state.query.init = true
  }, 100)
  state.query.page = {
    pageNum: pageNum,
    pageSize: pageSize,
  }
  const params = {
    datasetId: ID,
    page: state.query.page.pageNum,
    size: state.query.page.pageSize,
  }
  //  添加表单参数
  for (const [k, v] of Object.entries(state.query.formReal)) {
    if (proxy.$czrUtil.isValue(v)) {
      params[k] = v
    }
  }
  state.query.loading = true
  qaGetQaPage(params)
    .then(({ data }: any) => {
      state.query.result.total = data.totalElements
      state.query.result.data = data.content
    })
    .catch(() => {})
    .finally(() => {
      state.query.loading = false
    })
}
const onSearch = () => {
  state.query.selected = []
  state.query.formReal = JSON.parse(JSON.stringify(state.query.form))
  onPage(1, state.query.page.pageSize)
}
const onReset = () => {
  state.query.page = {
    pageNum: 1,
    pageSize: 20,
  }
  state.query.form = {}
  onSearch()
}
const onAdd = () => {
  state.detail.transfer = {
    mode: 'add',
    ID: ID,
  }
  state.detail.show = true
}
const onEdit = (row) => {
  state.detail.transfer = {
    mode: 'edit',
    id: row.id,
  }
  state.detail.show = true
}
const onDel = (row: any = null) => {
  if (row) {
    DialogStore.confirm({
      title: '删除确认',
      content: `是否删除问答：${row.name}？<br/>请谨慎操作。`,
      onSubmit: () => {
        qaQaDocsDelete([row.id])
          .then(() => {
            ElMessage.success('删除成功！')
          })
          .catch(() => {})
          .finally(() => {
            onSearch()
          })
      },
    })
  } else {
    if (state.query.selected.length === 0) {
      ElMessage.warning('请至少选择一条记录！')
      return
    }
    DialogStore.confirm({
      title: '删除确认',
      content: `是否批量删除${state.query.selected.length}个问答？<br/>请谨慎操作。`,
      onSubmit: () => {
        qaQaDocsDelete(state.query.selected.map((v) => v.id))
          .then(() => {
            ElMessage.success('删除成功！')
          })
          .catch(() => {})
          .finally(() => {
            onSearch()
          })
      },
    })
  }
}
const onRename = (row) => {
  state.rename.transfer = {
    id: row.id,
    name: JSON.parse(JSON.stringify(row.name)),
  }
  state.rename.show = true
}
const onKnowledge = (row: any = null) => {
  if (row) {
    state.knowledge.transfer = {
      row: JSON.parse(JSON.stringify(row)),
      type: 'qa',
    }
    state.knowledge.show = true
  } else {
    if (state.query.selected.length === 0) {
      ElMessage.warning('请至少选择一条记录！')
      return
    }
    state.knowledge.transfer = {
      list: [...state.query.selected],
      type: 'qa',
    }
    state.knowledge.show = true
  }
}
onMounted(() => {
  initDictionary()
  onReset()
})
const initDictionary = () => {}
</script>

<style lang="scss" scoped>
.knowledge {
  width: 100%;
  height: 11.81rem;
  background-image: url('@/assets/images/knowledge-item-bg.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  padding: 1rem 1.5rem;
}
</style>
