<script lang="ts" setup>
import AppTable from '@/components/app-table/index.vue'
import AutoTooltip from '@/components/auto-tooltip/index.vue'
import MdPreview from '@/components/markdown/MdPreview.vue'
import router from '@/router'
import api from '@/servers/finyx/api'
import DialogParagraph from '@/views/knowledge/dataset/components/DialogParagraph.vue'
import { ElMessage } from 'element-plus'
import { debounce, isEmpty, remove, unionBy } from 'lodash-es'
import Category from '../document/components/Category.vue'
import { computed, reactive, ref } from 'vue'
import ImportDocSteps from './components/ImportDocSteps.vue'
import { useRoute } from 'vue-router'

const { query } = useRoute()

const tableRef = ref<any>(null)

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

const importDocStepsRef = ref<any>(null)

const activeNumber = computed(() => importDocStepsRef.value?.activeNumber || 0)

const loading = ref<boolean>(false)
const searchForm = ref<any>({})
const documentData = ref<Array<any>>([])
const ids = ref<Array<string>>([])
const selectAll = ref<Array<any>>([])
const paginationConfig = reactive({
  current_page: 1,
  page_size: 10,
  total: 0
})

// 搜索按钮
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,
      knowledgeBaseId: query?.id,
      // importStatus: 'SUCCESS',
    },
    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 (!isEmpty(ids.value)) {
      documentData.value = records.map((v: any) => {
        v.selected = ids.value.includes(v.id)
        return v
      })
    }
  } catch (e) {
    ElMessage.error('获取文档列表失败！')
  } finally {
    loading.value = false
  }
}

const handleChangeCategory = (data: any) => {
  searchForm.value.category = data.id
  searchForm.value.categoryName = data.name
  handleSizeChange()
}

const handleSizeChange = () => {
  paginationConfig.current_page = 1
  getPageData()
}
const handleChangeSelect = (selected: boolean, row?: any) => {
  if (selected) {
    ids.value.push(row.id)
    selectAll.value.push(row)
  } else {
    remove(ids.value, (id: string) => id === row.id)
    remove(selectAll.value, (c: any) => c.id === row.id)
  }
}

const handleAllChangeSelect = (selected: boolean) => {
  // 获取本页数据ID集合
  const currentPageIds = documentData.value.map(item => item.id);

  if (selected) {
    // 选中状态：合并本页数据和已选中数据，并去重
    ids.value = [...new Set([...ids.value, ...currentPageIds])];
    console.log(ids.value)
    // 更新selectAll数组
    selectAll.value = unionBy([...selectAll.value, ...documentData.value], 'id');
    // 更新本页数据的选中状态
    documentData.value.forEach(item => {
      item.selected = true;
    });
  } else {
    // 取消选中状态：从已选中数据中移除本页数据
    ids.value = ids.value.filter(
      id => !currentPageIds.includes(id)
    );
    // 更新selectAll数组
    selectAll.value = selectAll.value.filter(
      item => !currentPageIds.includes(item.id)
    );
    // 更新本页数据的选中状态
    documentData.value.forEach(item => {
      item.selected = false;
    });
  }
}

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

const handleDelete = (row: any) => {
  remove(selectAll.value, (v: any) => v.id === row.id)
  remove(ids.value, (id: string) => id === row.id)
  documentData.value = documentData.value.map((v: any) => {
    v.selected = ids.value.includes(v.id)
    return v
  })
}

const subLoading = ref<boolean>(false)
const result = ref<any>([])
const showResult = computed(() => {
  //   从 result 里面寻找出 id 跟 target 相等的对象，否则return {}
  return result.value.find((v: any) => v.documentId === target.value) || { content: '', name: '' }
})

// 下一步
const handleChangeActiveNumber = debounce(async (i: number) => {
  if (i === 1) {
    try {
      subLoading.value = true
      const model: any = { id: query?.id, documentIds: ids.value }
      const data: any = await api.zhishiku.paras(model)
      result.value = data?.knowledgeDocumentResultVOList
      target.value = result.value[0]?.documentId
      importDocStepsRef.value.activeNumber = 1
    } catch (e) {
      ElMessage.error('文档解析分段失败！')
    } finally {
      subLoading.value = false
    }
  } else {
    importDocStepsRef.value.activeNumber = 0
  }
}, 500)

