
<template>
  <div class="layout-pd">
    <el-row>
<!--操作-->
      <el-col :xs="24" >
        <el-card class="mt8"  shadow="hover" >
<el-form :model="state.filter" :inline="true" @submit.stop.prevent style="margin-bottom: -3vh;">
            <el-form-item prop="name" style="width: 100%">
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
  <el-form-item label="主板类型">
                  <el-select v-model="state.filter.boardType" placeholder="">
                    <el-option v-for="(value, key) in PCBABoardType" :key="key" :label="value[1].name"
                      :value="Number(value[1].value)" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                <el-form-item label="检测员">
                  <el-input v-model="state.filter.lastTestUser" placeholder="单行输入" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                <el-form-item label="创建时间">
                  <el-date-picker
                    v-model="state.filter.createTimeRange"
                    type="daterange"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    range-separator="To"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  />
                </el-form-item>
              </el-col>
</el-form-item>
          </el-form>

          <hr>

          <el-row class="submit-button" style="margin-bottom:-6px">
<el-button  type="primary" icon="ele-Search" @click="onQuery"> 查询 </el-button>
<el-button  type="primary" icon="ele-Document" @click="exportDataToExcel"> 导出 </el-button>
          </el-row>
</el-card>
      </el-col>
<!--表格-->
      <el-col  :xs="24" >
        <el-card class="my-fill mt8" shadow="hover">
