<template>
  <div class="bm-main-box">
    <div class="flex items-center">
      <div class="bm-main-box-title">文档</div>
    </div>
    <template v-if="!state.stage.show">
      <CzrContent
        v-model:tableHead="state.query.head"
        @handleReset="onReset"
        @handleSearch="onSearch"
      >
        <template #tableTitle>
          <div class="flex gap-2.5">
            <CzrButton
              type="add"
              title="添加文件"
              @click="
                $router.push({
                  name: '18e6009c-a72c-4359-864b-e7725fccca69',
                  params: {
                    id: ID,
                  },
                })
              "
            />
            <CzrButton
              type="add"
              title="添加分段"
              @click="() => (state.detail.show = true)"
            />
            <CzrButton title="迁移" icon="move" @click="onKnowledge()" />
            <CzrButton title="归档" icon="cloud" />
            <CzrButton
              type="del"
              title="删除"
              icon="czr_del"
              @click="onDel()"
            />
          </div>
        </template>
        <template #buttons>
          <div class="flex items-center gap-2.5">
            <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 #name-column-value="{ scope }">
              <div class="flex justify-center">
                <template v-if="scope.row.indexingStatus === 'completed'">
                  <CzrButton
                    type="table"
                    :title="scope.row.name"
                    @click="onStage(scope.row)"
                  />
                </template>
                <template v-else>
                  {{ scope.row.name }}
                </template>
              </div>
            </template>
            <template #caozuo-column-value="{ scope }">
              <div class="__czr-table-operations">
                <template v-if="scope.row.indexingStatus === 'archived'">
                  <CzrButton
                    type="table"
                    title="撤销归档"
                    @click="onUnArchive(scope.row)"
                  />
                </template>
                <template v-if="scope.row.indexingStatus === 'completed'">
                  <CzrButton
                    type="table"
                    title="归档"
                    @click="onArchive(scope.row)"
                  />
                </template>
                <CzrButton
                  type="table"
                  title="重命名"
                  @click="onRename(scope.row)"
                />
                <CzrButton
                  type="table"
                  title="迁移"
                  @click="onKnowledge(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"
      />
      <moveSelectCom
        v-model:show="state.moveSelect.show"
        :transfer="state.moveSelect.transfer"
        @refresh="onSearch"
      />
    </template>
    <template v-else>
      <stageIndexCom
        v-model:show="state.stage.show"
        :document="state.stage.document"
      />
    </template>
  </div>
</template>

<script setup lang="ts">
import {
  computed,
  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 moveSelectCom from './move-select.vue'
import stageIndexCom from './stage-index.vue'
import {
  documentArchive,
  documentDocsDelete,
  documentGetDocumentsByPage,
  documentNoArchive,
} from '@/api/modules/knowledge/document'

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, width: 200 },
      { value: 'wordCount', label: '字符数', show: true, width: 100 },
      {
        value: 'indexingStatus',
        label: '状态',
        show: true,
        width: 100,
        dictList: computed(() => DictionaryStore.indexingStatusList),
      },
      { value: 'recallCount', label: '召回次数', show: true, width: 100 },
      {
        value: 'isUse',
        label: '启用/停用',
        show: true,
        width: 100,
        dictList: computed(() => DictionaryStore.documentUseList),
      },
      { value: 'p1', 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: {
      ID: ID,
    },
  },
  rename: {
    show: false,
    transfer: {},
  },
  moveSelect: {
    show: false,
    transfer: {},
  },
  stage: {
    show: false,
    document: {},
  },
})
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
  documentGetDocumentsByPage(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 onDel = (row: any = null) => {
  if (row) {
    DialogStore.confirm({
      title: '删除确认',
      content: `是否删除文档：${row.name}？<br/>此文档下的${row.segmentCount}个分段都会被删除，请谨慎操作。`,
      onSubmit: () => {
        documentDocsDelete([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: () => {
        documentDocsDelete(state.query.selected.map((v) => v.id))
          .then(() => {
            ElMessage.success('删除成功！')
          })
          .catch(() => {})
          .finally(() => {
            onSearch()
          })
      },
    })
  }
}
const onArchive = (row: any = null) => {
  if (row) {
    DialogStore.confirm({
      title: '归档确认',
      content: `是否归档文档：${row.name}？<br/>归档后的数据就只能查看或删除，无法重新编辑，请谨慎操作。`,
      onSubmit: () => {
        documentArchive([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: () => {
        documentArchive(state.query.selected.map((v) => v.id))
          .then(() => {
            ElMessage.success('归档成功！')
          })
          .catch(() => {})
          .finally(() => {
            onSearch()
          })
      },
    })
  }
}
const onUnArchive = (row: any = null) => {
  DialogStore.confirm({
    title: '撤销归档确认',
    content: `是否撤销归档：${row.name}？<br/>撤销归档后的数据，可重新编辑，请谨慎操作。`,
    onSubmit: () => {
      documentNoArchive([row.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.moveSelect.transfer = {
      row: JSON.parse(JSON.stringify(row)),
      type: 'text',
    }
    state.moveSelect.show = true
  } else {
    if (state.query.selected.length === 0) {
      ElMessage.warning('请至少选择一条记录！')
      return
    }
    state.moveSelect.transfer = {
      list: [...state.query.selected],
      type: 'text',
    }
    state.moveSelect.show = true
  }
}
const onStage = (row) => {
  state.stage.document = JSON.parse(JSON.stringify(row))
  state.stage.show = true
}
onMounted(() => {
  initDictionary()
  onReset()
})
const initDictionary = () => {
  DictionaryStore.initDict('document_use')
  DictionaryStore.initDict('indexing_status')
}
</script>

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