<template>
  <el-drawer :model-value="visible" title="常用语" size="70%" style="--el-drawer-padding-primary: 0" @close="close()">
    <my-layout bg-fff no-radius v-loading="loading">
      <layout-item>
        <div class="flex items-center border-b">
          <div class="tab" :class="{active: tab === 'user'}" @click="changeTab('user')">我的常用语</div>
          <div class="tab" :class="{active: tab === 'corp'}" @click="changeTab('corp')">更多常用语（机构）</div>
        </div>
      </layout-item>
      <layout-main :scroll="false">
        <div class="flex h-full">
          <my-layout class="left-menu" flex-shrink-0 no-radius border-right>
            <layout-main>
              <div v-if="tab === 'user'">
                <div v-for="i in myCates" :key="i._id" class="cate-item"
                  :class="{active: currentCate && currentCate._id === i._id}" @click="selectCate(i)">{{ i.label }}</div>
              </div>
              <div v-else>
                <classify-list appendAll link :checked-cate="currentCate" :data="cateList" @change="selectCate" />
              </div>
            </layout-main>
            <layout-item>
              <div v-if="tab === 'user'" class="py-10px">
                <el-button class="edit-group-btn" plain type="primary" @click="showGroupModal">编辑分组</el-button>
              </div>
            </layout-item>
          </my-layout>
          <my-layout no-radius flex-grow>
            <layout-item>
              <div class="search-bar flex items-center border-b">
                <el-input v-model="keyword" placeholder="搜索" clearable @keyup.enter="getList" class="search-input">
                  <template #prefix>
                    <el-icon>
                      <Search />
                    </el-icon>
                  </template>
                </el-input>
                <el-button v-if="tab === 'user'" type="primary" class="ml-10px" @click="addWords">新增常用语</el-button>
              </div>
            </layout-item>
            <layout-main :scroll="false">
              <el-scrollbar height="100%">
                <div v-for="item in list" :key="item._id" class="flex group border-b items-center px-15px">
                  <div class="w-0 flex-grow words-item hover:text-blue-500">{{ item.content }}</div>
                  <div class="flex-shrink-0 ml-10px group-hover:block hidden">
                    <el-text type="primary" class="cursor-pointer" @click.stop="send(item.content)">发送</el-text>
                    <el-text v-if="tab === 'user'" type="primary" class="cursor-pointer ml-10px"
                      @click.stop="edit(item)">编辑</el-text>
                    <el-text v-if="tab === 'user'" type="danger" class="cursor-pointer ml-10px"
                      @click.stop="remove(item._id)">删除</el-text>
                  </div>
                </div>
                <empty-data v-if="list.length === 0" :top="120" title="暂无常用语" padding="0 0 15px" text-top="10px"
                  :image-width="160"></empty-data>
              </el-scrollbar>
            </layout-main>
            <layout-item>
              <pagination class="border-t border-gray-200" :totalRow="total" :pageSize="pageSize" :currentPage="page"
                @handle-size-change="changeSize" @handle-current-change="changePage" />
            </layout-item>
          </my-layout>
        </div>
      </layout-main>

    </my-layout>
  </el-drawer>

  <edit-modal :visible="groupVisible" :width="560" :cates="myCates" @change="getMyCates()" @delete="onDelete"
    @close="closeGroupModal" />
  <edit-words :words="currentWords" :visible="wordsVisible" :width="560" :cates="myCates" @change="reloadList()"
    @close="closeWordsModal" />
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import EditModal from "./edit-modal.vue";
import editWords from "./edit-words.vue";
import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import EmptyData from "@/components/empty-data.vue";
import pagination from "@/components/pagination/pagination.vue";
import classifyList from "@/components/classify-list/classify-list-side.vue";
import useModal from "@/hooks/useModal";
import useCommonWordsApi from "./useApi";
import { getCommonWordsList, getCorpCommonWordCate, getUserCommonWordCate } from "@/api/knowledgeBase";

const emits = defineEmits(["close"]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  }
});

const loading = ref(false);
const tab = ref("user");
const keyword = ref("");
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);
const list = ref([]);
const myCates = ref([]);
const cateList = ref([]);
const currentCate = ref({});
const { close: closeGroupModal, show: showGroupModal, visible: groupVisible } = useModal(560);
const { close: closeWordsModal, show: showWordsModal, visible: wordsVisible } = useModal(560);
const currentWords = ref({});
const timer = ref(null);