<el-table v-loading="state.loading" ref="myTable" stripe :data="state.tableModel" row-key="id" style="width: 100%">
        <!--<el-table-column v-for="column in state.dynamicColumns" :key="column.prop" :prop="column.prop" :label="column.label"  >
        </el-table-column>-->






            <el-table-column prop="boardType" label="主板类型">
              <template #default="{ row }">
                <div :style="{ color: getPCBABoardType(row.boardType).color }" class="bold-font">
                  {{ getPCBABoardType(row.boardType).name }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="code" label="功能码" />
            <el-table-column prop="name" label="功能名称" />
            <el-table-column prop="num" label="测试功能数量" />
            <el-table-column prop="successNum" label="通过数量" />
            <el-table-column prop="oneTestSuccessNum" label="测试一次通过数量" />
            <el-table-column prop="testTimes" label="测试次数" />
            <el-table-column prop="testSuccessTimes" label="测试成功次数" />
            <el-table-column prop="successRate" label="测试通过率" >
            <template #default="{ row }">
                <div> {{row.successRate }}%</div>
              </template>
            </el-table-column>
            <el-table-column prop="oneTestSuccessRate" label="测试一次通过率" >
            <template #default="{ row }">
                <div> {{row.oneTestSuccessRate }}%</div>
              </template>
            </el-table-column>
            <el-table-column prop="testSuccessRate" label="测试成功率">
            <template #default="{ row }">
                <div> {{row.testSuccessRate }}%</div>
              </template>
            </el-table-column>



</el-table>
<div class="my-flex my-flex-end" style="margin-top: 20px">
            <el-pagination
              v-model:currentPage="pageState.pageInput.currentPage"
              v-model:page-size="pageState.pageInput.pageSize"
              :total="state.total"
              :page-sizes="[10, 15, 20, 50, 100]"
              small
              background
              @size-change="onSizeChange"
              @current-change="onCurrentChange"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
</el-card>
      </el-col>
</el-row>
    </div>
  </template>
  <script setup lang="ts">
  import {onBeforeMount, onMounted, reactive, watch,ref} from "vue";
  import eventBus from "/@/utils/mitt";
import { BoardFunctionSummaryApi } from '/@/api/admin/PCBA/boardFunctionSummaryApi'
import { BoardFunctionSummaryOutput } from '/@/api/admin/PCBA/boardFunctionSummaryDto'
import type { pageInput } from "/@/api/admin/shareDto/shareDto";
import { useGlobalCacheStore } from "/@/stores/globalCacheStore";
import { getCurrentInstance } from 'vue';
import { saveAs } from 'file-saver';
import * as ExcelJS from 'exceljs';
import { useDynamicPageSize } from "/@/composables/useDynamicPageSize";

// 使用组合式函数获取分页状态
const pageState = useDynamicPageSize(10, 15);

const { proxy: ctx } = getCurrentInstance();

/**获取全局缓存*/
const globalCacheStore = useGlobalCacheStore()
/**数据字典缓存*/
const PCBATestState = ref(globalCacheStore.getGlobalStore().get('pcbaTestState'))
const PCBABoardType = ref(globalCacheStore.getGlobalStore().get('pcbaBoardType'))

const getPCBATestState = (val) => {
  val = String(val)
  if(PCBATestState.value?.has(val)){
    return PCBATestState.value.get(val)
  }else {
    return val
  }
}

const getPCBABoardType = (val) => {
  val = String(val)
  if(PCBABoardType.value?.has(val)){
    return PCBABoardType.value.get(val)
  }else {
    return val
  }
}

/**数据对象*/
  const state = reactive({
    /**加载显示 */
    loading: false,
    /**条件查询模块 */
      filter: {
/**boardType */
        boardType: -1,
/**检测员 */
        lastTestUser: "",
// 创建时间范围
        createTimeRange:[],
      },
  /**表格信息 */
tableModel: [] as BoardFunctionSummaryOutput,
    /**动态表头 */
    dynamicColumns: [
{ prop: 'code', label: '功能码' },
{ prop: 'name', label: '功能名称' },
{ prop: 'num', label: '测试功能数量' },
{ prop: 'successNum', label: '通过数量' },
{ prop: 'oneTestSuccessNum', label: '测试一次性通过数量' },
{ prop: 'testTimes', label: '测试次数' },
{ prop: 'testSuccessTimes', label: '测试成功次数' },
{ prop: 'successRate', label: '测试通过率，单位：%' },
{ prop: 'oneTestSuccessRate', label: '测试一次性通过率，单位：%' },
{ prop: 'testSuccessRate', label: '测试成功率，单位：%' },],
/**分页标识 */
    pageInput:{
      CurrentPage: 1,
      PageSize: 10,
    } as pageInput,
    /**分页总数 */
    total: 0,
})
  onMounted(() => {
    // 初始化分页大小
state.pageInput.PageSize = pageState.pageInput.pageSize;
    init()
    eventBus.off('refreshView')
    eventBus.on('refreshView', async () => {
      await init()
    })
  })
  onBeforeMount(() => {
    eventBus.off('refreshView')
  })

      /**页条数变化*/
const onSizeChange = () => {
  init()
}

/**页数变化*/
const onCurrentChange = () => {
  init()
}



  /**
  * 监听变换
  */
  watch(() => {},() => {})
/**条件查询 */
          const onQuery = () => {
          init()
        }
/**初始化 */
const init = async () => {
  state.loading = true;
  // 处理时间范围，将数组中的开始和结束时间分别赋值给API需要的字段
  const { createTimeRange, ...filterWithoutTimeRange } = state.filter;
  const beginCreateTime = createTimeRange.length > 0? createTimeRange[0] : "";
  const endCreateTime = createTimeRange.length > 1? createTimeRange[1] : "";


  const res: any = await new BoardFunctionSummaryApi().getList({
   ...pageState.pageInput,
    Filter: {
     ...filterWithoutTimeRange,
      beginCreateTime,
      endCreateTime,
    },
  });
  state.total = res?.data?.total?? 0;
  state.tableModel = res?.data?.list?? [];


  state.loading = false;
};


      async function exportDataToExcel() {

const tableData = ctx.$refs.myTable.data;

    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('My Sheet');
    worksheet.columns = [
        { header: '主板类型', key: 'boardType', width: 15 },
        { header: '功能码', key: 'code', width: 15 },
        { header: '功能名称', key: 'name', width: 15 },
        { header: '测试功能数量', key: 'num', width: 15 },
        { header: '通过数量', key: 'successNum', width: 15 },
        { header: '测试一次通过数量', key: 'oneTestSuccessNum', width: 15 },
        { header: '测试次数', key: 'testTimes', width: 15 },
        { header: '测试成功次数', key: 'testSuccessTimes', width: 15 },
        { header: '测试通过率', key: 'successRate', width: 15 },
        { header: '测试一次通过率', key: 'oneTestSuccessRate', width: 15 },
        { header: '测试成功率', key: 'testSuccessRate', width: 15 }

    ];




    for (let i = 0; i < tableData.length; i++)
    {
      let data = {...tableData[i]};
      data.boardType = getPCBABoardType(data.boardType).name
      data.successRate +="%";
      data.oneTestSuccessRate +="%";
      data.testSuccessRate +="%";

      worksheet.addRow(data);
    }



    
  
    // await workbook.xlsx.writeFile('output.xlsx');

    // 生成 Excel 文件
    const buffer = await workbook.xlsx.writeBuffer();

    // 将文件保存到本地
    const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    saveAs(blob, '主板功能检测汇总.xlsx');

      console.log('文件已成功导出！');
  }


</script>
<style scoped lang="scss">
.el-input,
.el-select {
  width: 240px;
}

/* 输入框标签固定四个字符宽度 */
::v-deep .el-form-item__label {
  // 字体大小14，4个字符，12px右间距
  width: 14*4px+12px;
  justify-content: start;
}

/* 数据表头 设置灰色样式 */
::v-deep .el-table th.el-table__cell {
  background-color: #F6F6F6;
}
  </style>