<template>
  <div bg-fff flex class="common-words" v-loading="loading">
    <div h-full flex-shrink-0 class="common-words__side">
      <my-layout>
        <layout-item>
          <div p-15 class="pb-0">
            <div font-semibold active-title-bar class="text-20px">常用语</div>
          </div>
        </layout-item>
        <layout-main :scroll="false">
          <classify-list v-bind="componentProps" :checked-cate="current" :data="cateList"
            @change="changeCurrent($event)" @search="getCateList()">
            <template #prepend>
              <div class="mt-15px pl-10px text-14px text-gray-600">全部常用语（{{allCount}}）</div>
            </template>
          </classify-list>
        </layout-main>
      </my-layout>

    </div>
    <div h-full flex-grow>
      <my-layout>
        <layout-item>
          <div p-15 class="flex items-center justify-between">
            <div class="mr-10px truncate min-w-0"> {{''}}</div>
            <el-button w-100px :icon="Plus" type="primary" @click="setWords()">新增</el-button>
            <!-- <el-button w-100px :icon="UploadFilled" type="primary" plain>导入数据</el-button> -->
          </div>
        </layout-item>
        <layout-main :scroll="false">
          <el-table stripe height="100%" :data="list">
            <el-table-column type="index" label="序号" :width="60" />
            <el-table-column property="content" label="内容" :min-width="200">
              <template #default="{ row: { content, files } }">
                <el-popover :key="_id" placement="top-start" :width="320" trigger="hover">
                  <template #reference>
                    <div flex>
                      <div class="leading-none" overflow-hidden>
                        <el-text truncated>{{ content }}</el-text>
                      </div>
                    </div>
                  </template>
                  <el-text>{{ content }}</el-text>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column fixed="right" class-name="el-table-fixed-column--shadow" label="操作" width="100">
              <template #default="{ row }">
                <el-text class="pointer" type="primary" @click="setWords(row)">编辑</el-text>
                <!-- <el-text class="pointer" type="danger" @click="removeWords(row)">删除</el-text> -->
              </template>
            </el-table-column>
          </el-table>
        </layout-main>
        <layout-item>
          <pagination :totalRow="total" :pageSize="pageSize" :currentPage="currentPage"
            @handle-size-change="onSizeChange" @handle-current-change="onCurrentChange" />
        </layout-item>
      </my-layout>
    </div>
  </div>
  <el-dialog v-model="wordsVisible" :title="currentWords._id ? '编辑常用语' : '新增常用语'" :width="480">
    <el-form px-15 pt-10 :label-width="0">
      <el-form-item prop="name">
        <el-cascader v-model="currentWords.cateIds" class="flex-grow" w-full :options="cateTree"
          :props="{checkStrictly:true,value:'_id'}" clearable />
      </el-form-item>
      <el-form-item class="mb-0">
        <div w-full>
          <el-input type="textarea" :maxlength="1500" show-word-limit v-model="currentWords.content"
            placeholder="请输入常用语内容" :autosize="{ minRows: 4, maxRows: 8 }"></el-input>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div text-center>
        <el-button v-if="currentWords._id" class="w-100px" type="danger" :loading="removeLoading"
          @click="removeWords()">删除</el-button>
        <el-button v-else class="w-100px" @click="wordsVisible = false">取消</el-button>
        <el-button class="w-100px" :loading="updateWordsLoading" type="primary" @click="updateWords()"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>
  <platform-words :visible="quotoVisible" @on-quoto="quotoWords($event)" @on-close="quotoVisible = false" />
</template>
<script setup>
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getCommonWordsList,
  setCommonWords,
  removeCommonWords,
  addCorpCommonWordCate,
  deleteCorpCommonWordCate,
  getCorpCommonWordCate,
  updateCorpCommonWordCate,
  sortCorpCommonWordCate,
  getCommonWordsCount
} from '@/api/knowledgeBase'
import { Plus } from '@element-plus/icons-vue';
import useClassifyList from '@/components/classify-list/useClassifyList';

import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import pagination from "@/components/pagination/pagination.vue";
import PlatformWords from './platform-words.vue';
import classifyList from '@/components/classify-list/classify-list.vue';


