<template>
  <el-dialog append-to-body :model-value="props.visible" :width="width" title="常用语" @close="close">
    <div class="pt-10px pb-15px text-center">
      <el-radio-group v-model="type" @change="change">
        <el-radio-button label="corp" value="corp">机构常用语</el-radio-button>
        <el-radio-button label="mine" value="mine">我的常用语</el-radio-button>
      </el-radio-group>
    </div>
    <div v-loading="loading" class="h-50vh flex border-t border-gray-200">
      <el-scrollbar class="flex-shrink-0 border-r min-w-120px w-1/3 max-w-180px border-gray-200">
        <classify-list v-if="type === 'corp'" :checked-cate="current" :data="cateList"
          @change="changeCurrent($event)" />
        <div v-else>
          <div v-for="i in myCates" :key="i._id"
            class="mr-10px break-all text-14px py-12px px-5px border-b border-gray-200 cursor-pointer"
            :class="current && current._id === i._id ?'text-blue-500':''" @click="changeCurrent(i)">
            {{ i.label }}
          </div>
        </div>
      </el-scrollbar>
      <div class="h-full flex-grow">
        <div class="h-56px flex items-center justify-center px-15px">
          <el-input v-model="keyword" text-center placeholder="搜索" :suffix-icon="Search" />
        </div>
        <div class="flex-grow" style="height: calc(100% - 56px);">
          <el-scrollbar ref="scrollRef" @scroll="handleScroll($event)">
            <div v-for="item in list" :key="item._id"
              class="flex items-center border-b border-gray-200 px-15px py-10px cursor-pointer" @click="words=item">
              <div class="flex-grow w-0 break-all line-clamp-2 text-14px leading-22px">
                {{ item.content }}
              </div>
              <el-checkbox class="flex-shrink-0 ml-10px" :class="words._id === item._id ?'':'opacity-0'"
                :model-value="true" />
            </div>
          </el-scrollbar>
        </div>
      </div>
    </div>
    <template #footer>
      <div text-center>
        <el-button class="w-100px" @click="close()">取消</el-button>
        <el-button class="w-100px" type="primary" @click="confirm()"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>

</template>
<script setup>
import { nextTick, watch, ref } from 'vue';
import { watchDebounced } from '@vueuse/core';
import { getCommonWordsList, getCorpCommonWordCate, getUserCommonWordCate } from '@/api/knowledgeBase'
import useClassifyList from '@/components/classify-list/useClassifyList';
import useElScrollbar from "@/hooks/useElScrollbar";

import classifyList from '@/components/classify-list/classify-list-side.vue';
import { Search } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const props = defineProps({
  visible: { type: Boolean, default: false },
  width: { type: Number }
})
const emits = defineEmits(['close', 'select']);
const type = ref('corp');
const keyword = ref("");
const page = ref(1);
const more = ref(false);
const list = ref([]);
const loading = ref(false)
const scrollRef = ref();
const words = ref({});
const myCates = ref([]);

const options = {
  getList: getCorpCommonWordCate,
  // callback: handleCurrentChang
}

const { cateList, current, cateIds, changeCurrent, getCateList } = useClassifyList(options, false);
const { atBottom, handleScroll } = useElScrollbar(scrollRef, 0);

async function loadmore() {
  if (more.value && !loading.value) {
    page.value += 1;
    await getList();
  }
}


async function change(val) {
  if (val === 'mine') {
    if (myCates.value.length === 0) await getMyCates()
    current.value = myCates.value[0] || {};
  }
  words.value = {}
}

function handleCurrentChang() {
  page.value = 1;
  getList();
}

function close() {
  emits('close')
}

function confirm() {
  if (words.value._id) {
    emits('select', words.value.content)
    close()
  } else {
    ElMessage.info('请选择一个常用语')
  }
}

async function getList() {
  loading.value = true;
  const params = {
    page: page.value,
    corpId: sessionStorage.getItem('corpId'),
    userId: sessionStorage.getItem('userId'),
    keyword: keyword.value
  }
  if (type.value === 'corp') {
    if (current.value._id === 'all') {
      params.cateIds = cateList.value.map(i => i._id);
    } else {
      params.cateIds = cateIds.value
    }
  } else {
    params.cateIds = current.value._id === 'all' ? myCates.value.map(i => i._id) : [current.value._id];
  }
  const { data } = await getCommonWordsList(params)
  const arr = Array.isArray(data.list) ? data.list : [];
  list.value = page.value === 1 ? arr : [...list.value, ...arr];
  more.value = data.pages > page.value;
  loading.value = false;
  if (page.value === 1) {
    await nextTick()
    scrollRef.value.setScrollTop(0);
  }
}

async function getMyCates() {
  const { data } = await getUserCommonWordCate({
    corpId: sessionStorage.getItem('corpId'),
    userId: sessionStorage.getItem('userId')
  })
  myCates.value = data && Array.isArray(data.list) ? [...data.list] : []
}


watch(() => props.visible, n => {
  if (n) {
    type.value = 'corp';
    words.value = {};
    cateList.value.length === 0 ? getCateList() : '';
  }
})

watch(cateIds, () => {
  handleCurrentChang()
})

watchDebounced(keyword, () => {
  page.value = 1;
  getList();
}, { debounce: 500 })

watchDebounced(atBottom, async (n) => {
  if (n) {
    await loadmore()
    atBottom.value = false
  };
}, { debounce: 500 })
</script>