// 导入文档库
const handleSubmitImport = debounce(async () => {
  try {
    subLoading.value = true
    const model: any = {
      id: query?.id,
      documentIds: ids.value,
      knowledgeDocumentResultVOList: result.value
    }
    await api.zhishiku.importDocument(model)
    ElMessage.success('导入成功！')
    router.go(-1)
  } catch (e) {
    ElMessage.error('导入失败！')
  } finally {
    subLoading.value = false
  }
}, 500)

const target = ref<string>('')

// 使用 ref 创建一个响应式变量来跟踪鼠标悬停状态
const isHovered = ref<string>('')
const dialogParagraphRef = ref<any>(null)

const handlePreviewParagraph = (row: any) => {
  dialogParagraphRef.value.open({
    title: row.name,
    content: row.content,
    availableState: row.availableState,
    serial: row.sort,
    id: row.chunkId
  })
}
const handleChangeContent = (data: any) => {
  const targetItemIndex = result.value.findIndex((item: any) => item.documentId === target.value)
  if (targetItemIndex !== -1) {
    const targetItem: any = result.value[targetItemIndex] || {
      knowledgeDocumentSegmentResultVOS: []
    }
    const childIndex = targetItem?.knowledgeDocumentSegmentResultVOS.findIndex(
      (child: any) => child.chunkId === data.id
    )
    if (childIndex !== -1) {
      targetItem.knowledgeDocumentSegmentResultVOS[childIndex].content = data.content
    }
  }
}
</script>

<template>
  <div class="import-doc">
    <div class="import-doc-back pointer">
      <el-icon @click="router.go(-1)">
        <ArrowLeftBold />
      </el-icon>
      {{ query?.name }}
    </div>
    <ImportDocSteps ref="importDocStepsRef" />
    <div v-show="activeNumber === 0" v-loading="subLoading" class="import-doc-content">
      <div class="import-doc-content-center">
        <Category :view="true" @change-active="handleChangeCategory" />
        <div class="import-doc-content-center-table">
          <el-row style="margin-top: 16px; margin-bottom: 10px">
            <el-col :lg="6" :md="6" :sm="8" :xs="12">
              <el-input
                v-model="searchForm.keyword"
                placeholder="请输入关键词"
                @input="searchPageData"
              />
            </el-col>
          </el-row>
          <!--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
            ref="tableRef"
            :data="documentData"
            :pagination-config="paginationConfig"
            style="width: 100%"
            @changePage="getPageData"
            @sizeChange="handleSizeChange"
          >
            <el-table-column min-width="55">
              <template #header>
                <el-checkbox
                  @change="(selected: boolean) => handleAllChangeSelect(selected)"
                ></el-checkbox>
              </template>
              <template #default="{ row }">
                <el-checkbox
                  v-model="row.selected"
                  @change="(selected: boolean) => handleChangeSelect(selected, row)"
                  :disabled="row.usedState"
                ></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="文档名称" min-width="220">
              <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">
              <template #default="{ row }">
                <AutoTooltip>
                  {{ row.format }}
                </AutoTooltip>
              </template>
            </el-table-column>
            <el-table-column label="文件大小" min-width="120">
              <template #default="{ row }">
                <AutoTooltip>
                  {{ row.size }}
                </AutoTooltip>
              </template>
            </el-table-column>

            <el-table-column align="left" fixed="right" label="操作" min-width="120">
              <template #default="{ row }">
                <div>
                  <span
                    class="mr-10 primary-text"
                    style="cursor: pointer"
                    @click="handlePreview(row)"
                  >
                    预览
                  </span>
                </div>
              </template>
            </el-table-column>
          </app-table>
        </div>
      </div>

      <div class="import-doc-content-right">
        <div class="import-doc-content-right-title">已选文档</div>
        <div class="import-doc-content-right-list">
          <div v-for="(item, i) in selectAll" :key="i" class="import-doc-content-right-list-item">
            <p class="name">{{ item.name }}</p>
            <el-icon class="pointer" @click="handleDelete(item)">
              <CircleCloseFilled />
            </el-icon>
          </div>
        </div>
      </div>
    </div>
    <div v-show="activeNumber === 1" v-loading="subLoading" class="import-doc-content-two">
      <div class="import-doc-content-two-select">
        <el-select v-model="target" placeholder="请选择文档" style="width: 240px">
          <el-option v-for="item in result" :key="item.documentId" :label="item.name" :value="item.documentId" />
        </el-select>
      </div>
      <div class="import-doc-content-two-warp">
        <div class="import-doc-content-two-warp-preview">
          <div class="title">{{ showResult?.name }}</div>
          <md-preview
            :modelValue="showResult?.content"
            class="maxkb-md"
            editorId="preview-only"
            style="padding: 20px 30px"
          ></md-preview>
        </div>
        <div class="import-doc-content-two-warp-paragraph">
          <div
            v-for="(item, i) in showResult?.knowledgeDocumentSegmentResultVOS || []"
            :key="i"
            class="import-doc-content-two-warp-paragraph-item pointer"
            @mouseenter="isHovered = item.chunkId"
            @mouseleave="isHovered = ''"
          >
            <div class="title">#{{ item.sort }} {{ item.size }}字符</div>
            <MdPreview
              :modelValue="item.content || ''"
              class="maxkb-md"
              editorId="preview-only"
            />
            <div
              :class="{ visible: isHovered === item.chunkId }"
              class="footer pointer"
              @click="handlePreviewParagraph(item)"
            >
              查看详情
              <el-icon>
                <Right />
              </el-icon>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="import-doc-footer">
      <el-space v-if="activeNumber === 0">
        <el-button @click="router.go(-1)">取消</el-button>
        <el-button
          :disabled="subLoading"
          :loading="subLoading"
          type="primary"
          @click="handleChangeActiveNumber(1)"
        >
          下一步
        </el-button>
      </el-space>
      <el-space v-else>
        <el-button @click="handleChangeActiveNumber(0)">上一步</el-button>
        <el-button
          :disabled="subLoading"
          :loading="subLoading"
          type="primary"
          @click="handleSubmitImport"
          >导入知识库
        </el-button>
      </el-space>
    </div>
  </div>
  <DialogParagraph ref="dialogParagraphRef" @update-content="handleChangeContent" />
