<template>
  <div class="bm-main-box">
    <div class="flex items-center">
      <div class="bm-main-box-title">{{ $route.meta.title }}</div>
      <div class="ml-auto flex items-center gap-[var(--czr-gap)]">
        <div
          class="__hover flex items-center gap-[0.3rem] text-[0.88rem] text-[#576275]"
          @click="state.query.form.isCreate = !state.query.form.isCreate"
        >
          <SvgIcon
            name="czr_add1"
            size="14"
            :active="state.query.form.isCreate"
          />我的创建
        </div>
        <div
          class="__hover flex items-center gap-[0.3rem] text-[0.88rem] text-[#576275]"
          @click="state.query.form.isStar = !state.query.form.isStar"
        >
          <SvgIcon
            name="star"
            size="15"
            class="mb-[2px]"
            :active="state.query.form.isStar"
          />我的收藏
        </div>
        <CzrForm class="bm-filter" label-width="0px" @handleEnter="onSearch">
          <CzrFormColumn
            width="6.68rem"
            class="__czr-table-form-column"
            :span="24"
            label-width="0px"
            v-model:param="state.query.form.groupId"
            link="select"
            :options="DictionaryStore.knowledgeGroups.list"
            placeholder="全部分组"
          />
          <CzrFormColumn
            width="6.68rem"
            class="__czr-table-form-column"
            :span="24"
            label-width="0px"
            v-model:param="state.query.form.tagIds"
            link="select"
            :options="DictionaryStore.knowledgeTags.list"
            placeholder="全部标签"
          />
          <CzrFormColumn
            width="15.63rem"
            class="__czr-table-form-column"
            :span="24"
            label-width="0px"
            v-model:param="state.text"
            placeholder="按名称搜索"
            :prefix-icon="Search"
          />
        </CzrForm>
      </div>
    </div>
    <div
      class="mt-[1rem] flex-1 overflow-hidden"
      v-loading="state.query.loading"
    >
      <CzrTableCard
        class="table-card"
        :page="state.query.page.pageNum"
        :pageSize="state.query.page.pageSize"
        :total="state.query.result.total"
        :data="state.query.result.data"
        @handlePage="onPage"
        :col="4"
      >
        <template #model="{ row, index }">
          <template v-if="row.empty">
            <div
              class="knowledge __hover flex items-center justify-center"
              @click="onAdd"
            >
              <img src="@/assets/images/knowledge-item-add.png" />
              <span
                class="ml-[var(--czr-gap)] text-[1.25rem] text-[var(--czr-main-color)]"
                >创建知识库</span
              >
            </div>
          </template>
          <template v-else>
            <div
              class="__hover knowledge flex flex-col"
              @click="
                $router.push({
                  name: '78430247-a531-4c8f-8a08-c88e93a836e2',
                  params: {
                    id: index,
                  },
                })
              "
            >
              <div class="flex">
                <img
                  src="@/assets/images/knowledge-item-icon.png"
                  class="mr-[var(--czr-gap)] h-[3.25rem] w-[3.25rem]"
                />
                <div
                  class="flex flex-1 flex-col justify-around overflow-hidden"
                >
                  <div class="text-[1.25rem] font-bold text-[#2E3238]" v-title>
                    {{ row.name }}
                  </div>
                  <div class="text-[0.75rem] text-[#6F7889]">
                    创建者：{{ row.userName }}
                  </div>
                </div>
                <div class="mt-[0.25rem] ml-auto">
                  <tagsSelect
                    :value="row.tags"
                    @onChange="(tags) => onChangeTag(row, tags)"
                  />
                </div>
              </div>
              <div
                class="mt-[var(--czr-gap)] mb-auto text-[0.88rem] text-[#606266]"
                style="line-height: 1.4rem"
                v-title="{ lines: 3 }"
              >
                {{ row.description }}
              </div>
              <div
                class="flex items-center gap-[var(--czr-gap)] text-[0.75rem] text-[#6F7889]"
              >
                <div>文档数:{{ row.docCount }}</div>
                <div>|</div>
                <div>字符:{{ row.wordCounts }}</div>
                <div>|</div>
                <div>关联应用:{{ row.p6 }}</div>
                <el-tooltip content="编辑" effect="light" placement="top">
                  <SvgIcon
                    name="czr_edit"
                    size="14"
                    class="__hover ml-auto"
                    @click.stop="onEdit(row)"
                  />
                </el-tooltip>
                <el-tooltip content="删除" effect="light" placement="top">
                  <SvgIcon
                    name="czr_del"
                    size="16"
                    class="__hover"
                    @click.stop="onDel(row)"
                  />
                </el-tooltip>
                <el-tooltip
                  :content="row.datasetCollection ? '取消收藏' : '收藏'"
                  effect="light"
                  placement="top"
                >
                  <SvgIcon
                    name="star"
                    size="15"
                    class="__hover"
                    :active="!!row.datasetCollection"
                    @click.stop="onStart(row)"
                  />
                </el-tooltip>
              </div>
            </div>
          </template>
        </template>
      </CzrTableCard>
    </div>
    <detailCom
      v-model:show="state.detail.show"
      :transfer="state.detail.transfer"
      @refresh="onSearch"
    />
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, reactive, ref, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { debounce } from 'lodash'
import { useAppStore, useDialogStore, useDictionaryStore } from '@/stores'
import { ElMessage } from 'element-plus'
import tagsSelect from './tags-select.vue'
import detailCom from './detail.vue'
import {
  datasetsGetAllByPage,
  datasetsTagsBinding,
} from '@/api/modules/knowledge'
import {
  datasetCollections,
  datasetCollectionsDel,
} from '@/api/modules/knowledge/collect'

