<template>
  <div class="wrap">
    <div style="position: absolute; right: 15px; top: 30px">
      <el-button type="primary" @click="creatKnowledge" v-if="outerFlag">创建知识</el-button>
    </div>
    <div style="text-align: center; margin-top: 30px; margin-bottom: 15px">
      <el-radio-group v-model="tabPosition" class="searchBtn" v-if="!outerFlag && getToExamine!==2">
        <el-radio-button label="普通检索" value="first"/>
        <el-radio-button label="高级检索" value="second"/>
      </el-radio-group>
      <div class="searchBox">
        <div class="searchBox1" v-if="tabPosition === 'first'">
          <div style="display: flex">
            <div style="width: 200px;">
              <el-tree-select
                v-model="directoryValue"
                :data="knowledgeCatalogData"
                @change="changeDirectory"
                check-strictly
                clearable
                :render-after-expand="false"
              />
            </div>
            <el-input class="firstTitle" v-model="fromCommon.title" placeholder="标题、关键字、全文"> </el-input>
          </div>
          <el-button @click="resetCommon()" style="margin-top: 15px">重置</el-button>
          <el-button type="primary" @click="onSubmit(1)" style="margin-top: 15px">搜索</el-button>
        </div>
        <div class="searchBox2" v-if="tabPosition === 'second'">
          <el-form :model="form" label-width="120px">
            <el-form-item label="标题">
              <el-input v-model="form.title" />
            </el-form-item>
            <el-form-item label="关键字">
              <!-- <el-input v-model="form.keywords" /> -->
              <div style="width: 100%; height: 32px; border: 1px solid #dfdfdf; display: flex">
                <el-tag
                  v-for="tag in dynamicTags"
                  :key="tag"
                  class="mx-1"
                  size="large"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  v-if="inputVisible"
                  ref="InputRef"
                  v-model="inputValue"
                  class="ml-1 w-20"
                  size="small"
                  @keyup.enter="handleInputConfirm"
                  @blur="handleInputConfirm"
                />
                <el-button v-else class="button-new-tag ml-1" @click="showInput">
                  + New Tag
                </el-button>
              </div>
            </el-form-item>
            <el-form-item label="全文">
              <el-input v-model="form.content" />
            </el-form-item>
            <el-form-item label="标签">
              <el-select v-model="form.label" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in knowledgeLabeData"
                  :key="item.value"
                  :label="item.title"
                  :value="item.value"
                >
                  {{ item.title }}
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="目录分类">
              <el-tree-select
                v-model="form.directory"
                @change="changeDirectory"
                :data="knowledgeCatalogData"
                check-strictly
                clearable
                :render-after-expand="false"
                style="width: 100%"
              />
            </el-form-item>

            <!-- <el-form-item label="发布时间">
              <el-date-picker
                v-model="form.date"
                type="daterange"
                value-format="YYYY-MM-DD"
                range-separator="To"
                start-placeholder="Start month"
                end-placeholder="End month"
              />
            </el-form-item> -->
          </el-form>
          <div>
            <el-button @click="resetAdvanced(2)">重置</el-button>
            <el-button type="primary" @click="onSubmit(2)">搜索</el-button>
          </div>
        </div>
      </div>
      <div class="content">
        <div class="list">
          <ul>
            <li v-for="(item, index) in listData" :key="index" v-if="listData.length > 0">
              <div class="title" @click="trunDetail(item)">
                <el-icon style="margin-right: 3px; vertical-align: -15%"><Tickets /></el-icon>
                <span v-html="replaceKeywordColor(item.title, 'title')"></span>
                <el-text
                  class="mx-1"
                  :type="item.toExamine === 1 ? 'success' : 'danger'"
                  style="margin-left: 15px; font-size: 12px"
                  v-if="item.toExamine === 2"
                >
                  {{ item.reason }}
                </el-text>
              </div>
              <div class="category">
                <span v-if="item.categoryname">
                  分类：<span> {{ item.categoryname }}</span>
                </span>
                <span v-if="item.labelname">
                  标签：<span> {{ item.labelname }} </span>
                </span>
                <span v-if="item.directoryname">
                  目录分类：<span>
                    {{ item.directoryname }}
                    <!-- {{ getSelectName(item.directory, useSelectStore().knowledgeCatalogTree) }} -->
                  </span>
                </span>
              </div>
              <span
                class="text"
                v-html="replaceKeywordColor(delHtmlTag(item.content), 'content')"
              ></span>
              <div class="time">
                <el-icon style="margin-right: 3px; vertical-align: -15%"><Document /></el-icon
                >{{ item.createBy }} <span>发布于</span>
                {{ item.createTime && item.createTime }}
              </div>
              <div class="button" v-if="outerFlag">
                <el-button type="warning" v-if="item.toExamine === 0 && !audioBtnFlag" link>
                  待审核
                </el-button>
                <el-button type="primary" v-if="audioBtnFlag" link @click="handleAduio(item, 1)">
                  通过
                </el-button>
                <el-button type="danger" v-if="audioBtnFlag" link @click="handleAduio(item, 2)">
                  不通过
                </el-button>
                <el-button
                  type="primary"
                  v-if="!audioBtnFlag && item.toExamine !== 0"
                  link
                  @click="!editKnowledge(item)"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  v-if="!audioBtnFlag && item.toExamine !== 0"
                  link
                  @click="!deleteKnowledge(item)"
                >
                  删除
                </el-button>
              </div>
              <el-divider />
            </li>
            <el-empty description="暂无数据" v-else />
          </ul>
        </div>
        <div class="page" v-if="tableCount">
          <el-pagination
            v-model:page-size="pageSize4"
            layout="prev, pager, next"
            :total="tableCount"
            style="float: right"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <!-- <el-drawer
      v-model="detailDrawer"
      title="知识库详情"
      :direction="direction"
      :before-close="handleCloseDrawer"
    >
      11111
      <knowledge-detail :docId="drawerDocId"/>
    </el-drawer> -->
  </div>
  