function close() {
  emits("close");
}

function edit(item) {
  currentWords.value = item;
  showWordsModal();
}

function changeTab(val) {
  tab.value = val;
  page.value = 1;
  getCates();
}

function selectCate(cate) {
  currentCate.value = cate;
  page.value = 1;
  getList();
}

function addWords() {
  currentWords.value = {};
  showWordsModal();
}

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

function changeSize(val) {
  pageSize.value = val;
  page.value = 1;
  getList();
}
function changePage(val) {
  page.value = val;
  getList();
}

function onDelete(id) {
  const idx = myCates.value.findIndex(i => i._id === id);
  if (idx > -1) myCates.value.splice(idx, 1);
  if (currentCate.value._id === id) currentCate.value = myCates.value[0] || {};
}

async function getMyCates() {
  const { data } = await getUserCommonWordCate({
    corpId: sessionStorage.getItem("corpId"),
    userId: sessionStorage.getItem("userId"),
  });
  myCates.value = data && Array.isArray(data.list) ? [{ label: "全部", _id: "all" }, ...data.list] : [{ label: "全部", _id: "all" }];
  currentCate.value = myCates.value[0];
}

async function getCorpCates() {
  const { data } = await getCorpCommonWordCate();
  cateList.value = data && Array.isArray(data.list) ? [{ label: "全部", _id: "ALL" }, ...data.list] : [{ label: "全部", _id: "ALL" }];
  currentCate.value = cateList.value[0];
}

async function getCates() {
  if (tab.value === "user") {
    await getMyCates();
  } else {
    await getCorpCates();
  }
  getList();
}

async function remove(id) {
  await ElMessageBox.confirm("是否删除？", "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  });
  const { remove } = useCommonWordsApi();
  const success = await remove(id);
  if (success) {
    ElMessage.success('删除成功');
    getList();
  }
}

async function getList() {
  if (timer.value) {
    clearTimeout(timer.value);
  }
  timer.value = setTimeout(() => {
    getList1();
  }, 500);
}

async function getList1() {
  loading.value = true;
  const params = {
    page: page.value,
    pageSize: pageSize.value,
    corpId: sessionStorage.getItem("corpId"),
    userId: sessionStorage.getItem("userId"),
    keyword: keyword.value,
  };
  if (tab.value === "user") {
    params.cateIds = currentCate.value && currentCate.value._id === "all"
      ? myCates.value.map(i => i._id)
      : [currentCate.value._id];
  } else {
    const childrenIds = currentCate.value && Array.isArray(currentCate.value.childrenIds) ? currentCate.value.childrenIds : [];
    if (currentCate.value._id === 'ALL') {
      params.cateIds = [currentCate.value._id, ...cateList.value.map(i => i._id)];
    } else {
      params.cateIds = [currentCate.value._id, ...childrenIds];
    }
  }
  const { data } = await getCommonWordsList(params);
  list.value = Array.isArray(data.list) ? data.list : [];
  total.value = data.total || 0;
  loading.value = false;
}

function send(content) {
  emits("send", content);
}

// watch(tab, getCates);
watch(keyword, () => {
  page.value = 1;
  getList();
});

watch(() => props.visible, val => {
  if (val) {
    getCates();
  }
})
</script>

<style scoped>
.common-words-page {
  height: 100%;
}

.tab {
  padding: 10px 32px;
  cursor: pointer;
  font-weight: 500;
  border-bottom: 2px solid transparent;
}

.tab.active {
  color: #409eff;
  border-bottom: 2px solid #409eff;
  background: #fff;
}

.left-menu {
  min-width: 120px;
  width: 180px;
  background: #fafbfc;
}

.cate-item {
  padding: 12px 10px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
}

.cate-item.active {
  color: #409eff;
  background: #f4f8ff;
}

.edit-group-btn {
  margin: 10px 0 0 10px;
  width: calc(100% - 20px);
}

.search-bar {
  padding: 10px 15px;
  background: #fff;
}

.search-input {
  width: 220px;
}

.words-item {
  padding: 10px 0;
  font-size: 14px;
  background: #fff;
  cursor: pointer;
}
</style>