</template>

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

  &-back {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 20px;

    .el-icon {
      margin-right: 6px;
    }
  }

  &-content {
    display: flex;
    height: calc(100% - 140px);

    &-center {
      width: 80%;
      display: flex;
      border: 1px solid #eee;
      padding-right: 1%;

      &-table {
        width: 81%;
        margin-left: 1%;
      }
    }

    &-right {
      width: 19%;
      margin-left: 1%;
      padding: 12px;
      border: 1px solid #eee;

      &-title {
        height: 29px;
        display: flex;
        align-items: center;
      }

      &-list {
        height: calc(100% - 30px);
        overflow-y: auto;

        &-item {
          height: 32px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          border-radius: 6px 6px 6px 6px;
          border: 1px solid #dfe0e3;
          padding-left: 12px;
          padding-right: 12px;
          margin-bottom: 12px;
          font-weight: 400;
          font-size: 14px;
          color: #333333;
          line-height: 20px;
          box-sizing: border-box;

          .name {
            flex: 1;
            display: inline-block;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
            margin-right: 10px;
          }

          .el-icon {
            width: 14px;
          }
        }
      }
    }

    &-two {
      height: calc(100% - 140px);

      &-select {
        width: 100%;
        text-align: right;
        margin-bottom: 15px;
      }

      &-warp {
        height: calc(100% - 47px);
        display: flex;
        gap: 10px;

        &-preview {
          flex: 1;
          padding: 20px;
          border: 1px solid rgba(0, 0, 0, 0.08);
          font-weight: 500;
          font-size: 14px;
          color: #333333;
          line-height: 25px;
          overflow-y: scroll;

          .title {
            margin-bottom: 10px;
          }
        }

        &-paragraph {
          flex: 1;
          margin-left: 10px;
          overflow-y: auto;

          &-item {
            padding: 20px;
            border: 1px solid rgba(0, 0, 0, 0.08);
            margin-bottom: 10px;
            position: relative;

            .title {
              margin-bottom: 10px;
            }

            .footer {
              font-weight: 500;
              font-size: 12px;
              color: #3067ef;
              position: absolute;
              right: 10px;
              bottom: 5px;
              margin-top: 4px;
              opacity: 0; /* 默认隐藏 */
              transform: translateY(10px); /* 初始位置下移 */
              transition:
                opacity 0.3s ease,
                transform 0.3s ease; /* 添加过渡效果 */
            }

            .visible {
              opacity: 1;
              transform: translateY(0);
            }
          }
        }
      }
    }
  }

  &-footer {
    margin-top: 15px;
    text-align: right;
  }
}
</style>
