<template>
  <div class="jeecg-basic-table-form-container" style="background-color: #ffffff">
    <div v-if="searchFlag" class="stm-query" @keyup.enter="handlerStandSearch" style="background-color: ; margin: 0px">
      <a-row :gutter="24">
        <a-col class="gutter-row" :lg="6" />
        <a-col class="gutter-row" :lg="6" />
        <a-col class="gutter-row" :lg="12" :span="2" :offset="0" style="text-align: right">
          <!-- <a-button type="link" @click="handlerStandardlibSwitch">管理后台</a-button> -->
          <!-- <a-button type="link" @click="handelCreateIndex" :loading="loading">创建索引</a-button> -->
          <a-button type="link" @click="handelCreateDocLib" :loading="loading" v-if="hasPermission('stm:es:file:createDocLib')">同步数据</a-button>
        </a-col>
      </a-row>
      <a-form style="margin-top: 10%; margin-bottom: 20%">
        <a-row :gutter="24">
          <a-col :lg="4" />
          <a-col :lg="16">
            <a-typography-title class="stm-typography">文件内容搜索</a-typography-title>
          </a-col>
          <a-col :lg="3" />
        </a-row>
        <a-row :gutter="24">
          <a-col :lg="4" />
          <a-col :lg="14">
            <a-form-item>
              <a-input-search
                ref="stminput1"
                size="large"
                placeholder="请输入"
                v-model:value="queryParam.name"
                :loading="loading"
                enter-button="搜索"
                autofocus="autofocus"
                @search="handlerStandSearch"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :lg="4" />
          <a-col :lg="14">
            <a-tabs v-model:activeKey="queryParam.sctype">
              <a-tab-pane v-for="item in standardlibQueryRadioArr" :key="item.value" :tab="item.label" />
            </a-tabs>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div v-else class="stm-query">
      <a-form style="position: fixed; top: 2; width: 98%; margin-top: -50px; z-index: 11; padding-top: 20px; opacity: 1">
        <a-card
          :bordered="false"
          style="margin: 0px; height: 120px; display: hidden; overflow: hidden; width: 100%; margin: 0px; padding-top: 20px"
          :body-style="{ padding: 0 }"
        >
          <a-row :gutter="24">
            <a-col :lg="14">
              <a-input-search
                ref="stminput2"
                size="large"
                placeholder="请输入"
                v-model:value="queryParam.name"
                :loading="loading"
                enter-button="搜索"
                @search="handlerStandSearch"
              />
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :lg="24">
              <a-tabs v-model:activeKey="queryParam.sctype" @change="handlerRadioChange" style="margin-top: 5px; padding-top: 0px">
                <a-tab-pane v-for="item in standardlibQueryRadioArr" :key="item.value" :tab="item.label" />
              </a-tabs>
            </a-col>
          </a-row>
        </a-card>
      </a-form>

      <div style="margin-top: 110px; min-height: 200px; z-index: 10">
        <a-list item-layout="horizontal" :data-source="dataList" style="width: 100%">
          <template #renderItem="{ item }">
            <a-list-item>
              <a-list-item-meta>
                <template #description>
                  <div v-if="item.allHilight" style="font-weight: 500; line-height: 26px; font-size: medium; color: black">
                    <!-- <span  v-html="item.allHilight[0].substring(0,500)"> </span> -->
                    <span v-html="handlerDesc(item.allHilight)"> </span>
                  </div>
                  <div style="font-weight: 500; line-height: 26px; font-size: medium; color: black">
                    <a-button
                      :loading="loading"
                      v-if="item.fpath"
                      ghost
                      type="link"
                      @click="showFileContent(item)"
                      xs="100%"
                      sm="100%"
                      style="margin-left: 0px; padding-left: 0px"
                    >
                      <span v-if="item.sctype == 11">查看原始文件</span>
                      <span v-else v-html="item.fpathHight"></span>
                    </a-button>
                    <a-button
                      v-if="item.allHilight"
                      :loading="loading"
                      ghost
                      type="link"
                      @click="handlerShowDetail(item)"
                      xs="100%"
                      sm="100%"
                      style="margin-left: 0px; padding-left: 0px"
                      >查看所有搜索结果</a-button
                    >
                  </div>
                </template>
                <template #title>
                  <h5 style="color: #000000d9; font-size: 1.2em; font-weight: 600">
                    <span v-html="item.name"></span>
                    <Tag style="margin-left: 10px">
                      <span>{{ setTagName(item.sctype) }}</span>
                    </Tag>
                  </h5>
                </template>
              </a-list-item-meta>
            </a-list-item>
          </template>
        </a-list>
        <Pagination
          style="text-align: center; margin-top: 40px"
          v-model:current="pagination.current"
          show-quick-jumper
          :total="pagination.total"
          @change="pageChange"
        />
      </div>
    </div>
    <div>
      <FileDetail @register="registerModalDetail" />
    </div>
  </div>
  <FileViewerModal @register="registerShowFileContentModal" />