const list = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const loading = ref(false);
const removeLoading = ref(false);
const options = {
  add: addCorpCommonWordCate,
  remove: deleteCorpCommonWordCate,
  update: updateCorpCommonWordCate,
  sort: sortCorpCommonWordCate,
  getList: getCorpCommonWordCate,
  getTotal: getCommonWordsCount,
  callback: getList,
  loading: loading
}

const { cateList, cateTree, current, total: allCount, getCateList, changeCurrent, componentProps } = useClassifyList(options);

function onSizeChange(e) {
  pageSize.value = e;
  getList()
}
function onCurrentChange(e) {
  currentPage.value = e;
  getList()
}

const currentWords = ref({});
const wordsVisible = ref(false);
const updateWordsLoading = ref(false);
function setWords(words = {}) {
  currentWords.value = { ...words, cateId: current.value && current.value._id ? current.value._id : '' };
  if (currentWords.value.cateId) {
    let cate = cateList.value.find(i => i._id === currentWords.value.cateId);
    const cateIds = cate ? [cate._id] : [];
    while (cate && cate.parentId) {
      cate = cateList.value.find(i => i._id === cate.parentId);
      cate && cateIds.unshift(cate._id);
    }
    currentWords.value.cateIds = cateIds;
  }
  wordsVisible.value = true;
}
async function updateWords() {
  if (updateWordsLoading.value) return;
  if (!currentWords.value.cateIds.length === 0) {
    ElMessage.info('请选择常用语分类')
  } else if (!currentWords.value.content || currentWords.value.content.trim() === '') {
    ElMessage.info('请输入常用语内容')
  } else {
    updateWordsLoading.value = true;
    const params = {
      cateId: currentWords.value.cateIds[currentWords.value.cateIds.length - 1],
      content: currentWords.value.content,
      corpId: sessionStorage.getItem('corpId'),
      userId: sessionStorage.getItem('userId')
    }
    if (currentWords.value._id) params.id = currentWords.value._id;
    const { success, message } = await setCommonWords(params)
    if (success) {
      ElMessage.success(message);
      wordsVisible.value = false;
      getList()
    }
    else ElMessage.error(message);
    updateWordsLoading.value = false;
  }
}
async function removeWords() {
  if (removeLoading.value) return
  await ElMessageBox.confirm('确认删除该常用语吗？', '提示', { type: 'warning' });
  removeLoading.value = true
  const params = {
    id: currentWords.value._id,
    corpId: sessionStorage.getItem('corpId'),
    userId: sessionStorage.getItem('userId')
  }
  const { success, message } = await removeCommonWords(params);
  removeLoading.value = false
  if (success) {
    ElMessage.success(message);
    wordsVisible.value = false
    if (list.value.length === 1 && currentPage.value > 1 && list.value[0]._id == params.id) {
      currentPage.value -= 1;
    }
    getList()
  }
  else ElMessage.error(message);
}

const quotoVisible = ref(false);
function quotoWords(txt) {
  currentWords.value.content = txt;
  quotoVisible.value = false
}

async function getList() {
  if (loading.value) return;
  if (current.value._id) {
    loading.value = true;
    const childrenIds = Array.isArray(current.value.childrenIds) ? current.value.childrenIds : [];
    const { success, data, message } = await getCommonWordsList({
      page: currentPage.value,
      pageSize: pageSize.value,
      corpId: sessionStorage.getItem("corpId"),
      userId: sessionStorage.getItem('userId'),
      cateIds: [current.value._id, ...childrenIds],
    })
    const { list: arr, total: count = 0 } = data;
    loading.value = false;
    if (success) {
      list.value = arr;
      total.value = count;
    }
    else ElMessage.error(message);
    
  } else {
    list.value = [];
    total.value = 0
  }
  
}

</script>
<style scoped lang="scss">
.common-words {
  height: 100%;

  @at-root &__side {
    width: 30%;
    min-width: 240px;
    max-width: 320px;
    border-right: 1px solid #eee;
  }

  @at-root &__cate {
    border-bottom: 1px solid #eee;

    @at-root &--active {
      color: #fff;
      background-color: var(--el-color-primary);

    }

    @at-root &:first-of-type {
      border-top: 1px solid #eee;
    }
  }
}

.mr-12 {
  margin-right: 12px;
}

.mb-0 {
  margin-bottom: 0;
}
</style>