</template>
<script setup name="KnowledgeList">
  import { onMounted, ref } from 'vue';
  import { ElMessageBox } from 'element-plus';
  import { Search, Document, Tickets } from '@element-plus/icons-vue';
  import { useRouter } from 'vue-router';
  import knowledgDetail from "@/views/main/knowledgeBase/knowledgeList/cpns/detail/detail.vue";

  import {
    getPageListData,
    getPageHandle,
    deletePageData,
    editPageData,
  } from '@/api/main/system/system';
  import useSelectStore from '@/store/commonSelect/common';
  const { proxy } = getCurrentInstance();
  const tableCount = ref(0);
  const pageSize4 = ref(5);
  const listData = ref([]);
  const directoryValue = ref([]);
  const getDirectory = ref([]);
  const knowledgeLabeData = useSelectStore().knowledgeLabeTree;
  const paramsSearch = ref({});
  const audioBtnFlag = ref(false);
  const router = useRouter();
  const outerFlag = ref(true);
  const props = defineProps({
    toExamine: {
      type: Number,
      default: 0,
    },
    isSreen:{
      type: Number,
      default: 0,
    }
  });
  const inputValue = ref('');
  const dynamicTags = ref([]);
  const inputVisible = ref(false);
  const InputRef = ref();
  const getToExamine = ref()
  function changeDirectory(data) {
    getKnowledgeCatalog(data, knowledgeCatalogData);
  }
  function changeDirectoryClear() {
    paramsSearch.value.directory  = ''
    console.log(paramsSearch.value.directory)
  }
  const handleClose = (tag) => {
    dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1);
  };

  const showInput = () => {
    if (dynamicTags.value.length > 4) {
      return;
    }
    inputVisible.value = true;

    nextTick(() => {
      InputRef.value.input.focus();
    });
  };

  const handleInputConfirm = () => {
    if (inputValue.value) {
      dynamicTags.value.push(inputValue.value);
    }
    inputVisible.value = false;
    inputValue.value = '';
  };
  const handleCurrentChange = (val) => {
    paramsSearch.value.pageNum = val;
    getPageList();
  };
  onActivated(() => {
    getPageList();
  });
  onMounted(() => {
    paramsSearch.value.advSearchFlag = 0;
    paramsSearch.value.pageNum = 1;
    paramsSearch.value.pageSize = pageSize4.value;
    if (!props.toExamine) {
      audioBtnFlag.value = true;
      paramsSearch.value.toExamine = props.toExamine;
    } else {
      if (props.toExamine === 2) {
        paramsSearch.value.toExamine = 1;
        getToExamine.value = props.toExamine
        outerFlag.value = false;
      } else{
        audioBtnFlag.value = false;
        delete paramsSearch.value.toExamine;
      }
      
    }
    if (router.currentRoute.value.query.outerFlag) {
      paramsSearch.value.toExamine = 1;
      outerFlag.value = false;
    }
    getPageList();
  });

  function getPageList() {
    // paramsSearch.value.toExamine = 0;
    let apiUrl;
    if (outerFlag.value) {
      apiUrl = '/km/doc';
    } else {
      apiUrl = '/km/doc';
      delete paramsSearch.value.toExamine;
    }
    getPageListData(apiUrl, paramsSearch.value).then(({ data, total }) => {
      if (data) {
        listData.value = data;
        tableCount.value = total;
      } else {
        listData.value = [];
      }
    });
  }
  function delHtmlTag(str) {
    return str.replace(/<[^>]+>/g, ''); //去掉所有的html标记
  }
  function deleteKnowledge(item) {
    proxy.$modal.confirm('确定删除此条记录吗').then((e) => {
      deletePageData('/km/doc/' + item.docId).then((data) => {
        proxy.$modal.msgSuccess('操作成功');
        getPageList();
      });
    });
  }
  function handleAduio(item, state) {
    const params = {};
    params.state = state;
    let promptText = '';
    if (state === 1) {
      promptText = '确定同意此条记录吗？';
      proxy.$modal.confirm(promptText).then(() => {
        messageAduio(item, params);
      });
    } else if (state === 2) {
      promptText = '确定拒绝此条记录吗？';
      ElMessageBox.prompt(promptText, '知识库审核', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern: /[\S]/,
        inputErrorMessage: '不能为空',
      })
        .then(({ value }) => {
          params.reason = value;
          messageAduio(item, params);
        })
        .catch(() => {
          proxy.$modal.msgError('取消');
        });
    }
  }
  function messageAduio(item, params) {
    getPageHandle('/km/doc/toExamine/' + item.docId, params).then((data) => {
      proxy.$modal.msgSuccess('操作成功');
      getPageList();
    });
  }
  function replaceKeywordColor(val, type) {
    if (!val) {
      return '';
    }
    let keyword = '';
    if (paramsSearch.value.advSearchFlag === 0) {
      keyword = paramsSearch.value.title;
      if (val.includes(keyword) && keyword !== '') {
        return val.replace(keyword, '<span style="color:#f00">' + keyword + '</span>');
      } else {
        return val;
      }
    } else if (paramsSearch.value.advSearchFlag === 1) {
      if (type === 'title') {
        keyword = paramsSearch.value.title;
      } else if (type === 'content') {
        keyword = paramsSearch.value.content;
      } else if (type === 'keywords') {
        keyword = paramsSearch.value.keywords;
      }
      if (val.includes(keyword) && keyword !== '') {
        return val.replace(keyword, '<span style="color:#f00">' + keyword + '</span>');
      } else {
        return val;
      }
    }
  }

  function creatKnowledge() {
    router.push({
      path: '/knowledge/addKonwledge',
    });
  }
  function editKnowledge(item) {
    router.push({
      path: '/knowledge/addKonwledge',
      query: {
        docId: item.docId,
      },
    });
  }
  const detailDrawer = ref(false)
  const detailDirection = ref('rtl')
  const drawerDocId =ref()
  function handleCloseDrawer(e) {
    detailDrawer.value =false
  }
  function trunDetail(item) {
    // if (props.isSreen) {
    //   detailDrawer.value = true
    //   drawerDocId.value = Number(item.docId)
    //   console.log(item)
    //   console.log(props)
    // } else 
    if (outerFlag.value) {
      router.push({
        path: '/knowledge/detail',
        query: {
          docId: item.docId,
        },
      });
    } else {
      router.push({
        path: '/knowledge/detail',
        query: {
          docId: item.docId,
        },
      });
      // window.open('/knowledgeBase/detailOuter?docId=' + item.docId, '_blank');
    }
  }

  const tabPosition = ref('first');
  const form = ref({
    title: '',
    keywords: '',
    content: '',
    label: '',
    category: '',
    directory: '',
  });
  const fromCommon = ref({
    title: '',
  });
  function resetCommon() {
    fromCommon.value.title = '';
    directoryValue.value = '';
  }
  function resetAdvanced() {
    form.value.title = '';
    form.value.content = '';
    dynamicTags.value = [];
    form.value.label = '';
    form.value.category = '';
    form.value.directory = '';
    getDirectory.value = [];
  }
  const onSubmit = (val) => {
    paramsSearch.value = {};
    if (props.toExamine === 0) {
      paramsSearch.value.toExamine = 0;
    }
    paramsSearch.value.pageNum = 1;
    paramsSearch.value.pageSize = pageSize4.value;
    if (val === 1) {
      paramsSearch.value.advSearchFlag = 0;
      paramsSearch.value.title = fromCommon.value.title;
      paramsSearch.value.directory = directoryValue.value;
      // if (!outerFlag.value) {
      //   paramsSearch.value.directory = getDirectory.value.join(',');
      //   paramsSearch.value.content = fromCommon.value.title;
      //   paramsSearch.value.keywords = fromCommon.value.title;
      // }
    } else if (val === 2) {
      paramsSearch.value.advSearchFlag = 1;
      paramsSearch.value.title = form.value.title;
      paramsSearch.value.content = form.value.content;
      paramsSearch.value.keywords = dynamicTags.value.join(',');
      paramsSearch.value.label = form.value.label;
      paramsSearch.value.category = form.value.category;
      paramsSearch.value.directory = getDirectory.value.join(',');
      // paramsSearch.value.directory = form.value.directory;
    }
    getPageList();
  };
  const knowledgeCatalogData = useSelectStore().knowledgeCatalogTree;
  function getKnowledgeCatalog(id, data) {
    let res = [];
    data.forEach((item) => {
      if (item.value === id) {
        res.push(item.value);
        getChildList(res, item);
      }

      // res.push({
      //     label: item.label,
      //     value: item.id,
      //     children: (item.children && item.children.length > 0) ? filterTreeData(item.children) : []
      // })
    });
    // return res.join(',');
  }
  function getChildList(res, data) {
    if (data.children && data.children.length > 0) {
      data.children.forEach((eleChild) => {
        res.push(eleChild.value);
        getChildList(res, eleChild.children);
      });
    } else {
      getDirectory.value = res;
    }
  }
