<template>
  <my-layout>
    <layout-item>
      <div px-15 py-10 flex items-center justify-between>
        <div flex-shrink-0 font-semibold class="text-20px">文章列表</div>
        <div flex items-center>
          <el-input v-model="title" class="w-200px" placeholder="输入文章标题搜索" @keyup.enter="search()"
            @input="changeTitle"></el-input>
          <el-form-item class="mb-0 ml-20px" label="文章状态" prop="eventType">
            <el-select v-model="status" clearable>
              <el-option label="已启用" :value="true" />
              <el-option label="已停用" :value="false" />
            </el-select>
          </el-form-item>
          <el-button class="ml-20px" type="primary" @click="search()">查询</el-button>
          <el-button class="" type="primary" @click="toEdit()">新增</el-button>
        </div>
      </div>
    </layout-item>
    <layout-main class="article" :scroll="false">
      <div flex h-full>
        <div bg-fff h-full flex-shrink-0 class="atricle__side mr-10px">
          <classify-list v-bind="componentProps" :checked-cate="current" :data="cateList" :level="1"
            @change="changeCurrent($event)" @search="getCateList()">
            <template #prepend>
              <div class="mt-15px pl-10px text-14px text-gray-600">全部文章（{{allCount}}）</div>
            </template>
          </classify-list>
        </div>
        <div v-if="list.length" h-full flex-grow>
          <my-layout>
            <layout-main>
              <div v-for="item in list" :key="item._id" bg-fff rounded-8 mb-10 px-15 common-shadow>
                <div flex items-center justify-between py-15 border-bottom>
                  <div font-16 font-semibold mr-10 flex items-center>
                    <span>{{ item.title }}</span>
                    <el-tag v-if="item.isTop" class="ml-10px" size="small" type="warning">置顶</el-tag>
                  </div>
                  <div flex items-center>
                    <!-- <div font-14 mr-10>
                      <span color-666>发送量：</span><span min-w-80 font-16 font-semibold>
                        {{ item.send > 0 ? item.send : 0 }}
                      </span>
                    </div> -->
                    <div font-14>
                      <span color-666>查看量：</span><span font-16 font-semibold>
                        {{ item.read > 0 ? item.read : 0 }}
                      </span>
                    </div>
                  </div>
                </div>
                <div flex items-center justify-between py-15 flex-wrap>
                  <div flex items-center flex-wrap font-14 color-666>
                    <span>创建人：</span><el-text class="mr-15px" min-w-80>
                      {{ item.userName || item.userId }}
                    </el-text>
                    <span>创建时间：</span><el-text class="mr-15px">{{ item.time }}</el-text>
                    <span>发布状态 ：</span><el-text :type="item.enable ? 'primary' : ''">
                      {{ item.enable ? '启用中' : '已停用' }}
                    </el-text>
                    <div class="ml-15px flex items-center cursor-pointer" @click="setNewCate(item)">
                      <div>分类 ：</div>
                      <div class="min-w-40px max-w-80px truncate">{{cateMap[item.cateId]||''}}</div>
                      <el-icon class="ml-4px text-black -transform translate-y-2px">
                        <CaretBottom />
                      </el-icon>
                    </div>
                  </div>
                  <div flex items-center class="gap-x-15px">
                    <el-text pointer type="primary" @click="toggle(item._id, !item.enable)">
                      {{ item.enable ? '停用' : '启用' }}
                    </el-text>
                    <el-text pointer type="primary" @click="toggleTop(item._id, !item.isTop)">
                      {{ item.isTop ? '取消置顶' : '置顶' }}
                    </el-text>
                    <el-text pointer type="primary" @click="toEdit(item._id,item.cateId)">编辑</el-text>
                    <el-text v-if="!item.enable" pointer type="danger"
                      @click="remove(item._id, item.title)">删除
                    </el-text>
                    <!-- <el-text pointer type="primary" @click="toDetail(item._id)">查看详情</el-text> -->
                    <el-text pointer type="primary" @click="previewArticle(item)">预览</el-text>
                  </div>
                </div>
              </div>
            </layout-main>
            <layout-item>
              <pagination :bgWhite="false" :totalRow="total" :pageSize="pageSize" :currentPage="currentPage"
                @handle-size-change="onSizeChange" @handle-current-change="onCurrentChange" />
            </layout-item>
          </my-layout>
        </div>
        <div v-else h-full flex flex-col items-center justify-center flex-grow>
          <empty-data title="暂无文章"></empty-data>
        </div>
      </div>
    </layout-main>
  </my-layout>
  <classify-modal :id="currentArticle.cateId" :cateTree="cateTree" :visible="cateVisible"
    :update-method="setArticleNewCate" :width="cateModalWidth" @close="closeCateModal" />
  <el-dialog :model-value="visible" :width="width" title="文章预览" @close="close">
    <div class="px-15px pt-6px pb-12px text-16px text-dark-500 text-center font-semibold">{{ articleTitle }}</div>
    <iframe class="w-full" style="height:calc(100vh - 360px) ;" :srcdoc="iframeContent"></iframe>
    <template #footer>
      <div text-center>
        <el-button type="primary" plain class="w-100px" @click="close()">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import dayjs from 'dayjs';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  setArticleCate,
  getArticleList,
  toggleArticleStatus,
  removeArticle,
  getArticle,
  addArticleCate,
  updateArticleCate,
  deleteArticleCate,
  getArticleCateList,
  sortArticleCate,
  getArticleCount,
  toggleArticleTop
} from '@/api/knowledgeBase';
import usePreviewArticle from '@/hooks/usePreviewArticle';
import useClassifyList from '@/components/classify-list/useClassifyList';
import useModal from "@/hooks/useModal";

