<template> 
<div>
      <a-card
        size = "small"
        :width="leftWidth"
        style="height:76vh; font-size: 14px;"
        :tab-list="tabDatas"
        :active-tab-key="activtyTabKey"
        :loading="loading"
        @tabChange="(key) => onTabChange(key)"
      >

      <template #tabBarExtraContent>
        <a-button type="link" v-show="!isFileList" @click="isFileList=true">返回</a-button>
        <a-button type="link" v-show="!isFileList" @click="showSelectList">查看检查列表</a-button>
        <a-button type="link" v-show="!isFileList" @click="queryLibData">进入下一步选择/创建检查列表</a-button>
      </template>
      <LeftLibList  ref="refAuditCommonList" @callback="callboack"/>  
      <a-drawer
          title="文件列表"
          v-model:visible="isFileList"
          placement="bottom"
          :closable="true"
          :mask="false"
          :get-container="false"
          :style="{ position: 'absolute' }"
          height="90%"
          @close="onClose"
        >
          <template #extra>
            <vxe-button @click="onClose">关闭</vxe-button>
          </template>
          <div>
            <DocFileList ref="refDocFilelist" @showItem="showItem" />
          </div>
        </a-drawer>
            
      </a-card>

  <ShowFileContentModal @register="regShowFileContentModal" />
</div>
</template>
<script lang="ts" setup>
import { ref, nextTick,reactive } from 'vue';
import { MenuUnfoldOutlined, MenuFoldOutlined } from '@ant-design/icons-vue';
import LeftLibList from './LeftLibList.vue';
import { VXETable } from 'vxe-table';
import { queryActRelates } from '../index.api';
import { auditCols,srhCond } from './ReportCommon.data';
import DocFileList from './DocFileList.vue';
import ShowFileContentModal from '../components/modal/ShowFileContentModal.vue';
import { useModal } from '/@/components/Modal';
const [regShowFileContentModal, { openModal }] = useModal();


const activtyTabKey = ref(1);
const curAct = ref({});
const loading = ref(false)
const refAuditCommonList = ref();
const srhContent = ref();
const refDocFilelist = ref();
const leftWidth = ref(24)
const collapsed = ref(false)

const tableData = ref([]);
const listData = ref([]);
const isFileList = ref(false)
const fileData = ref([])
const activeCollapseKey = ref(1)



const tabDatas = [
  {tab: '合规', key: 1},
  {tab: '内控策略',key: 2},
  {tab: '内控制度',key: 3},
  {tab: '问题',key: 4},
  {tab: '检查项',key: 5},
  {tab: '风险',key: 6},
  {tab: '实践',key: 7},
  {tab: '控制项',key: 9}
];

const collapses = ref([]);
const selectedDatas = ref({});
const emit = defineEmits(['callback','query','closeLeft']);

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


const handleSearch = async(srhText) => {
  srhContent.value =srhText
  if(isFileList.value) {
    await refDocFilelist.value.handleSearch(srhText);
    return;
  }
  if (!srhText) {
      tableData.value = listData.value;
      await refAuditCommonList.value.setTableData(activtyTabKey.value,listData.value)
  } else {
    const filterContent = String(srhText).trim().toLowerCase();
    const searchProps = srhCond[activtyTabKey.value]
    const filterRE = new RegExp(filterContent, 'gi');
    const rest = listData.value.filter((item) => searchProps.some((key) => String(item[key]).toLowerCase().indexOf(filterContent) > -1));
    tableData.value = rest.map((row) => {
      const item = Object.assign({}, row);
      searchProps.forEach((key) => {
        item[key] = String(item[key]).replace(filterRE, (match) => `<span class="keyword-lighten" style="color:red">${match}</span>`);
      });
      return item;
    });
    refAuditCommonList.value.setTableData(activtyTabKey.value,tableData.value)
  }
};

async function setDataList() {
  //let actId =  curAct.value?.id;
  loading.value = true;
  listData.value = tableData.value = await queryActRelates({
    tp: activtyTabKey.value,
    actId: null,
  });
  loading.value = false;
  await nextTick();

  let tp =  activtyTabKey.value
  if (tp == 1 || tp == 2 || tp == 3 || tp == 7) {
    if (listData.value.length > 0) {
      isFileList.value = true;
      await setFileListData(listData.value);
      nextTick(async () => {
        await refDocFilelist.value.iniData(fileData.value);
      });
    } else {
      isFileList.value = false;
      await refAuditCommonList.value.setTableData(activtyTabKey.value, listData.value);
    }
  } else {
    isFileList.value = false;
    await refAuditCommonList.value.setTableData(activtyTabKey.value, listData.value);
  }
  loading.value = false;
}

function callboack(tp) {

  // if(!selectedDatas.value[tp]) {
  //   selectedDatas.value[tp] = [] 
  //   selectedDatas.value[tp] = rows;
  // } else {
  //   selectedDatas.value[tp] = []
  //   selectedDatas.value[tp] = rows;
  // }
  activeCollapseKey.value = tp
  queryLibData()

  // let tt = tabDatas.find(item => item.key === tp); 
  // collapses.value = []
  // collapses.value.push(tt)


  // let exist = collapses.value.find(item => item.key === tp); 
  // if(!exist) {
  //   collapses.value.push(tt)
  // }
}


async function iniActList() {
  await setDataList()
}

function setCollapsed() {
  emit("closeLeft",true);
}

async function queryLibData() {
  let datas = await refAuditCommonList.value.getSelectDatas();
  let newData = {}
  if(!Array.isArray(datas) || datas.length==0) {
    VXETable.modal.message({ content: '请选择记录', status: 'warning' });
    return;
  }

  
  let actIds = []
  if(activtyTabKey.value==9){
    datas.forEach(function(ele) {
      if(ele['id']) {
        actIds.push(ele['id'])
      }
    }); 
  } else if(activtyTabKey.value<6){
    datas.forEach(function(ele) {
      if(ele['actIds']) {
        let tmpAry = ele["actIds"].split(",")
        tmpAry.forEach(id => {  
          actIds.push(id)
        });
      }
    }); 
  }

  newData["actIds"] = actIds.map(Number); 
  newData["datas"] = datas;
  newData["tp"] = activtyTabKey.value;
  emit("query",newData);
  setCollapsed(true)
}

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

  async function showItem(doc) {
    //fileDoc.value = doc;
    isFileList.value = false;
    nextTick();
    await handleSearch(doc.fileName)
    emit("callback",doc);
    //await refAuditCommonList.value.setTableData(activtyTabKey.value, listData.value);
  }

  function showFileContent(row) {
    if (row.filePath) {
      openModal(true, {
        record: row,
        isUpdate: false,
        showFooter: true,
      });
    }
  }

  function onClose() {
    isFileList.value = false
    refAuditCommonList.value.setTableData(activtyTabKey.value, listData.value);
  }


  function closeLeft(isCloseLeft) {
    leftWidth.value =  isCloseLeft?0:24
  }

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


defineExpose({
  iniActList,
  handleSearch,
  closeLeft
});

</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: #fff;
  height: calc(90vh - 120px);
  margin: 0px 0px 0px 0px;
  overflow: hidden;
  min-height: 400px;
}
</style>
