<template>  
  <div class="layout">  
    <a-card
        style="width: 100%; font-size: 14px; background: "
        :bordered="false"
        size="small"
        contentFullHeight="true"
        :tab-list="tabDatas"
        :active-tab-key="activeKey"
        :loading="loading"
        @tabChange="(key) => onTabChange(key)"
        :bodyStyle="{ height: '77vh' }"
        >
        <div v-if="activeKey == 1" style="height:100%; padding: 0px">
            <vxe-table
              border
              keep-source
              ref="tableRef"
              size="small"
              height="auto"
              :data="allReportData"
              :row-config="{ isCurrent: true, isHover: true,useKey:true }"
              :column-config="{ resizable: true,useKey:true }"
              :scroll-y="{ enabled: true, gt: 50 }"
              :radio-config="{ labelField: 'label', highlight: true }"
            >
              <vxe-column type="seq" width="50" />
              <vxe-column field="prjName" title="项目" width="8%"  :visible="true"  :filters="prjList"  :filter-method="filterPrjMethod"/>
              <vxe-column field="fileName" title="来源文件" width="12%"  :visible="true"  :filters="fileList"  :filter-method="filterFileMethod"/>
              <vxe-column field="item" title="合规条目" width="10%"  :visible="true" :filters="textFilters" :filter-method="textFilterMethod" :filter-render="textFilterRender"/>
              <vxe-column field="checkContent" title="检查点"  width="20%"  :visible="true" :filters="textFilters" :filter-method="textFilterMethod" :filter-render="textFilterRender"/>
              <vxe-column field="checkItemTp" title="方法分类" width="6%"  :visible="true"  :filters="tpDicts"  :filter-method="filterTpMethod">
                <template #default="{ row }">
                 <template v-for="(item, ind) in tpDicts" :key="ind">
                    <span v-if="item.value==row.checkItemTp" v-html="item.text"></span>
                  </template>
                </template> 
              </vxe-column>
              <vxe-column field="prjItemName" title="检查方法" :visible="true" :filters="textFilters" :filter-method="textFilterMethod" :filter-render="textFilterRender"/>
              <vxe-column field="situation" title="现状" width="10%"  :visible="true" :filters="textFilters" :filter-method="textFilterMethod" :filter-render="textFilterRender"/>
              <vxe-column field="issues" title="存在问题" width="10%"  :visible="true" :filters="textFilters" :filter-method="textFilterMethod" :filter-render="textFilterRender"/>
              <vxe-column field="score" title="得分" width="5%"  :visible="true" :filters="scoreOpts" :filter-method="filterScoreMethod"/>
            </vxe-table>
        </div>
        <div v-else-if="activeKey == 2" style="height:100%; padding: 0px">
          <vxe-grid ref="gridRef"  :row-config="{ isCurrent: true, isHover: true }" v-bind="gridOptions">
            <template #toolbar_buttons>
              <a-space wrap style="margin: 5px auto;">
                <a-checkbox-group v-model:value="chkSels" name="checkboxgroup" :options="chkOptions" @change="chkChange"/>
              </a-space>
            </template>
            <template #checkItemTp_slot="{ row }">
              <template v-for="(item, ind) in tpDicts" :key="ind">
                <span v-if="item.value==row.checkItemTp" v-html="item.text"></span>
              </template>
            </template> 
            <template #totalScore_slot="{ row }">
              <span>{{ row.totalScore }}/{{ row.count*5 }}</span>
            </template> 

            <template #averageScore_slot="{ row }">
              <span>{{ row.averageScore }}/5</span>
            </template> 

            
          </vxe-grid>
        </div>
        <template #tabBarExtraContent>
          <a-button type="link" @click="clearFilter()">刷新</a-button>
      </template>
    </a-card>
  </div>
