<template>
  <div class="document-page">
    <div class="document-page">
      <el-row :gutter="10">
        <el-col :xs="12" :sm="12" :md="4" :xl="4">
          <el-form-item label-width="auto">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入关键词"
              @input="searchPageData"
              :prefix-icon="Search"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="5" :xl="5">
          <el-form-item label="导入状态:" label-width="auto">
            <el-select
              v-model="searchForm.state"
              placeholder="请选择"
              @change="searchPageData"
            >
              <el-option
                v-for="item in importStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="5" :xl="5">
          <el-form-item label="启用状态:" label-width="auto">
            <el-select
              v-model="searchForm.useState"
              placeholder="请选择"
              @change="searchPageData"
            >
              <el-option
                v-for="item in enableStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="5" :xl="5">
          <el-form-item label="标签:" label-width="auto">
            <el-cascader
              v-model="searchForm.tag"
              :options="tagData"
              :props="{ multiple: true, label: 'name', value: 'id', children: 'flabelList' }"
              clearable
              filterable
              collapse-tags
              @change="searchPageData"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="5" :xl="5">
          <el-space>
            <el-dropdown>
              <el-button>
                批量操作
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :disabled="ids.length <= 0" @click="handleBatchDelete"
                  >
                    <el-icon>
                      <Delete />
                    </el-icon>
                    批量删除
                  </el-dropdown-item>
                  <el-dropdown-item :disabled="batchParsingDisabled" @click="handleBatchParsing"
                  >
                    <el-icon>
                      <Refresh />
                    </el-icon>
                    批量解析
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button :icon="Plus" type="primary" @click="importDoc"
            >导入文档
            </el-button>
          </el-space>
        </el-col>
      </el-row>
      <div class="document-page-table">
        <!--loading-->
        <div
          v-if="loading"
          v-loading="loading"
          class="loading-page"
          element-loading-text="正在加载..."
          style="width: 100%; height: calc(100vh - 250px)"
        ></div>
        <!--搜索结果-->
        <lz-page-empty v-else-if="!documentData.length && !loading" type="5" >
          <lz-svg-icon icon-class="empty2" style="font-size: 312px;" />
        </lz-page-empty>
        <!-- table列表和分页-->
        <app-table
          v-else
          :data="documentData"
          :pagination-config="paginationConfig"
          :tableDefaultHeight="320"
          class="mt-16"
          style="width: 100%"
          @changePage="getPageData"
          @sizeChange="handleSizeChange"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="文件名称" min-width="220" prop="name">
            <template #default="{ row }">
              <span @click="handlePreview(row)">
                <AutoTooltip style="color: #3067ef; cursor: pointer">
                  {{ row.name }}
                </AutoTooltip>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="启用状态" min-width="100" prop="create_id">
            <template #default="{ row }">
              <AutoTooltip>
                <el-switch v-model="row.useState" @change="handleChangeState(row)" />
              </AutoTooltip>
            </template>
          </el-table-column>
          <el-table-column label="文件大小" min-width="120" prop="modify_time">
            <template #default="{ row }">
              <AutoTooltip>
                {{ row.size }}
              </AutoTooltip>
            </template>
          </el-table-column>
          <el-table-column label="导入状态" min-width="120" prop="modify_time">
            <template #default="{ row }">
              <ImportStatus :status="row.parasStatus" />
            </template>
          </el-table-column>
          <el-table-column label="更新时间" min-width="180" prop="modify_time">
            <template #default="{ row }">
              <AutoTooltip>
                {{ row.updatedTime }}
              </AutoTooltip>
            </template>
          </el-table-column>
          <el-table-column label="创建人" min-width="120" prop="modify_time">
            <template #default="{ row }">
              <AutoTooltip>
                {{ row.crateName }}
              </AutoTooltip>
            </template>
          </el-table-column>
          <el-table-column align="left" fixed="right" label="操作" width="280">
            <template #default="{ row }">
              <div>
                <span
                  v-if="row.parasStatus === 'PARSING'"
                  class="mr-10 primary-text"
                  style="cursor: pointer"
                  @click="handleParsing(row)"
                >
                  解析
                </span>
                <span
                  class="mr-10 primary-text"
                  style="cursor: pointer"
                  @click="handlePreview(row)"
                >
                  预览
                </span>
                <el-button
                  link
                  type="primary"
                  @click="handleParagraph(row)"
                  :disabled="row.parasStatus !== 'SUCCESS'"
                >
                  查看分段
                </el-button>
                <el-button link type="primary" style="cursor: pointer" @click="handleTag(row)">
                  标签
                </el-button>
                <el-button link type="primary" style="cursor: pointer" @click="handleDelete(row)">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </app-table>
      </div>
    </div>
    <DialogTag ref="dialogTagRef" @submit-handle="handleSubmitTag" />
  </div>
