<template>
  <div class="document-page">
    <Category class="category" @change-active="handleChangeCategory" />
    <div class="document-page-content">
      <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="7" :xl="7">
          <el-form-item label="导入状态:" label-width="auto">
            <el-select
              v-model="searchForm.importStatus"
              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="6" :xl="6">
          <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="6" :xl="6">
          <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="ids.length <= 0" @click="handleBatchMove">
                    <el-icon>
                      <Switch />
                    </el-icon>
                    批量移动
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button
              :icon="Plus"
              type="primary"
              @click="
                go('knowledgeUploadDoc', {
                  categoryName: searchForm.categoryName,
                  category: searchForm.category
                })
              "
              >上传文档
            </el-button>
          </el-space>
        </el-col>
      </el-row>
      <div class="document-page-content-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="width: 100%; font-size: 312px" />
        </lz-page-empty>
        <!-- table列表和分页-->
        <app-table
          v-else
          :data="documentData"
          :pagination-config="paginationConfig"
          :tableDefaultHeight="230"
          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="120" prop="create_id">
            <template #default="{ row }">
              <AutoTooltip>
                {{ row.format }}
              </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.importStatus" />
            </template>
          </el-table-column>
          <el-table-column label="上传时间" min-width="180" prop="modify_time">
            <template #default="{ row }">
              <AutoTooltip>
                {{ row.createdTime }}
              </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="操作" min-width="220">
            <template #default="{ row }">
              <div>
                <el-button
                  link
                  type="primary"
                  @click="handlePreview(row)"
                  :disabled="!['SUCCESS', 'TAGGING'].includes(row.importStatus)"
                  v-if="row.importStatus !== 'FAILED'"
                >
                  预览
                </el-button>
                <el-button
                  type="primary"
                  link
                  @click="handleTag(row)"
                  v-if="row.importStatus !== 'FAILED'"
                  :disabled="!['SUCCESS'].includes(row.importStatus)"
                >
                  标签
                </el-button>
                <el-button
                  type="primary"
                  link
                  @click="handleMove(row)"
                  v-if="row.importStatus !== 'FAILED'"
                  :disabled="!['SUCCESS'].includes(row.importStatus)"
                >
                  移动
                </el-button>
                <el-button
                  type="primary"
                  link
                  @click="handleDelete(row)">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </app-table>
      </div>
    </div>

    <DialogForm
      ref="dialogFormRef"
      :moveCurrentId="searchForm.category"
      move-label="目标类目"
      title="文档移动"
      type="move"
      @submit-handle="handleMoveSubmit"
    />
    <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/index'
import DialogTag from '@/views/knowledge/components/DialogTag.vue'
import { Plus, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { debounce, map } from 'lodash-es'
import { onBeforeUnmount, reactive, ref } from 'vue'
import DialogForm from '../components/DialogForm.vue'
import Category from './components/Category.vue'
import ImportStatus from './components/ImportStatus.vue'
import { importStatus, tags } from './config'

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

const timer = ref<number>(0)

const searchForm = ref<any>({
  keyword: '',
  category: '',
  categoryName: '',
  importStatus: ''
})

const loading = ref<boolean>(true)
const documentData = ref<any>([])
// 多条记录id
const ids = ref<Array<string>>([])
// 单挑记录id
const id = ref<string>('')
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,
      categoryId: searchForm.value.category,
      importStatus: searchForm.value.importStatus,
      tag: searchForm.value.tag
    },
    size: page_size,
    current: current_page
  }
  return model
}

const getPageData = async () => {
  try {
    loading.value = true
    const { records, total } = await api.wendang.page8(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
  }
}
// 轮询列表查询状态
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 handleChangeCategory = (data: any) => {
  searchForm.value.category = data.id
  searchForm.value.categoryName = data.name
  handleSizeChange()
}

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

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

const handlePreview = (row: any) => {
  go('knowledgeReviewDoc', { id: row.id })
}
const dialogTagRef = ref<any>(null)
const handleTag = async (row: any) => {
  const data = await api.wendang.queryDocumentLabelIds({ id: row.id })
  id.value = row.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 dialogFormRef = ref<any>(null)
const handleMove = (row: any) => {
  id.value = row.id
  dialogFormRef.value.open()
}
const handleBatchMove = () => {
  dialogFormRef.value.open()
}
const handleMoveSubmit = async (data: any) => {
  try {
    loading.value = true
    const model: any = {
      categoryId: data.target
    }
    if (id.value) {
      model.ids = [id.value]
    } else {
      model.ids = ids.value
    }
    await api.wendang.moveCategory(model)
    dialogFormRef.value.close()
    ElMessage.success('文档移动成功！')
    await getPageData()
  } catch (e: any) {
    ElMessage.error('文档移动失败！')
  } finally {
    id.value = ''
    loading.value = false
  }
}
const handleDelete = async (row: any) => {
  const confirm = await ElMessageBox.confirm('文档删除后不可恢复，请谨慎操作', {
    title: '确认删除文档',
    type: 'warning'
  })
  if (confirm) {
    try {
      loading.value = true
      await api.wendang.delete6([row.id])
      ElMessage.success('文档删除成功！')
      await getPageData()
    } catch (e) {
      ElMessage.error('文档删除失败！')
    } finally {
      loading.value = false
    }
  }
}
const handleBatchDelete = async (row: any) => {
  const confirm = await ElMessageBox.confirm('文档删除后不可恢复，请谨慎操作', {
    title: '确认删除文档',
    type: 'warning'
  })
  if (confirm) {
    try {
      loading.value = true
      await api.wendang.delete6(ids.value)
      ElMessage.success('文档删除成功！')
      await getPageData()
    } catch (e) {
      ElMessage.error('文档删除失败！')
    } finally {
      loading.value = false
    }
  }
}
</script>

<style lang="scss" scoped>
.document-page {
  display: flex;
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  :deep(.el-button.is-link:hover) {
    color: #3067EF !important;
  }
  &-content {
    width: 84%;
    margin-left: 1%;

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