<template>
  <a-row :gutter="5">
    <a-col :span="leftWidth">
      <div style="background-color: #ececec; padding: 0px; height: 77vh; overflow: hidden;">
          <a-card style="width: 100%; overflow: hidden; background: #fff; height:75vh" :loading="loading" size="small" :bordered="false">
            <template #title>控制项列表</template>
            <template #extra>
              <a-button size="small" style="margin: 5px" @click="handleChangeLeftWidth">
                <menuUnfoldOutlined v-if="collapsed" class="trigger" />
                <MenuFoldOutlined v-else class="trigger" />
              </a-button>
            </template>
            <div style="height:66vh;overflow: hidden">
              <vxe-table
                keep-source
                ref="tableActRef"
                size="small"
                show-overflow
                max-height="100%"
                :data="acts"
                :show-radio="true"
                :row-config="{ isCurrent: true, isHover: true }"
                @current-change="changeEvent"
                :columnConfig="{ resizable: true }"
                :scroll-y="{ enabled: true, gt: 50 }"
                :radio-config="{ labelField: 'name', highlight: true }"
              >
                <vxe-column type="seq" width="40" />
                <vxe-column field="caName" sortable type="html" title="控制项名称" />
                <vxe-column field="id" title="" :visible="false" />
              </vxe-table>
            </div>
          </a-card>
      </div>
    </a-col>
    <a-col :span="24 - leftWidth">
      <div style="background-color: #ececec; padding: 0px; height: 77vh; overflow: hidden">
          <div style="width: 100%; max-height: 75vh; overflow-y: auto">
            <template v-if="!acts || acts.length == 0">
              <a-card style="width: 100%; overflow: hidden; background: #fff; height: 100%" :loading="loading" size="small" :bordered="false">
                <template #title>报告详细内容</template>
                <template #extra>
      
                  <a-button type="link" @click="setCollapsed"  style="margin-right:20px">返回</a-button>
                  <a-button size="small" style="margin: 5px" @click="setCollapsed">
                    <menuUnfoldOutlined v-if="collapsed" class="trigger" />
                    <MenuFoldOutlined v-else class="trigger" />
                  </a-button>
                  
                </template>
      
                <div style="height:69vh;overflow-y:auto">
                  <vxe-grid v-bind="gridOptionsSimple" 
                        border  
                        stripe 
                        show-overflow 
                        auto-resize
                        max-height="100%"
                        keep-source
                        :check-config="{ highlight: true }"
                        :columnConfig="{ resizable: true }"
                        :row-config="{ isCurrent: true, isHover: true }"
                        ref="exportsSimpleTableRef" 
                      >
                  </vxe-grid>
                </div>
              </a-card>
            </template>
              
            <template v-else>
              <a-card
                size="small"
                :bordered="false"
                style="height:75vh; font-size: 14px"
                :tab-list="curTabDatas"
                :active-tab-key="activeKey"
                :loading="loading"
                @tabChange="(key) => onTabChange(key)"
              >
                <template #tabBarExtraContent>
                  <a-button type="link" @click="showDrawer"  style="margin-right:100px">导出检查列表</a-button>
                  <a-button type="link" @click="exportEvent"  style="margin-right:20px">导出当前表</a-button>
                  <a-button type="link" @click="setCollapsed"  style="margin-right:20px">返回</a-button>       
                  <a-button size="small" style="margin: 5px" @click="changeShowMode">
                    <MenuOutlined v-if="showTp" />
                    <AppstoreOutlined v-else />
                  </a-button>   
                </template>
                <template v-if="showTp">
                  <div style="height:66vh;overflow: hidden">
                    <vxe-table 
                      keep-source 
                      ref="curTableRef" 
                      size="small" 
                      max-height="100%"
                      show-overflow 
                      auto-resize
                      :check-config="{ highlight: true }"
                      :column-config="{ resizable: true,useKey: true,}"
                      :row-config="{ isCurrent: true, isHover: true }" 
                      @cell-click="cellClickEvent"
                      :checkbox-config="{ highlight: true,checkStrictly:false }"
                      @checkbox-change="handleSelectEvent"
                      :data="curLibDatas"
                      @checkbox-all="handleSelectAll"
                    >
                      <vxe-column type="seq" width="50" />
                      <vxe-column type="checkbox" width="40"></vxe-column>
                      <vxe-column v-for="(col, ind) in newwCols[activeKey]" :key="ind" :field="col['field']" type="html" :title="col['title']" />
                      
                      <vxe-column :visible="activeKey==5" title="操作" fixed="right" width="10%">
                        <template #default="{ row }">
                          <vxe-button mode="text" size="small" @click="handleAddReport(row)">添写报告</vxe-button>
                        </template>
                      </vxe-column>
                    </vxe-table>
                  </div>
                </template>
                <template v-else>
                  <a-collapse v-model:activeKey="collapsedactiveKey" accordion style="width:100%;margin:0px;padding:0px;height:64vh;overflow-y:auto" expand-icon-position="right">
                    <a-collapse-panel v-for="(act,actInd) in acts" :key="actInd" :header="act.caName"  style="width:100%;">
                    <a-card style="width: 100%; overflow: hidden;max-height:300px;background:#ececec;overflow-y: auto;margin:0px;padding:0px" size="small" :bordered="false">
                      <div v-for="(row, dInd) in curLibDatas" :key="dInd" style="margin: 0px;border: 0px solid black;padding:2px">
                        <template v-for="(col, ind) in newwCols[activeKey]" :key="ind">
                          <a-descriptions  size="middle" :contentStyle="{'background':'#FFF','padding':'10px'}" :labelStyle="{'background':'#FFF','minWidth':'100px','padding':'10px',marginRight:'2px'}" :span="col.span">
                            <a-descriptions-item  :label="col['title']" style="padding-bottom: 1px;">
                              <div v-if="row && col['field']" style="display: grid; place-items: center; padding-top: 0px; margin: 0px;">  
                                <a v-if="col['field']=='fileName'" @click="showFileContent(row)">  
                                  <p v-html="row[col['field']]"></p>  
                                </a>  
                                <p v-else v-html="row[col['field']]"></p>  
                              </div> 
                            </a-descriptions-item>
                          </a-descriptions>
                        </template>
                      </div>
                    </a-card>
                   </a-collapse-panel> 
                  </a-collapse>
                </template>
              </a-card>
            </template>
           
         
        </div>
      </div>
    </a-col>
  </a-row>

  <a-drawer
    title="检查信息列表"
    v-model:visible="isOpenDrawer"
    placement="right"
    :closable="true"
    :mask="false"
    :get-container="false"
    width="100%"
    @close="onClose"
  >
    <div style="height:90vh;overflow: hidden">
      <vxe-grid v-bind="gridOptions" 
          border  
          stripe 
          auto-resize
          max-height="100%"
          keep-source
          :check-config="{ highlight: true }"
          :columnConfig="{ resizable: true }"
          :row-config="{ isCurrent: true, isHover: true }"
          ref="exportTableRef" 
        >
      </vxe-grid>
    </div>
  </a-drawer>
  <FileViewerModal @register="regShowFileContentModal" :useStaticPrefixForDocx="true" />
  <CheckItem ref="refCheckItem" />
  <TaskReportIndex ref="refTaskReportIndex" />