</template>

<script lang="ts" setup>
import AppTable from '@/components/app-table/index.vue'
import AutoTooltip from '@/components/auto-tooltip/index.vue'
import router from '@/router'
import api from '@/servers/finyx/api'
import DialogTag from '@/views/knowledge/components/DialogTag.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { debounce, map } from 'lodash-es'
import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'
import { importStatus, tags, enableStatus } from '../../document/config'
import ImportStatus from '../../document/components/ImportStatus.vue'
import { useRoute } from 'vue-router'
import useStore from '@/stores'

const { knowledge } = useStore();
const { query } = useRoute();
const go = (name: string, query?: any) => {
  router.push({ name, query })
}

const searchForm = ref<any>({
  keyword: '',
  useState: '',
  knowledgeId: query?.id,
  state: ''
})
const timer = ref<number>(0)
const loading = ref<boolean>(false)
const documentData = ref<any>([])
const ids = ref<Array<any>>([])
const id = ref<string>('')
const selectAll = ref<Array<any>>([])
const paginationConfig = reactive({
  current_page: 1,
  page_size: 10,
  total: 0
})

const tagData = ref<any>([])
const getTagData = async () => {
  try {
    tagData.value = await api.weidu.query10({})
  } catch (e) {
    ElMessage.error('获取数据失败！')
  } finally {
  }
}
getTagData();

// 搜索按钮
const searchPageData = debounce(() => {
  handleSizeChange()
}, 300)

const getListParams = () => {
  const { current_page, page_size } = paginationConfig
  const model: any = {
    model: {
      name: searchForm.value.keyword,
      state: searchForm.value.state,
      useState: searchForm.value.useState,
      knowledgeId: query?.id,
    },
    size: page_size,
    current: current_page
  }
  return model
}


const getPageData = async () => {
  try {
    loading.value = true
    const { records, total } = await api.zhishikuwendang.page4(getListParams())
    documentData.value = records
    paginationConfig.total = +total
    // 列表数据 包含非最终状态数据，开启轮询，且不影响列表操作
    if (records.some((v: any) => ['IMPORTING', 'PROCESSING', 'TAGGING'].includes(v.importStatus))) {
      clearInterval(timer.value)
      pollStatus()
    } else {
      clearInterval(timer.value)
    }
  } catch (e) {
    ElMessage.error('获取文档列表失败！')
  } finally {
    loading.value = false
  }
}

onMounted(getPageData)

// 轮询列表查询状态
const pollStatus = () => {
  timer.value = setInterval(async () => {
    try {
      const { records } = await api.wendang.page8(getListParams())
      // 循环 documentData.value 和 records 对比，状态有不一样的 则使用records里的状态更新
      documentData.value.forEach((v: any) => {
        const target = records.find((item: any) => item.id === v.id)
        if (target && v.importStatus !== target.importStatus) {
          Object.assign(v, target)
        }
      })
    } catch (e) {
      ElMessage.error('获取文档列表失败！')
    }
  }, 2000)
}

// 退出页面清除loading状态
onBeforeUnmount(() => {
  clearInterval(timer.value)
})

const handleSizeChange = () => {
  paginationConfig.current_page = 1
  getPageData()
}

const handleSelectionChange = (val: any) => {
  ids.value = val.map((v: any) => v.id)
  selectAll.value = val
}

const handlePreview = (row: any) => {
  go('knowledgeReviewDoc', { id: row.documentId })
}
const handleParagraph = (row: any) => {
  go('knowledgeDatasetViewParagraph', { id: row.documentId })
}

