<template>
  <a-card
    style="width: 100%; font-size: 14px; disabled: true"
    :bordered="false"
    contentFullHeight="true"
    :tab-list="tabDatas"
    :active-tab-key="activtyTabKey"
    :loading="loading"
    :disabled="true"
    @tabChange="(key) => onTabChange(key)"
    :bodyStyle="{ height: '99%' }"
  >
    <div style="margin: 0px 0; height: 100%">
      <div v-show="isFileList" style="height: 100%">
        <DocFileList ref="refDocFilelist" @showItem="showItem" />
      </div>
      <div v-show="!isFileList" style="height: 100%">
        <AuditCommonLibList ref="refAuditCommonList" @showFileList="showFileList" @callBackAct="callBackAct" @success="handleSuccess" />
      </div>
    </div>
    <template #tabBarExtraContent>
      <div :loading="loading" v-show="!isFileList">
        <a-space :size="3">
          <a-button size="middle" type="primary"  ghost @click="showForm(false)" :loading="loading">新建</a-button>
          <a-button size="middle" type="primary"  ghost @click="showForm(true)" :loading="loading">编辑</a-button>
          <a-button size="middle" type="primary"  ghost v-show="activtyTabKey == 1" @click="handleLink()" :loading="loading">关联</a-button>
          <a-button size="middle" type="primary"  ghost v-show="activtyTabKey != 10"  @click="handleSetLabels">设置标签</a-button>
          <a-button size="middle" type="primary"  ghost v-show="activtyTabKey > 1 && activtyTabKey < 6"  @click="handleBatchSetAct">设置控制项</a-button>
          <a-button size="middle" type="primary"  ghost v-show="activtyTabKey == 9" @click="mergeActModel()">控制项合并</a-button>
          <a-button size="middle" type="primary"  ghost v-show="activtyTabKey == 1 || activtyTabKey == 3" @click="handleContentGrp()">分组管理</a-button>
          <a-button size="middle" type="primary"  ghost @click="deleteRecord()">删除</a-button>       
        </a-space>
      </div>
    </template>
    <template #customTab="{ key, tab }">
      <a :class="{ 'ant-dropdown-link': true, 'disabled-tab': isTabDisabled(key) }" :loading="loading" v-show="!loading">
        {{ tab }}
      </a>
    </template>
  </a-card>
  <CategoriesModal @register="registerModal" />
  <ItemLink ref="refItemLink"></ItemLink>