const AppStore = useAppStore()
const DialogStore = useDialogStore()
const DictionaryStore = useDictionaryStore()
const emit = defineEmits([])
const props = defineProps({})
const { proxy }: any = getCurrentInstance()
const state: any = reactive({
  text: '',
  query: {
    init: false,
    loading: false,
    page: {
      pageNum: 1,
      pageSize: 20,
    },
    form: {},
    formReal: {},
    result: {
      total: 0,
      data: [],
    },
  },
  detail: {
    show: false,
    transfer: {},
  },
})
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 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)) {
      if (k === 'isCreate') {
        if (v) {
          params['creator'] = AppStore.userInfo?.id
        }
      }
      if (k === 'isStar') {
        if (v) {
          params['collectId'] = AppStore.userInfo?.id
        }
      }
      if (k === 'tagIds') {
        params['tagIds'] = [v]
      } else {
        params[k] = v
      }
    }
  }
  state.query.loading = true
  datasetsGetAllByPage(params)
    .then(({ data }: any) => {
      state.query.result.total = data.totalElements
      state.query.result.data = [{ empty: true }, ...data.content]
    })
    .catch(({ message }: any) => {
      ElMessage.error(message)
    })
    .finally(() => {
      state.query.loading = false
    })
}
const onSearch = () => {
  state.query.formReal = JSON.parse(JSON.stringify(state.query.form))
  onPage(1, state.query.page.pageSize)
}
const onReset = () => {
  state.query.page = {
    pageNum: 1,
    pageSize: 20,
  }
  state.query.form = {}
  onSearch()
}
const onAdd = () => {
  state.detail.transfer = {
    mode: 'add',
  }
  state.detail.show = true
}
const onEdit = (row) => {
  state.detail.transfer = {
    mode: 'edit',
    id: row.id,
  }
  state.detail.show = true
}
const onDel = (row: any) => {
  DialogStore.confirm({
    title: '删除确认',
    content: `${row.p6}个应用正在使用该大模型，请确认是否删除`,
    onSubmit: () => {
      ElMessage.success('删除成功！')
      onSearch()
    },
  })
}
const onChangeTag = (row, tags) => {
  datasetsTagsBinding({
    datasetId: row.id,
    tag_ids: tags,
  })
    .then(() => {
      ElMessage.success('标签绑定成功！')
    })
    .catch(({ message }: any) => {
      ElMessage.error(message)
    })
    .finally(() => {
      onSearch()
    })
}
const onStart = (row) => {
  if (row.datasetCollection) {
    datasetCollectionsDel(row.id)
      .then(() => {
        ElMessage.success('取消收藏成功！')
      })
      .catch(({ message }: any) => {
        ElMessage.error(message)
      })
      .finally(() => {
        onSearch()
      })
  } else {
    datasetCollections({
      tenantId: AppStore.tenantInfo?.id,
      targetId: row.id,
    })
      .then(() => {
        ElMessage.success('收藏成功！')
      })
      .catch(({ message }: any) => {
        ElMessage.error(message)
      })
      .finally(() => {
        onSearch()
      })
  }
}
const initDictionary = () => {
  DictionaryStore.initKnowledgeGroups(AppStore.tenantInfo?.id)
}
onMounted(() => {
  initDictionary()
  onReset()
})
</script>

<style lang="scss" scoped>
.knowledge {
  width: 100%;
  height: 11.81rem;
  background-image: url('@/assets/images/knowledge-item-bg.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  padding: 1rem 1.5rem;
}
</style>