</template>
<script lang="ts" setup> 
import { ref, nextTick, onMounted,reactive } from 'vue';  
import { VxeColumnPropTypes,VxeGridProps } from 'vxe-table';  
import { defHttp } from '/@/utils/http/axios';  
import XEUtils from 'xe-utils'
import { getDictItemsByCode } from '/@/utils/dict';

const allReportDataUrl = "/audit/auditTaskReport/findAllTaskReport"
const activeKey = ref(1);
const allReportData = ref([]);
const loading = ref(false)

const tableRef = ref()
const gridRef = ref()
const tpDicts = ref([])
const scoreOpts = ref([{}])

const tabDatas = [
    { tab: '所有记录', key: 1 },
    { tab: '得分统计', key: 2 },
];

const chkOptions = [
  { label: '项目名称', value: 'prjName' },
  { label: '来源文件', value: 'fileName' },
  { label: '合规条目', value: 'item' },
  { label: '检查点', value: 'checkContent' },
  { label: '方法分类', value: 'checkItemTp'},
];

const chkSels = ref(['prjName'])
const fileList = ref([{}])
const prjList = ref([{}])

const filterFileMethod: VxeColumnPropTypes.FilterMethod = ({ value, row }) => {
  return row.fileId*1==value*1
}

const filterTpMethod: VxeColumnPropTypes.FilterMethod = ({ value, row }) => {
  return row.checkItemTp*1==value*1
}

const filterScoreMethod: VxeColumnPropTypes.FilterMethod = ({ value, row }) => {
  return (row.score >=value && row.score < value+1)
}



const filterPrjMethod: VxeColumnPropTypes.FilterMethod = ({ value, row }) => {
  return row.projectid*1==value*1
}

const textFilterRender: VxeColumnPropTypes.FilterRender = {
  name: 'VxeInput',
};

const textFilters = ref([
  { data: '' }
])

function textFilterMethod({ option, row, column }) {
  if (option.data) {
    return `${row[column.field]}`.indexOf(option.data) > -1;
  }
  return true;
}

const setFileList = async () => {
  const uniqueFileList = Array.from(  
    new Map(  
      allReportData.value.map(item => [item.fileId, { value: item.fileId, label: item.fileName }])  
    ).values()  
  );  
  fileList.value = uniqueFileList
  // const $table = tableRef.value;  
  // if ($table) {  
  //   $table.setFilter('fileName',uniqueFileList);  
  // }  
}

const setProjectList = async () => {
  const uniqueFileList = Array.from(  
    new Map(  
      allReportData.value.map(item => [item.projectid, { value: item.projectid, label: item.prjName }])  
    ).values()  
  );  
  prjList.value = uniqueFileList
  // const $table = tableRef.value;  
  // if ($table) {  
  //   $table.setFilter('prjName',uniqueFileList);  
  // }  
}

const setScoreFilterOpts = () => {
  scoreOpts.value = [
    { label: '分数[1-2)', value: 1 },
    { label: '分数[2-3)', value: 2 },
    { label: '分数[3-4)', value: 3 },
    { label: '分数[4-5]', value: 4 },
  ]
}