import EmptyData from '@/components/empty-data.vue';
import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import pagination from "@/components/pagination/pagination.vue";
import WwUser from '@/components/ww-user/index.vue';
import classifyList from '@/components/classify-list/classify-list.vue';
import classifyModal from '@/components/classify-list/classify-modal.vue';


const title = ref('');
const status = ref('');
const list = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const { content: iframeContent, close, preview, visible, width, articleTitle } = usePreviewArticle();

const options = {
  add: addArticleCate,
  remove: deleteArticleCate,
  update: updateArticleCate,
  sort: sortArticleCate,
  getList: getArticleCateList,
  callback: getList,
  getTotal: getArticleCount,
}

const { cateList, current, cateTree, getCateList, total: allCount, changeCurrent, componentProps } = useClassifyList(options);
const cateMap = computed(() => cateList.value.reduce((acc, cur) => {
  acc[cur._id] = cur.label;
  return acc;
}, {}))

const { close: closeCateModal, show, visible: cateVisible, width: cateModalWidth } = useModal(560); // 选择客户弹窗
const currentArticle = ref({})
function setNewCate(item) {
  currentArticle.value = item;
  show()
}

async function setArticleNewCate(cateId) {
  const { success, message } = await setArticleCate({
    corpId: sessionStorage.getItem("corpId"),
    _id: currentArticle.value._id,
    cateId
  })
  if (success) getList()
  return { success, message }

}

const router = useRouter();

function toDetail(id = '') {
  router.push({ name: 'ARTICLESTATS', params: { id } })
}

function toEdit(id = '', cateId) {
  router.push({ name: 'ARTICLEDETAIL', params: { id }, state: { cateId: cateId || current.value._id } })
}

function changeTitle(e) {
  if (e === '') {
    currentPage.value = 1;
    getList()
  }
}

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

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

async function getList() {
  const cateIds = Array.isArray(current.value.childrenIds) ? [current.value._id, ...(current.value.childrenIds || [])] : [current.value._id];
  const params = {
    page: currentPage.value,
    pageSize: pageSize.value,
    corpId: sessionStorage.getItem("corpId"),
    title: title.value,
    cateIds,
    showCount: true
  }
  if (typeof status.value == 'boolean') params.enable = status.value;
  const { success, data, message } = await getArticleList(params);
  const { list: arr, total: count = 0 } = data;
  if (success) {
    list.value = arr.map(i => ({
      ...i,
      time: dayjs(i.createTime).format('YYYY-MM-DD HH:mm')
    }));
    total.value = count;
  } else {
    ElMessage.error(message);
  }
}

function search() {
  currentPage.value = 1;
  getList()
}

async function toggle(_id, enable) {
  const { message, success } = await toggleArticleStatus({ _id, enable });
  if (success) {
    ElMessage.success(message)
    getList()
  } else {
    ElMessage.error(message)
  }
}
async function toggleTop(_id, isTop) {
  const { message, success } = await toggleArticleTop({ _id, isTop });
  if (success) {
    ElMessage.success(message);
    getList();
  } else {
    ElMessage.error(message);
  }
}

async function remove(_id, title) {
  await ElMessageBox.confirm(`确定删除文章“${title}”吗？`, '提示', { type: 'warning' });
  const { message, success } = await removeArticle({ _id, corpId: sessionStorage.getItem('corpId') });
  if (success) {
    ElMessage.success(message);
    if (list.value.length === 1 && list.value[0]._id === _id && currentPage.value > 1) {
      currentPage.value -= 1;
    }
    getList()
  } else {
    ElMessage.error(message)
  }
}

async function previewArticle(item) {
  const { success, message, data } = await getArticle({ id: item._id, corpId: sessionStorage.getItem('corpId') });
  if (success) {
    preview(data.data)
  } else {
    ElMessage.error(message || '预览文章失败')
  }
}

</script>

<style scoped lang="scss">
.atricle {
  height: calc(100% - 80px);

  @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>
<style>
.article-action-popover.el-popover {
  padding: 0;
}
</style>