</template>
<script lang="ts" name="es-esSearchFile" setup>
  import { Pagination, Tag } from 'ant-design-vue';
  import { useModal } from '/@/components/Modal';
  import { Base64 } from 'js-base64';
  import { nextTick, ref, unref } from 'vue';
  import { useRouter } from 'vue-router';
  import { filelist, createFileDocLib } from './esStandLibQuery.api';
  import { useDrawer } from '/@/components/Drawer';
  import FileDetail from './FileDetail.vue';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { isEmpty } from '/@/utils/is';
  import FileViewerModal from '/@/components/onlinePreview/FileViewerModal.vue';

  const { hasPermission } = usePermission();

  const stminput1 = ref(null);
  const stminput2 = ref(null);
  const loading = ref(true);
  const searchFlag = ref(true);

  const [registerModalDetail, { openDrawer }] = useDrawer();
  const [registerShowFileContentModal, { openModal: openFileContentModel }] = useModal();

  const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 100,
  });
  const standardlibQueryRadioArr = ref([
    { label: '全部', value: '' },
    { label: '法律', value: '1' },
    { label: '法规', value: '2' },
    { label: '监管意见', value: '3' },
    { label: '风险提示', value: '4' },
    { label: '行业实践', value: '10' },
    { label: '行业标准', value: '11' },
  ]);
  nextTick(() => {
    stminput1.value?.focus();
  });

  const router = useRouter();
  const queryParam = ref({
    name: '',
    content: '',
    sctype: '',
    pageNo: pagination.value.current,
    pageSize: pagination.value.pageSize,
  });

  const dataList = ref([]);

  function handlerStandardlibSwitch() {
    router.push({ path: '/standardlib' });
  }

  function setTagName(sctp) {
    for (let i in standardlibQueryRadioArr.value) {
      if (standardlibQueryRadioArr.value[i].value == sctp) {
        return standardlibQueryRadioArr.value[i].label;
      }
    }

    return '';
  }

  function handlerShowDetail(record) {
    openDrawer(true, { data: record, srh: queryParam.value.name });
  }

  function handlerDesc(hilightAry) {
    if (!hilightAry) return '';
    let len = hilightAry.length;
    let qstr = queryParam.value.name;
    let ret = hilightAry[0];
    const regex = /<em\s+style=['"]color:\s*red;?\s*['"]>(.*?)<\/em>/gi;
    for (let i = 0; i < len; i++) {
      let strTmp = hilightAry[i];
      const matchArr = strTmp.match(regex); // 匹配到的所有 <em> 标签的数组
      if (!matchArr) continue;
      let allText = '';
      for (let j = 0; j < matchArr.length; j++) {
        allText += matchArr[j].replace(/<\/?em[^>]*>/g, '');
      }
      let p = allText.indexOf(qstr);
      if (p > -1) {
        ret = strTmp;
        break;
      }
    }
    return ret;
  }

  function handlerStandSearch() {
    loading.value = true;
    searchFlag.value = false;
    queryParam.value.pageNo = 1;
    pagination.value.current = 1;
    pagination.value.total = 0;
    onSearch();
    setTimeout(function () {
      stminput2.value?.focus();
    }, 100);
  }

  function handlerRadioChange() {
    handlerStandSearch();
  }
  function onSearch() {
    dataList.value = [];
    filelist(unref(queryParam)).then((rep) => {
      dataList.value = rep.rows;
      pagination.value.current = queryParam.value.pageNo;
      pagination.value.total = rep.total;
      pagination.value.pageSize = queryParam.value.pageSize;
      loading.value = false;
    });
  }
  function pageChange(page, pageSize) {
    queryParam.value.pageNo = page;
    queryParam.value.pageSize = pageSize;
    onSearch();
  }
  function handlerGotoPage(item) {
    if (item.sctype == '1') {
      router.push({ path: '/standardlib/compliane/fl', query: { bizNo: item.bizNo, querName: queryParam.value.name } });
    } else if (item.sctype == '2') {
      router.push({ path: '/standardlib/compliane/fg', query: { bizNo: item.bizNo, querName: queryParam.value.name } });
    } else if (item.sctype == '3') {
      router.push({ path: '/standardlib/compliane/jg', query: { bizNo: item.bizNo, querName: queryParam.value.name } });
    } else if (item.sctype == '4') {
      router.push({ path: '/standardlib/compliane/fx', query: { bizNo: item.bizNo, querName: queryParam.value.name } });
    } else if (item.sctype == '5') {
      router.push({ path: '/standardlib/compliane/cf', query: { bizNo: item.bizNo, querName: queryParam.value.name } });
    }
  }

  function handelCreateDocLib() {
    loading.value = true;
    createFileDocLib(handleSuccess);
  }

  function handleSuccess() {
    loading.value = false;
  }

  function handleGoOldFile(item) {
    if (item.sctype == 11) {
      window.open(item.fpath);
    } else {
      let globOnlineViewUrl: string = import.meta.env.VITE_GLOB_ONLINE_VIEW_URL;
      let globOnlineViewServerUrl: string = import.meta.env.VITE_GLOB_ONLINE_VIEW_SERVER_URL;
      let urlpath = globOnlineViewUrl + item.fpath;
      urlpath = encodeURIComponent(Base64.encode(urlpath));
      window.open(globOnlineViewServerUrl + '?url=' + urlpath);
    }
  }

  setTimeout(() => {
    loading.value = false;
  }, 500);

  function showFileContent(item) {
    if (item.fpath) {
      openFileContentModel(true, {
        record: item,
        isUpdate: false,
        showFooter: true,
      });
    }
  }
</script>
<style scoped>
  .jeecg-basic-table-form-container {
    padding: 10px;
    position: relative;
  }
  .jeecg-basic-table-form-container .stm-query {
    padding: 12px 10px 6px 10px;
    margin-bottom: 8px;
    background-color: #fff;
    border-radius: 2px;
    position: relative;
  }
  .stm-typography {
    color: #009dff;
    font-size: 18px;
  }

  .stm-query em {
    color: red;
  }
</style>