const handleChangeState = async (row: any) => {
  try {
    await api.zhishikuwendang.update2({ id: row.id, knowledgeId: query?.id as number, useState: row.useState })
  } catch (e) {
    ElMessage.error('更新知识库文档状态失败')
  }
}


const dialogTagRef = ref<any>(null)
const handleTag = async (row: any) => {
  const data = await api.wendang.queryDocumentLabelIds({ id: row.id })
  id.value = row.id
  // todo 需要处理维度名称和维度id
  dialogTagRef.value.open(map(data || [], (v: any) => ({ ...v, wId: v.dimensionId, wName: v.dimensionName })))
}

const handleSubmitTag = async (ids: any) => {
  try {
    const model: any = { ids, id: id.value }
    await api.wendang.updateLabels(model)
    ElMessage.success('文档打标签成功！')
    await getPageData()
  } catch (e) {
    ElMessage.error('文档打标签失败！')
  } finally {
    id.value = ''
  }
}
const handleDelete = async (row: any) => {
  const confirm = await ElMessageBox.confirm('知识库文档删除后不可恢复，请谨慎操作', {
    title: '确认删除知识库文档',
    type: 'warning'
  })
  if (confirm) {
    try {
      loading.value = true
      await api.zhishikuwendang.delete2([row.id])
      ElMessage.success('知识库文档删除成功')
      await getPageData()
    } catch (e: any) {
      ElMessage.success('知识库文档删除失败')
    } finally {
      loading.value = false
    }
  }
}
const handleBatchDelete = async () => {
  const confirm = await ElMessageBox.confirm('知识库文档删除后不可恢复，请谨慎操作', {
    title: '确认删除知识库文档',
    type: 'warning'
  })
  if (confirm) {
    try {
      loading.value = true
      await api.zhishikuwendang.delete2(ids.value)
      ElMessage.success('知识库文档删除成功')
      await getPageData()
    } catch (e: any) {
      ElMessage.success('知识库文档删除失败')
    } finally {
      loading.value = false
    }
  }
}

const handleParsing = async (row: any) => {
  const confirm = await ElMessageBox.confirm('确认解析知识库文档', {
    title: '确认解析知识库文档',
    type: 'warning'
  })
  if (confirm) {
    try {
      loading.value = true
      const model: any = { id: query?.id, documentIds: [row.documentId] }
      await api.zhishiku.paras(model)
      ElMessage.success('知识库文档解析中...')
      await getPageData()
    } catch (e: any) {
      ElMessage.success('知识库文档解析失败')
    } finally {
      loading.value = false
    }
  }
}
const batchParsingDisabled = computed(() => ids.value.length <= 0 || selectAll.value.some((v: any) => v.parasStatus !== 'PARSING'))
const handleBatchParsing = async () => {
  // if (selectAll.value.some((v: any) => v.parasStatus !== 'PARSING')) {
  //   ElMessage.error('所选文档中存在已解析的文档')
  //   return
  // }
  const confirm = await ElMessageBox.confirm('确认解析知识库文档', {
    title: '确认解析知识库文档',
    type: 'warning'
  })
  if (confirm) {
    try {
      loading.value = true
      const model: any = { id: query?.id, documentIds: selectAll.value.map((v: any) => v.documentId) }
      await api.zhishiku.paras(model)
      ElMessage.success('知识库文档解析中...')
      await getPageData()
    } catch (e: any) {
      ElMessage.success('知识库文档解析失败')
    } finally {
      loading.value = false
    }
  }
}
const importDoc = () => {
  knowledge.setCategory({ id: '', name: '' })
  go('knowledgeDatasetImportDoc', { id: query?.id, name: query?.name })
}
</script>

<style lang="scss" scoped>
.document-page {
  height: 100%;

  :deep(.el-button.is-link:hover) {
    color: #3067EF !important;
  }

  &-search {
    width: 100%;
    display: flex;
    align-items: center;

    &-action {
      width: 200px;
      margin-left: 10px;
    }
  }

  &-table {
    height: calc(100% - 32px);
    position: relative;
  }
}
</style>