const gridOptions = reactive<VxeGridProps>({
  border: true,
  stripe: true,
  showFooter: true,
  height: 'auto',
  tooltipConfig: {},
  exportConfig: {},
  menuConfig: {},
  columnConfig: {
    resizable: true,
    useKey:true
  },
  rowConfig:{
    useKey:true 
  },
  toolbarConfig: {
    zoom: true,
    custom: true,
    export: true,
    slots: {
      buttons: 'toolbar_buttons',
    },
  },
  columns: [
    { type: 'seq',width: '50'},
    {
      field: 'prjName',
      title: '项目名称',
      minWidth:180,
      visible: true,
      type:"html",
      filters:prjList,
      filterMethod:filterPrjMethod
    },
    {
      field: 'fileName',
      title: '来源文件',
      showOverflow: 'title',
      minWidth:180,
      visible: false,
      type: 'html',
      filters:fileList,
      filterMethod:filterFileMethod
    },
    {
      field: 'item',
      title: '合规条目',
      minWidth:180,
      visible: false,
      type: 'html',
    },
    {
      field: 'checkContent',
      title: '检查点',
      showOverflow: 'title',
      minWidth:300,
      visible: false,
      type:"html",
    },
    {
      field: 'checkItemTp',
      title: '方法分类',
      minWidth: 110,
      visible: false,
      type:"html",
      slots: { default: 'checkItemTp_slot' }
    },
    {
      field:'totalScore',
      title: '得分/总分',
      visible: true,
      slots: { default: 'totalScore_slot' },
      type:"html",
      minWidth:120
    },
    {
      field:'averageScore',
      title: '平均分/分数',
      visible: true,
      slots: { default: 'averageScore_slot' },
      type:"html",
      minWidth:120
    },
    {
      field:'count',
      title: '记录数',
      visible: true,
      type:"html",
      minWidth:100
    },
    
  ],
  data: [],
});

const iniData = async () => {
  allReportData.value  = await defHttp.get({url: allReportDataUrl, params:{}});
  tpDicts.value = await getDictItemsByCode("check_item_tp")
  await setFileList();
  await setProjectList();
  await setScoreFilterOpts()
}

const onTabChange = async (curKey) => {
    activeKey.value = curKey;
    if(curKey==2) {
        nextTick(async ()=>{
          const $gridRef = gridRef.value;  
          if ($gridRef) {  
            gridOptions.data  = allReportData.value
            chkOptions.forEach(item => $gridRef.hideColumn(item.value));  
            const uniqueSelections = new Set(chkSels.value);  
            uniqueSelections.forEach(item => $gridRef.showColumn(item));  
            const finalResult = await groupAndCalculate(allReportData.value, Array.from(uniqueSelections));  
            gridOptions.data = finalResult;   
          }
        })
    }
};

const clearFilter = () => {
  const $tableRef = tableRef.value 
  $tableRef?.clearFilter();
  const $gridRef = gridRef.value 
  $gridRef?.clearFilter();
}

function findColumnByField(field) {  
  return  gridOptions["columns"]?.findIndex(column => column.field === field);  
} 

async function chkChange() {  
  const $gridRef = gridRef.value;  
  if ($gridRef) {  
    chkOptions.forEach(item => $gridRef.hideColumn(item.value));  
    const uniqueSelections = new Set(chkSels.value);  
    uniqueSelections.forEach(item => $gridRef.showColumn(item));  
    const finalResult = await groupAndCalculate(allReportData.value, Array.from(uniqueSelections));  
    gridOptions.data = finalResult;   
  }  
}


function groupAndCalculate(data, groupByFields) {  
  const result = data.reduce((acc, item) => {  
    const key = groupByFields.map(field => item[field]).join('|'); 

    if (!acc[key]) {  
      acc[key] = { 
        totalScore: 0,  
        count: 0,  
        averageScore: 0,  
        group: {}  
      };  
    }  

 
    acc[key].totalScore += item.score;  
    acc[key].count += 1;  

    acc[key].group = {};  
    groupByFields.forEach(field => {  
      acc[key].group[field] = item[field];  
    });  

    acc[key].group['fileId'] = item['fileId'];  
    acc[key].group['projectid'] = item['projectid'];  

    // 计算平均分  
    acc[key].averageScore = (acc[key].totalScore / acc[key].count).toFixed(2);  

    return acc;  
  }, {});  


  return Object.values(result).map(group => ({  
    ...group.group,  
    totalScore: group.totalScore,  
    averageScore: parseFloat(group.averageScore),  
    count: group.count  
  }));  
}


onMounted(async () => {  
    iniData();  
});  
</script>

<style scope>
  .layout {
    background: #fff;
    margin: 5px;
    overflow: hidden;
    height: 85vh;
  }
</style>