</template>

<script lang="ts" setup>
  import { ref, reactive,nextTick } from 'vue';
  import { queryAllDataReport } from './report.api';
  import { auditCols,srhCond } from './ReportCommon.data';
  import FileViewerModal from '/@/components/onlinePreview/FileViewerModal.vue';
  import CheckItem from '../components/CheckItem.vue';

  import TaskReportIndex from '../TaskReportIndex.vue';


  import { useModal } from '/@/components/Modal';
  import { MenuUnfoldOutlined, MenuFoldOutlined, MenuOutlined, AppstoreOutlined, FullscreenExitOutlined } from '@ant-design/icons-vue';

  import VXETable from 'vxe-table'
  import VXETablePluginExportXLSX from 'vxe-table-plugin-export-xlsx'
  import ExcelJS from 'exceljs'

  import { cloneDeep } from 'lodash-es';

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

  const tableActRef = ref();
  const curTableRef = ref();
  const exportTableRef = ref()
  const collapsed = ref(false);
  const activeKey = ref(1);
  const collapsedactiveKey = ref(0);

  const refCheckItem = ref()
  const refTaskReportIndex = ref()

  const loading = ref(false);
  const showTp = ref(true);
  const showAct = ref(true);
  const leftWidth = ref(5);
  const curAct = ref({});
  const isOpenDrawer = ref(false)

  const selectedDatas = ref({});

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

  VXETable.use(VXETablePluginExportXLSX, {
      ExcelJS
    })

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

  const curTabDatas = ref([{}]);
  const condDatas = ref({});
  const datas = ref({});
  const acts = ref([]);
  const newwCols = ref({});
  const oldData = ref({});
  const curLibDatas = ref([]);
  const curTp = ref();

  const curFileDoc =  ref()

  const repordTableDatas = ref([]);

  const simpleDatas = ref([])

  const gridOptions = reactive({
      border: true,
      showFooter: true,
      exportConfig: {
        sheetMethod (params) {
          const { worksheet } = params
          
          worksheet.columns.forEach(sheetColumn => {
            sheetColumn.width = 60
          })
      
          worksheet.eachRow((excelRow, rowIndex) => {
            excelRow.height = 30
            if (rowIndex <= 2) {
              excelRow.eachCell(excelCell => {
                // 填充单元格背景
                excelCell.fill = {
                  type: 'pattern',
                  pattern: 'solid',
                  fgColor: {
                    argb: 'c5d9f1'
                  }
                }
              })
            }
          })

          worksheet.eachRow(excelRow => {
            excelRow.eachCell(excelCell => {
              // 设置单元格边框
              excelCell.border = {
                top: {
                  style: 'thin',
                  color: {
                    argb: '000'
                  }
                },
                left: {
                  style: 'thin',
                  color: {
                    argb: '000'
                  }
                },
                bottom: {
                  style: 'thin',
                  color: {
                    argb: '000'
                  }
                },
                right: {
                  style: 'thin',
                  color: {
                    argb: '000'
                  }
                }
              }
            })
          })
        }
      },

      toolbarConfig: {
        refresh: false,
        zoom: true,
        custom: true,
        export: true,
        print: true
      },
      columns: [
        { type: 'seq', width: 70 },
        { field: 'caName', title: '控制项',width:200},
      ],
      data: repordTableDatas.value,
      scrollX: {
        enabled: true
      },
      scrollY: {
        enabled: true
      },
      
    })


    const gridOptionsSimple = reactive({
      border: true,
      showFooter: true,
      exportConfig: {
        sheetMethod (params) {
          const { worksheet } = params
          
          worksheet.columns.forEach(sheetColumn => {
            sheetColumn.width = 60
          })
      
          worksheet.eachRow((excelRow, rowIndex) => {
            excelRow.height = 30
            if (rowIndex <= 1) {
              excelRow.eachCell(excelCell => {
                // 填充单元格背景
                excelCell.fill = {
                  type: 'pattern',
                  pattern: 'solid',
                  fgColor: {
                    argb: 'c5d9f1'
                  }
                }
              })
            }
          })

          worksheet.eachRow(excelRow => {
            excelRow.eachCell(excelCell => {
              // 设置单元格边框
              excelCell.border = {
                top: { 
                  style: 'thin',
                  color: {
                    argb: '000'
                  }
                },
                left: {
                  style: 'thin',
                  color: {
                    argb: '000'
                  }
                },
                bottom: {
                  style: 'thin',
                  color: {
                    argb: '000'
                  }
                },
                right: {
                  style: 'thin',
                  color: {
                    argb: '000'
                  }
                }
              }
            })
          })
        }
      },

      toolbarConfig: {
        refresh: false,
        zoom: true,
        custom: true,
        export: true,
        print: true,
        slots: {
          buttons: 'toolbar_buttons',
        },
      },
      columns:[], 
      data: repordTableDatas.value
    })
    

  async function setReportData(conds) {
    selectedDatas.value = []
    //repordTableDatas.value = []
    curFileDoc.value = conds?.fileDoc
    condDatas.value = conds;
    newwCols.value = structuredClone(auditCols);
    curTp.value = conds.tp;
    if (Array.isArray(conds['actIds']) && conds['actIds'].length > 0) {
      loading.value = true;
      let retData = await queryAllDataReport({ actIds: conds['actIds'] });

      Object.entries(retData.datas).forEach(([tp, tpDatas]) => {  
        Object.entries(tpDatas).forEach(([atcid, values]) => {  
          const actItem = acts.value.find(item => item.actId === atcid);   
          values.map(val => ({  
            ...val,
            caName: actItem?.caName,
            actId: atcid,
          }));  

        });

      });

      oldData.value = datas.value = retData?.datas;
      acts.value = retData?.acts;
      loading.value = false;
      showAct.value = true;

      curTabDatas.value = tabDatas.filter((item) => item.key !== curTp.value);
      curTabDatas.value = curTabDatas.value.filter((item) => !!datas.value[item.key]);
      curTabDatas.value.forEach(function(ele) {  
          let tmp = {title:ele.tab}
          const newArray =  newwCols.value[ele.key].map(item => ({  
              ...item,  
              slot: 'col_default',
              width:500
          })); 
          tmp["children"] = newArray
          gridOptions.columns.push(tmp)
      });

      acts.value.forEach(function(ele) {  
        let newRow = {
          actId:ele.id,
          caName:ele.caName
        }
        repordTableDatas.value.push(newRow)
      });
      
     

      nextTick(async () => { 
        await iniSelectDatas()
        await defaultAct(0);
      })

    } else {
      repordTableDatas.value = conds.datas
      nextTick(async () => { 
        let tmpCols =  newwCols.value[curTp.value]
       
        if(!tmpCols) return
        tmpCols.unshift({type: 'seq', width: 50 })

        gridOptionsSimple.columns = tmpCols
        gridOptionsSimple.data = repordTableDatas.value
        acts.value = [];
        showAct.value = false;
        leftWidth.value = 0;
      })
    }
  }

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

  const handleSearch = async (srhText) => {
    if (!srhText) {
      datas.value = oldData.value;
    } else {
      // const filterContent = String(srhText).trim().toLowerCase();
      // const regExp = new RegExp(`(${filterContent})`, 'gi');
      // let fullContent = JSON.stringify(oldData.value);
      // let newData = await fullContent.replace(regExp, "<span style='color:red'>$1</span>");
      // curLibDatas.value = JSON.parse(newData);

      const filterContent = String(srhText).trim().toLowerCase();
      const searchProps = srhCond[activeKey.value]
      const filterRE = new RegExp(filterContent, 'gi');

      let tmpAry = datas.value[activeKey.value][curAct.value.id];
      const rest = tmpAry.filter((item) => searchProps.some((key) => String(item[key]).toLowerCase().indexOf(filterContent) > -1));
      curLibDatas.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;
      });

    }
  };

  const onTabChange = async(tp) => {
    curAct.value = {};
    activeKey.value = tp;
    curLibDatas.value = []
    tableActRef.value.clearCurrentRow();
    let tmpObj = cloneDeep(datas.value[tp]);
   
   
    let allTabDatas = []
    Object.entries(tmpObj).forEach(([atcid, values]) => {  
      if (Array.isArray(values)) { 
        allTabDatas.push(...values);  
      }  
    }); 

    let fileName = ""
    if(curTp.value==1&&curFileDoc.value?.fileName&&tp==5){
      fileName = curFileDoc.value?.fileName
      curLibDatas.value = allTabDatas.filter(item => item.fileName === fileName);
    }  else {
      curLibDatas.value = allTabDatas
    }
    const $table = curTableRef.value;
    if(!$table) return;

    nextTick(() => {
         console.log(allTabDatas.length,"3333") 
        $table.clearCheckboxRow() 
        $table.setCheckboxRow(curLibDatas.value, true)
        setSelectDatas();
    });  

  };


  function setCollapsed() {
    emit('closeLeft', false);
  }

  async function changeEvent({ row }) {
   // await creaateReportData();
    onClose()
    curAct.value = row;
    if(activeKey.value) {
      showCurActData(row.id);
    }
 
  }

  function changeShowMode() {
    showTp.value = !showTp.value;
  }

  async function defaultAct(ind) {
    if(curTabDatas.value.length>0) {
      onTabChange(curTabDatas.value[0].key);
    }
  }

  function handleChangeLeftWidth() {
    collapsed.value = !collapsed.value
    if(collapsed.value) {
      leftWidth.value = 1
    } else {
      leftWidth.value = 5
    }
  }

  function showDrawer(){
    isOpenDrawer.value = true
    creaateReportData();
  }

  function onClose() {
    isOpenDrawer.value = false
  }

  async function setSelectDatas() {
    let tp = activeKey.value;
    let rows = await getSelectDatas()

    rows.forEach((row) => {   
      let newKey= row.actId+ "_" + tp
      if(!selectedDatas.value[newKey]) {
        selectedDatas.value[newKey] = [row] 
      } else {
        selectedDatas.value[newKey].push(row);
      }
    })
  }

  async function iniSelectDatas() {
    curTabDatas.value.forEach(function(ele) {  
      let tp = ele.key;
      let tmpObj = oldData.value[tp];
      Object.entries(tmpObj).forEach(([actId, values]) => {  
          let newKey= actId+ "_" +tp
          if(!selectedDatas.value[newKey]) {
            selectedDatas.value[newKey] = values
          } else {
            selectedDatas.value[newKey].push(...values);
          }
      })
       
    });
  }


  function creaateReportData() {
    repordTableDatas.value.forEach(function(rowEle) { 
      Object.keys(selectedDatas.value).forEach(function(acttpKey) {  
        let tmpDatas = selectedDatas.value[acttpKey]
        let actTpAry = acttpKey.split('_')
        let actId = actTpAry[0]
        let tp =actTpAry[1]
        if(tmpDatas&&tmpDatas.length>0) { 
          if(rowEle.actId==actId){
            newwCols.value[tp].forEach(function(col) { 
              let newDataAry = [];   
              tmpDatas.forEach(function(eleData) {  
                let tmpData = {};   
                tmpData['value'] = eleData[col.field];  
                tmpData['title'] = col.title;  
                newDataAry.push({...tmpData});
              });  
              Object.defineProperty(rowEle, col.field, {  
                value: setValue(newDataAry,col),  
                writable: true,  
                enumerable: true,  
                configurable: true  
              }); 
            });  
            console.log(rowEle,"rowEle")
          }
        } else {
          Object.defineProperty(rowEle, ('col'+tp), {  
              value:"",  
              writable: true,
              enumerable: true,  
              configurable: true 
          });  
        }
      }); 
    })
        
  }



  function getSelectDatas() {
    let datas = [];
    const $table = curTableRef.value;
    if ($table) {
      const selRecords = $table.getCheckboxRecords();
      selRecords.forEach(function (ele) {
        datas.push(ele);
      });
    }
    return datas;
  }

  async function handleSelectEvent({ row: row }) {
    await setSelectDatas();
  }


  function cellClickEvent({row, column} ){
    if(column.title=="操作") return
    const $table = curTableRef.value;
    if(!$table) return;
    $table.toggleCheckboxRow(row);
    handleSelectEvent({ row: row });
  }

  function exportEvent() {
    const $table = curTableRef.value;
    if(!$table) return;
    $table.exportData({
      type: 'xlsx',
      original: true
    })
  }

  function handleSelectAll() {
    setSelectDatas();
  }

  function setColumns(tabDatas) {
    tabDatas.forEach(function(ele) { 
      let tmp = {field:("col"+ele.key),title:ele.tab,slots:{ default: 'col_default'}}
      tmp["child"] =  newwCols[+ele.key]
      gridOptions.columns.push(tmp)
    });
  }

  function setValue(datas,col) {
    let strTmp = ""
    let i=0;
    datas.forEach(function(data) { 
      i++;
      let tmpVal = data.value?data.value:null
      if(tmpVal) {
        if(col.field=='fileName') {
          strTmp +=""+i+"《" + tmpVal + "》\t\n"
        } else {
          strTmp +=""+i+"." + tmpVal + "\t\n"
        }
      }
    
    })
    return strTmp;
  }


  const showCurActData = async(actId) => {
  
    let tp = activeKey.value
    let tmpAry = datas.value[tp][actId];
    let fileName = ""
    if(curTp.value==1&&curFileDoc.value?.fileName&&tp==5){
      fileName = curFileDoc.value?.fileName
      curLibDatas.value = tmpAry.filter(item => item.fileName === fileName);
    }  else {
      curLibDatas.value = tmpAry
    }
    const $table = curTableRef.value;
    if(!$table) return;
    let newKey= curAct.value.id+"_" +tp
    let rows = selectedDatas.value[newKey]
    if(rows){
      $table.clearCheckboxRow()
      $table.setCheckboxRow(rows, true)
    } else {
      nextTick(() => {  
        selectedDatas.value[newKey] = curLibDatas.value
        $table.setCheckboxRow(curLibDatas.value, true)
      });  
    }
  };


  function handleAddReport(row) {
    let checkData = {checkid:row.id}
    refCheckItem.value.iniData(checkData)
  }

  


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

<style scope>
  .highlight {
    background-color: yellow;
  }
  .ant-card-body {
    padding: 2px;
  }
  .ant-card-small > .ant-card-body {
    padding: 1px; 
  }
</style>
