<template>
    <div class="page-container row-container">
        <!-- 左侧区域 -->
        <section class="list-part-container" style="flex: 3">
            <!-- 搜索区 -->
            <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true"
                style="margin-right: 0px">
                <el-form-item class="section-title" label="分选废品报表" />
                <el-form-item label="产品描述：">
                    <el-input placeholder="请输入产品描述" v-model.trim="queryParams.productDescription"
                        @blur="trimBlur('productDescription')" @keydown.enter.prevent clearable style="width: 130px" />
                </el-form-item>
                <el-form-item label="批次号：">
                    <el-input placeholder="请输入批次号" v-model.trim="queryParams.lotCode" @blur="trimBlur('lotCode')"
                        @keydown.enter.prevent clearable style="width: 130px" />
                </el-form-item>
                <el-form-item label="时间：">
                    <el-date-picker v-model="queryParams.startTime" type="date" value-format="YYYY-MM-DD"
                        :editable="false" clearable placeholder="请选择" style="width: 136px" />
                    <span>到</span>
                    <el-date-picker v-model="queryParams.endTime" type="date" value-format="YYYY-MM-DD"
                        :editable="false" clearable placeholder="请选择" style="width: 136px" />
                </el-form-item>
                <el-form-item style="margin-left: 0">
                    <el-button type="info" icon="Search" @click="handleQuery">搜索
                    </el-button>
                    <el-button type="success" icon="Download" @click="handlePrint">导出</el-button>
                </el-form-item>
            </el-form>
            <div class="el-table-container">
                <div class="el-table-inner-container">
                    <el-table ref="sortRejectTable" :data="sortRejectList" v-loading="sortRejectLoading"
                        highlight-current-row height="100%" style="overflow-x: auto;">
                        <el-table-column label="序号" width="60" prop="lineNumber" align="center" />
                        <el-table-column label="规格" prop="specification" width="100" align="center" />
                        <el-table-column label="日期" prop="date" align="center" width="100" />
                        <el-table-column label="批次号" prop="lotCode" width="110" align="center" />
                        <el-table-column label="产品描述" prop="productDescription" align="center" width="auto" />
                        <el-table-column label="分选量" prop="firstSortProd" width="70" align="center" />
                        <el-table-column label="实际量" prop="actualQuantity" width="70" align="center" />
                        <el-table-column label="废品量" prop="totalRejectNum" width="70" align="center" />
                        <el-table-column label="不明量" prop="unknownQuantity" width="70" align="center" />
                        <el-table-column label="不良率" prop="rejectRate" width="70" align="center" />
                        <el-table-column label="不明率" prop="unknownRate" width="70" align="center" />
                        <el-table-column label="批次率" prop="lotRate" width="70" align="center" />
                        <template v-for="column in sortCheckStandardList" :key="column.id">
                            <el-table-column :prop="column.inspectionInstructionId" :label="column.checkStandard"
                                width="80px" align="center">
                                <template #default="scope">
                                    {{ getSortCheck(scope.row.checkStandardList, column.inspectionInstructionId) }}
                                </template>
                            </el-table-column>
                        </template>
                    </el-table>
                </div>
            </div>
            <!-- 分页 -->
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getSortCheckStandardList" />
        </section>

    </div>
</template>

<script setup>
import { getSortCheckStandard, getSortRejectList, printSortReject } from "@/api/business/dayworkItemReject.js";
import { ref } from "vue";
import { flattenDeep } from 'lodash-es';
import queryStore from "@/store/modules/query";

const { proxy } = getCurrentInstance();
/** 报工信息 */
const sortRejectList = ref([]);
const sortCheckStandardList = ref([])
const total = ref(0);
const data = ref([])
const sortRejectLoading = ref(false);

const queryParams = ref({
    lotCode: null,
    productDescription: null,
    startTime: null,
    endTime: null,
    pageNum: 1,
    pageSize: 10
});

/***********************  工段相关事件  ****************************/
function getList() {
    getNowDate();
    //获得分选检查项目
    getSortCheckStandardList()
}
function getSortCheckStandardList() {
    const listQueryParams = queryStore().sortRejectParams;
    if (listQueryParams != null) {
        queryParams.value = listQueryParams;
    }
    getSortCheckStandard(queryParams.value).then(res => {
        sortCheckStandardList.value = res.data
    })
    //查询分选废品
    getSortReject()
}
function handlePrint() {
    printSortReject(queryParams.value)
}
function getSortCheck(row, data) {
    if (row.length > 0) {
        // console.log(row)
        let ids = row.map(item => item.inspectionInstructionId)
        if (ids.findIndex(item => item == data) > -1) {
            return row[ids.findIndex(item => item == data)].rejectNum
        } else {
            return '';
        }
    }
    return ''
}
function getNowDate() {
    queryParams.value.endTime = proxy.moment().format("YYYY-MM-DD")
    queryParams.value.startTime = proxy.moment().clone().subtract(3, 'month').format("YYYY-MM-DD");
    console.log(queryParams.value.startTime);
}
function getSortReject() {
    sortRejectLoading.value = true;
    getSortRejectList(queryParams.value).then(res => {
        let list = []
        for (let i = 0; i < res.rows.length; i++) {
            let index = i
            let data = res.rows[i]
            data.lineNumber = index + 1
            list.push(data)
            if ((index != res.rows.length - 1 && res.rows[i].productionPlanDetailId != res.rows[i + 1].productionPlanDetailId) || (index != res.rows.length - 1 && res.rows[i].date != res.rows[i + 1].date) || index == res.rows.length - 1) {
                let checkList = []
                let total = {}
                total.specification = "小计"
                let equalsPro = res.rows.filter(item => item.productionPlanDetailId == res.rows[index].productionPlanDetailId && item.date == res.rows[index].date)

                let check = computed(() => flattenDeep(equalsPro.map(item => item.checkStandardList))).value
                let standardIds = check.map(item => { return item.inspectionInstructionId })
                standardIds.forEach(item => {
                    let info = {}
                    let sum = check.filter(info => info.inspectionInstructionId == item)
                        .reduce((acc, obj) => {
                            // 确保 acc 和 obj.rejectNum 都是数字
                            return acc + parseInt(obj.rejectNum);
                        }, 0); // 提供初始值 0
                    info.inspectionInstructionId = item
                    info.rejectNum = sum
                    checkList.push(info)
                });
                total.checkStandardList = checkList
                list.push(total)
            }
        }
        console.log(list)
        sortRejectList.value = list
        total.value = res.total
        console.log(total.value)
        sortRejectLoading.value = false
    })
}
/** 搜索按钮操作 */
function handleQuery() {
    // 判断查询开始时间不能大于结束时间
    if (queryParams.value.startTime > queryParams.value.endTime) {
        proxy.$modal.msgError('结束时间不能小于开始时间')
        return
    }
    const listQueryParams = JSON.parse(JSON.stringify(queryParams.value));
    queryStore().setSortRejectParams(listQueryParams);
    getSortCheckStandardList()
}

function trimBlur(param) {
    queryParams.value[param] = queryParams.value[param].trim()
}

onMounted(() => {
    getList();
});
</script>
<style scoped>
.el-form--inline .el-form-item {
    margin-right: 20px;
}
</style>