</template>
<script lang="ts" setup>
  import { ref, nextTick } from 'vue';
  import { VxeUI } from 'vxe-table';
  import AuditCommonLibList from './components/AuditCommonLibList.vue';
  import DocFileList from './components/DocFileList.vue';
  import ItemLink from './components/ItemLink.vue';
  import CategoriesModal from './components/modal/AuditFileContentCategoriesModal.vue';
  import { queryActRelates, batchActDeleteByTp } from './index.api';
  import { auditCols, srhCond } from './components/data/AuditCommon.data';
  import { useModal } from '/@/components/Modal';

  const [registerModal, { openModal }] = useModal();

  const emit = defineEmits(['callBackAct', 'setSearchTp', 'callback']);

  const fileDoc = ref();
  const activtyTabKey = ref(1);
  const loading = ref(false);
  const refAuditCommonList = ref();
  const srhContent = ref();
  const tableData = ref([]);
  const listData = ref([]);
  const fileData = ref([]);

  const refItemLink = ref();

  const isFileList = ref(true);
  const refDocFilelist = ref();

  const tabDatas = [
    { tab: '合规库', key: 1 },
    // { tab: '内控制度', key: 3 },
    { tab: '问题库', key: 4 },
    { tab: '检查方法库', key: 5 },
    { tab: '风险事件库', key: 6 },
    { tab: '行业实践库', key: 7 },
    { tab: '风险分类', key: 8 },
    { tab: '控制项', key: 9 },
    { tab: '标签库', key: 10 },
  ];

  const onTabChange = (value) => {
    activtyTabKey.value = value;
    nextTick(async () => {
      await setDataList();
    });
  };

  async function setDataList() {
    let tp = activtyTabKey.value;
    loading.value = true;
    listData.value = tableData.value = await queryActRelates({
      tp: tp,
      actId: undefined,
    });
    loading.value = false;

    await nextTick();

    if (tp == 1 || tp == 3 || tp == 7) {
      if (listData.value.length > 0) {
        isFileList.value = true;
        await setFileListData(listData.value);
        nextTick(async () => {
          await refDocFilelist.value.iniData(fileData.value);
          await refAuditCommonList.value.setFilterOptions();
        });
      } else {
        isFileList.value = false;
        await refAuditCommonList.value.setTableData(activtyTabKey.value, listData.value);
        await refAuditCommonList.value.setFilterOptions();
      }
      emit('setSearchTp', setFileSrhOption());
    } else {
      isFileList.value = false;
      await refAuditCommonList.value.setTableData(activtyTabKey.value, listData.value);
      emit('setSearchTp', setSrhOption(auditCols[tp], srhCond[tp]));
    }

    loading.value = false;
  }

  function showForm(isUpdate) {
    loading.value = true;
    let tp = activtyTabKey.value;
    if (isUpdate) {
      refAuditCommonList.value.showForm(isUpdate, tp, listData.value);
    } else {
      refAuditCommonList.value.showForm(isUpdate, tp, []);
    }
    loading.value = false;
  }

  async function deleteRecord() {
    let tp = activtyTabKey.value;
    let ids = await refAuditCommonList.value.getSelectIds();
    if (ids.length == 0) {
      VxeUI.modal.message({ content: '请选择待删除的记录', status: 'warning' });
      return false;
    }
    await batchActDeleteByTp(tp, { ids: ids.join(',') }, handleSuccess);
  }

  function mergeActModel() {
    refAuditCommonList.value.mergeActModel();
  }

  async function handleSuccess() {
    await setDataList();
    nextTick(async () => {
      if (isFileList.value && fileDoc.value) {
        let fileId = fileDoc.value.fileId;
        fileDoc.value = fileData.value.find((item) => item.fileId * 1 == fileId * 1);
        await showItem(fileDoc.value);
      }
    });
  }

  async function showItem(doc) {
    fileDoc.value = doc;
    isFileList.value = false;
    emit('setSearchTp', setSrhOption(auditCols[activtyTabKey.value], srhCond[activtyTabKey.value]));
    nextTick(async () => {
      await refAuditCommonList.value.setTableDataFile(activtyTabKey.value, doc);
    });
  }

  async function iniLibList(tp) {
    activtyTabKey.value = tp||1;
    //nextTick();
    await setDataList();
  }

  function showFileList() {
    srhContent.value = '';
    isFileList.value = true;
  }

  function handleSearch(srhContent, col) {
    if (isFileList.value) {
      refDocFilelist.value.handleSearch(srhContent, col);
    } else {
      //handleSearchItem(srhContent,col);
      refAuditCommonList.value.handleSearch(srhContent, col);
      //refAuditCommonList.value.setTableData(activtyTabKey.value, tableData.value);
    }
  }

  async function callBackAct(params, stp) {
    if (stp == 3) {
      let fileId = params?.id;
      activtyTabKey.value = 1;
      await setDataList();
      nextTick(async () => {
        if (isFileList.value) {
          fileDoc.value = fileData.value.find((item) => item.fileId * 1 == fileId * 1);
          await showItem(fileDoc.value);
          console.log(fileDoc.value, 'fileDoc.value old');
        }
      });
    } else {
      emit('callBackAct', params, stp);
    }
  }

  function handleSetLabels() {
    refAuditCommonList.value.addLabels();
  }

  function handleBatchSetAct() {
    refAuditCommonList.value.addBatchActs();
  }

  async function setFileListData(allData) {
    fileData.value = Object.values(
      allData.reduce((acc, { fileName, filePath, fileTp, fileId, issued, issuedDate, issuedSta, docNo, applyRangeCodes, ...rest }) => {
        const key = `${fileId}`;
        if (!acc[key]) {
          acc[key] = { fileName, filePath, fileTp, fileId, issued, issuedDate, issuedSta, docNo, applyRangeCodes, child: [] };
        }
        // 删除 child 属性
        const { child, ...restWithoutChild } = rest; // 使用解构，排除 child 属性
        acc[key].child.push(restWithoutChild);
        return acc;
      }, {})
    );

    // fileData.value = Object.values(allData.reduce((acc, { fileName, filePath,fileTp,fileId, ...rest }) => {
    //     const key = `${fileName}-${filePath}-${fileTp}-${fileId}`;
    //     if (!acc[key]) {
    //         acc[key] = { fileName,filePath,fileTp,fileId , child: [] };
    //     }
    //     //acc[key].child.push(rest);
    //     const { child, ...restWithoutChild } = rest; // 使用解构，排除 child 属性
    //     acc[key].child.push(restWithoutChild);
    //     return acc;
    // }, {}));
  }

  function handleContentGrp() {
    openModal(true, {
      record: fileDoc.value,
      isUpdate: false,
      showFooter: true,
    });
  }

  function setSrhOption(cols, srhCols) {
    let srhColOptions: { label: string; value: string }[] = [];
    srhColOptions.push({ value: '', label: '全部' });
    srhCols.forEach(function (srhCol) {
      cols.forEach(function (col) {
        if (col.field == srhCol) {
          srhColOptions.push({
            value: col['field'],
            label: col['title'],
          });
          return;
        }
      });
    });
    return srhColOptions;
  }

  function setFileSrhOption() {
    let options: { value: string; label: string }[] = [];
    options.push({ value: '', label: '全部' });
    options.push({ value: 'fileName', label: '文件名称' });
    options.push({ value: 'issued', label: '发布单位' });
    options.push({ value: 'applyRange', label: '适用范围' });
    options.push({ value: 'issuedDate', label: '发布日期' });
    options.push({ value: 'issuedSta', label: '发布状态' });
    options.push({ value: 'docNo', label: '发布文号' });
    return options;
  }

  async function paramLibList(tp, id) {
    activtyTabKey.value = tp;
    await setDataList();
    nextTick(async () => {
      const foundItem = listData.value.find((item) => item.id * 1 === id);
      if (isFileList.value) {
        const fileId = foundItem.fileId;
        fileDoc.value = fileData.value.find((item) => item.fileId * 1 == fileId * 1);
        await showItem(fileDoc.value);
        nextTick(() => {
          refAuditCommonList.value.handleDetail(foundItem);
        });
      } else {
        nextTick(() => {
          refAuditCommonList.value.handleDetail(foundItem);
        });
      }
    });
  }

  function isTabDisabled(key) {
    return activtyTabKey.value == key;
  }

  function handleLink() {
    const selData = refAuditCommonList.value.getSelectDatas();
    if(!selData||selData.length==0) {
      VxeUI.modal.message({ content: '请选择条目', status: 'warning' });
      return 
    }
    if(selData.length>1) {
      VxeUI.modal.message({ content: '只能选择一条记录', status: 'warning' });
      return false
    }

    refItemLink.value.iniData(selData[0],fileDoc.value,listData.value)
  }

  
  defineExpose({
    iniLibList,
    handleSearch,
    paramLibList,
  });
</script>

<style scope>
  .underline-input {
    border-left: none;
    border-top: none;
    border-right: none;
    width: 100%;
  }
  .ant-tabs-large > .ant-tabs-nav .ant-tabs-tab {
    padding: 16px 0;
    font-size: 14px;
  }

  blockquote.info {
    border-left-color: rgb(91, 192, 222);
    color: rgb(91, 192, 222);
    background-color: rgb(244, 248, 250);
  }
  blockquote {
    display: block;
    unicode-bidi: isolate;
  }

  blockquote {
    padding: 0px 5px;
    color: rgb(119, 119, 119);
    border-left: 4px solid rgb(221, 221, 221);
  }

  .layout {
    background: RED;
    height: 100%;
    margin: 0px 0px 0px 0px;
    overflow: hidden;
    min-height: 450px;
  }
</style>
