<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 Category from '@/views/knowledge/document/components/Category.vue'
import { tags } from '@/views/knowledge/document/config'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { cloneDeep, debounce, isEmpty, remove } from 'lodash-es'
import { onBeforeUnmount, reactive, ref } from 'vue'
import DialogBox from '@/components/dialog-box/index.vue'


const props = withDefaults(defineProps<{
  ids?: any
}>(), {
  ids: []
})

// 定义组件事件，允许触发 submitHandle 事件
const emit = defineEmits(['submitHandle'])

// 定义一个响应式变量 dialogVisible，用于控制对话框的显示和隐藏
const dialogVisible = ref<boolean>(false)
// 定义一个响应式变量 formData，用于存储表单数据
const searchForm = ref<any>({})


// 定义一个响应式变量 loading，用于控制按钮的加载状态
const loading = ref<boolean>(false)

const submitLoading = ref<boolean>(false)
const documentData = ref<any>([{}])
const ids = ref<Array<string>>([])
const selectionList = 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,
      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())
    ids.value = []
    selectionList.value = []
    documentData.value = records.map((v: any) => {
      v.selected = props.ids.includes(v.id)
      if (v.selected) {
        ids.value.push(v.id)
        selectionList.value.push(v)
      }
      return v
    })
    paginationConfig.total = +total
  } 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)
    selectionList.value.push(row)
  } else {
    remove(ids.value, (id: string) => id === row.id)
    remove(selectionList.value, (c: any) => c.id === row.id)
  }
}

// 关闭对话框的方法
const close = () => {
  dialogVisible.value = false
}
const title = ref<string>('关联文档')
// 关闭对话框的方法
const open = () => {
  dialogVisible.value = true
  getPageData();
}

// 提交表单的方法
const submitHandle = async () => {
  try {
    emit('submitHandle', ids.value, selectionList.value)
    ElMessage.success('操作成功！')
    close()
  } catch (e) {
    console.error(e)
  }
}


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

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

// 暴露 open 和 closeDialog 方法给外部使用
defineExpose({ open, close })
</script>

<template>
  <dialog-box
    :dialogVisible="dialogVisible"
    :title="title"
    width="920"
    @close="dialogVisible = false"
  >
    <div class="dialog-doc">
      <el-space>
        <el-input v-model="searchForm.keyword" placeholder="搜索关键词" :prefix-icon="Search" style="width: 30%" @input="searchPageData" />
        <el-cascader
          v-model="searchForm.tag"
          :options="tags"
          :props="{ multiple: true }"
          clearable
          style="width: 30%"
        />
      </el-space>
      <div class="dialog-doc-wrap">
        <Category :view="true" @change-active="handleChangeCategory"/>
        <div class="dialog-doc-wrap-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"
            style="width: 100%"
            @changePage="getPageData"
            @sizeChange="handleSizeChange"
          >
            <el-table-column min-width="55">
              <template #default="{ row }">
                <el-checkbox
                  v-model="row.selected"
                  @change="(selected: boolean) => handleChangeSelect(selected, row)"
                ></el-checkbox>
              </template>
            </el-table-column>
            <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="modify_time">
              <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 align="left" fixed="right" label="操作" 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>
    <template #footer>
      <span class="dialog-footer res_el-dialog__footer">
        <el-button :loading="submitLoading" @click.prevent="close"> 取消 </el-button>
        <el-button :loading="submitLoading" type="primary" @click="submitHandle()">
          确定
        </el-button>
      </span>
    </template>
  </dialog-box>
</template>

<style lang="scss" scoped>
.dialog-doc {

  min-height: 500px;
  &-wrap {
    margin-top: 10px;
    margin-bottom: 15px;
    display: flex;
    min-height: 458px;
    border: 1px solid #eee;
    padding: 10px;
    border-radius: 6px;
    box-sizing: border-box;
    &-table {
      flex: 1;
      margin-left: 15px;
      position: relative;
    }
  }
}
</style>
