<template>
  <div
    class="flex flex-col rounded-lg bg-[var(--czr-dialog-bg)] p-4"
    v-loading="state.query.loading"
  >
    <div>
      <CzrFormColumn
        class="__czr-table-form-column"
        label-width="0px"
        :span="8"
        :offset="16"
        v-model:param="state.text"
        placeholder="按名称搜索"
        :prefix-icon="Search"
      />
    </div>
    <div
      class="mt-2 grid max-h-[600px] flex-1 grid-cols-2 gap-4 overflow-y-auto"
    >
      <template v-for="item in state.query.result.data">
        <div
          class="__hover relative col-span-1 flex flex-col overflow-hidden rounded-lg border-1 border-[#E6E8EA] px-6 py-4"
          :class="{
            'border-[var(--czr-main-color)]': state.selectedMap.has(item.id),
          }"
          @click="onSelect(item)"
        >
          <div class="flex">
            <img
              src="@/assets/images/knowledge/knowledge-item-icon.png"
              class="mr-2.5 size-11"
            />
            <div class="flex flex-1 flex-col justify-around overflow-hidden">
              <div class="flex items-center">
                <div class="flex-1 text-xl font-bold text-[#2E3238]" v-title>
                  {{ item.name }}
                </div>
              </div>
              <div
                class="flex items-center gap-2.5 text-[0.75rem] text-[#6F7889]"
              >
                <div>文档数:{{ item.docCount }}</div>
                <div>|</div>
                <div>字符:{{ item.wordCounts }}</div>
                <div>|</div>
                <div>创建者：{{ item.userName }}</div>
              </div>
            </div>
          </div>
          <div
            class="mt-2.5 mb-auto text-sm text-[#606266]"
            style="line-height: 1.4rem"
            v-title="{ lines: 2 }"
          >
            {{ item.description }}
          </div>
          <template v-if="state.selectedMap.has(item.id)">
            <div
              class="absolute top-0 right-0 h-[2rem] w-[2rem] bg-[url('@/assets/images/knowledge/checked.png')]"
            ></div>
          </template>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  computed,
  getCurrentInstance,
  nextTick,
  onMounted,
  reactive,
  ref,
  watch,
} from 'vue'
import { useAppStore, useDialogStore, useDictionaryStore } from '@/stores'
import { useRouter } from 'vue-router'
import { datasetsGetAllByPage } from '@/api/modules/knowledge'
import CzrFormColumn from '@/components/czr-ui/CzrFormColumn.vue'
import { Search } from '@element-plus/icons-vue'
import { debounce } from 'lodash'

const router = useRouter()
const DictionaryStore = useDictionaryStore()
const DialogStore = useDialogStore()
const AppStore = useAppStore()
const emit = defineEmits(['update:show', 'refresh'])
const { proxy } = getCurrentInstance()
const props = defineProps({
  multiple: { default: false },
  ids: { default: () => <any>[] },
})
const state: any = reactive({
  selectedMap: new Map(),
  text: '',
  query: {
    init: false,
    loading: false,
    page: {
      pageNum: 1,
      pageSize: 20,
    },
    form: {},
    formReal: {},
    result: {
      total: 0,
      data: [],
    },
  },
})
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 onSearch = () => {
  state.query.formReal = JSON.parse(JSON.stringify(state.query.form))
  onPage(1, 100000)
}
const onPage = (pageNum, pageSize) => {
  setTimeout(() => {
    state.query.init = true
  }, 100)
  state.query.page = {
    pageNum: pageNum,
    pageSize: pageSize,
  }
  const params = {
    tenantId: AppStore.tenantInfo?.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
  datasetsGetAllByPage(params)
    .then(({ data }: any) => {
      state.query.result.total = data.totalElements
      state.query.result.data = data.content.filter(
        (v) => !props.ids.includes(v.id),
      )
    })
    .catch(() => {})
    .finally(() => {
      state.query.loading = false
    })
}
const onSelect = (row) => {
  if (state.selectedMap.has(row.id)) {
    state.selectedMap.delete(row.id)
  } else {
    if (!props.multiple) {
      state.selectedMap.clear()
    }
    state.selectedMap.set(row.id, row)
  }
}
const getData = () => {
  return Array.from(state.selectedMap.values())
}
onMounted(() => {
  onSearch()
})
defineExpose({
  getData,
})
</script>

<style lang="scss" scoped></style>