</script>

<style lang="scss" scoped>
  .firstTitle{
    min-width: 200px;
  }
  .wrap::-webkit-scrollbar {
    display: none; /* Chrome Safari */
  }
  .wrap {
    overflow-y: auto;
    height: 100%;
    position: relative;
    scrollbar-width: none; /* firefox */
    -ms-overflow-style: none; /* IE 10+ */
    .searchBtn {
      display: inline-block;
      margin-bottom: 15px;
    }
    .searchBox {
      .searchBox1 {
        display: inline-block;
        width: 80%;
        .input-with-select {
          margin-bottom: 8px;
        }
      }
      .searchBox2 {
        /* width: 50%; */
        display: inline-block;
      }
    }
    .content {
      text-align: left;
      width: 98%;
      .list ul {
        list-style: none;
        color: rgba(0, 0, 0, 0.65);
        font-size: 14px;
        font-variant: tabular-nums;
        line-height: 1.5;
        li {
          position: relative;
          .title {
            font-size: 16px;
            font-weight: bolder;
            cursor: pointer;
            color: #000c17;
          }
          .category {
            color: #9e9e9e;
            font-size: 12px;
            span {
              background: #f4f4f4;
              font-size: 12px;
              padding: 3px 8px;
              border-radius: 5px;
              height: 28px;
              line-height: 28px;
              margin-right: 5px;
              color: #5c6065;
            }
          }
          .text {
            overflow: hidden;

            text-overflow: ellipsis;

            display: -webkit-box;

            -webkit-line-clamp: 2;

            overflow: hidden;

            /*! autoprefixer: off */

            -webkit-box-orient: vertical;
          }
          .button {
            position: absolute;
            right: 30px;
            bottom: 26px;
          }
        }
      }
    }
  }
</style>
