<!--
 * @Descripttion: (不良品记录表/qc_scrap_records)
 * @Author: (mes)
 * @Date: (2026-01-22)
-->
<template>
    <div>
        <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent>
            <el-form-item label="物料编码" prop="materialCode">
                <el-select v-model="selectedMaterial" value-key="id" @change="handleSearchMaterialChange" filterable placeholder="请选择">
                    <el-option label="全部" value=""> </el-option>
                    <el-option
                        v-for="(item, index) in options.materialOptions"
                        value-key="id"
                        :key="item.id"
                        :label="`${item.type || ''} ${item.materialCode} ${item.materialName} [${item.supplierName || ''}]`"
                        :value="item">
                        <span style="float: left">{{ item.type || '' }} {{ item.materialCode }} {{ item.materialName }} [{{ item.supplierName || '' }}]</span>
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="产品编号" prop="productCode">
                <el-input v-model="queryParams.productCode" placeholder="请输入产品编号" />
            </el-form-item>
            <el-form-item label="原材料批次号" prop="batchNo">
                <el-input v-model="queryParams.batchNo" placeholder="请输入原材料批次号" />
            </el-form-item>
            <el-form-item label="不良品单号" prop="scrapOrderNo">
                <el-input v-model="queryParams.scrapOrderNo" placeholder="请输入不良品单号" />
            </el-form-item>
            <el-form-item label="不良品类型" prop="scrapType">
                <el-select v-model="queryParams.scrapType" placeholder="请选择不良品类型" filterable>
                    <el-option v-for="item in options.scrapTypeOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item label="线别" prop="lineCode">
                <el-select v-model="queryParams.lineCode" placeholder="请选择线别" filterable>
                    <el-option label="全部" value=""> </el-option>
                    <el-option v-for="item in options.lineCodeOptions" :key="item" :label="item" :value="item" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
                <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
            </el-form-item>
        </el-form>
        <!-- 工具区域 -->
        <el-row :gutter="15" class="mb10">
            <el-col :span="3">
                <el-button type="success" plain icon="document" @click="handleCreateScrapOrder"> 填写原材料报废单 </el-button>
            </el-col>
            <el-col :span="3">
                <el-button type="success" plain icon="document" @click="handleCreateScrapOrder"> 填写成品报废单 </el-button>
            </el-col>
            <el-col :span="3">
                <el-button type="success" plain icon="document" @click="handleCreateScrapOrder"> 填写退货单 </el-button>
            </el-col>
            <el-col :span="3">
                <el-button type="success" plain icon="document" @click="handleCreateTransferOrder"> 填写工单转用单 </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table
            :data="dataList"
            v-loading="loading"
            ref="table"
            border
            header-cell-class-name="el-table-header-cell"
            highlight-current-row
            @sort-change="sortChange">
            <el-table-column prop="scrapOrderNo" label="不良品单号" align="center" v-if="columns.showColumn('scrapOrderNo')" />
            <el-table-column prop="workorder" label="工单号" align="center" v-if="columns.showColumn('workorder')" />
            <el-table-column prop="materialCode" label="物料编码" align="center" v-if="columns.showColumn('materialCode')" />
            <el-table-column prop="materialName" label="物料名称" align="center" v-if="columns.showColumn('materialName')" />
            <el-table-column prop="productCode" label="产品编号" align="center" v-if="columns.showColumn('productCode')" />
            <el-table-column prop="productName" label="产品名称" align="center" v-if="columns.showColumn('productName')" />
            <el-table-column prop="batchNo" label="原材料批次号" align="center" v-if="columns.showColumn('batchNo')" />
            <el-table-column prop="scrapType" label="不良品类型" align="center" v-if="columns.showColumn('scrapType')">
                <template #default="scope">
                    <dict-tag :options="options.scrapTypeOptions" :value="scope.row.scrapType" />
                </template>
            </el-table-column>
            <el-table-column prop="scrapReason" label="不良品原因" align="center" v-if="columns.showColumn('scrapReason')" />
            <el-table-column prop="scrapQuantity" label="不良品数量" align="center" v-if="columns.showColumn('scrapQuantity')" />
            <el-table-column prop="unit" label="单位" align="center" v-if="columns.showColumn('unit')" />
            <el-table-column prop="status" label="状态" align="center" v-if="columns.showColumn('status')">
                <template #default="scope">
                    <dict-tag :options="options.statusOptions" :value="scope.row.status" />
                </template>
            </el-table-column>
            <el-table-column prop="lineCode" label="线别" align="center" v-if="columns.showColumn('lineCode')" />
            <el-table-column prop="workStation" label="工位" align="center" v-if="columns.showColumn('workStation')" />
            <el-table-column prop="operator" label="操作员" align="center" v-if="columns.showColumn('operator')" />
            <el-table-column prop="qualityInspector" label="质检员" align="center" v-if="columns.showColumn('qualityInspector')" />
            <el-table-column prop="supervisorName" label="审核人" align="center" v-if="columns.showColumn('supervisorName')" />
            <el-table-column prop="disposalMethod" label="处置方式" align="center" v-if="columns.showColumn('disposalMethod')" />
            <el-table-column prop="scrapDate" label="不良品日期" v-if="columns.showColumn('scrapDate')" />
            <el-table-column prop="approvalDate" label="审批日期" v-if="columns.showColumn('approvalDate')" />
            <el-table-column prop="remark" label="备注" align="center" v-if="columns.showColumn('remark')" />
            <el-table-column prop="createdTime" label="创建时间" v-if="columns.showColumn('createdTime')" />
            <!-- 以下为隐藏的技术字段 -->
            <el-table-column prop="stoveCode" label="炉号" align="center" v-if="columns.showColumn('stoveCode')" />
            <el-table-column prop="locationCode" label="库存编号" align="center" v-if="columns.showColumn('locationCode')" />
            <el-table-column prop="costImpact" label="成本影响金额" align="center" v-if="columns.showColumn('costImpact')" />
            <el-table-column prop="updatedTime" label="更新时间" v-if="columns.showColumn('updatedTime')" />
            <el-table-column prop="version" label="版本号" align="center" v-if="columns.showColumn('version')" />
            <el-table-column prop="tenantId" label="租户ID" align="center" v-if="columns.showColumn('tenantId')" />
            <el-table-column prop="updatedBy" label="更新人ID" align="center" v-if="columns.showColumn('updatedBy')" />
            <el-table-column prop="createdBy" label="创建人ID" align="center" v-if="columns.showColumn('createdBy')" />
            <el-table-column prop="id" label="主键ID" align="center" v-if="columns.showColumn('id')" />
            <el-table-column label="操作" width="180" fixed="right">
                <template #default="scope">
                    <div>
                        <el-button
                            type="warning"
                            size="small"
                            icon="check"
                            v-hasPermi="['qcscraprecords:approve']"
                            v-if="scope.row.status === '待审批'"
                            @click="handleApprove(scope.row)"
                            >审批</el-button
                        >
                        <el-button
                            type="info"
                            size="small"
                            icon="undo"
                            v-hasPermi="['qcscraprecords:revoke']"
                            v-if="scope.row.status === '已批准'"
                            @click="handleRevoke(scope.row)"
                            >撤销</el-button
                        >
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

        <el-dialog :title="title" :lock-scroll="false" v-model="open">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
                <el-row :gutter="20">
                    <el-col :lg="12">
                        <el-form-item label="工位" prop="workStation">
                            <el-input v-model="form.workStation" placeholder="请输入工位" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="版本号" prop="version">
                            <el-input v-model.number="form.version" placeholder="请输入版本号" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="租户ID" prop="tenantId">
                            <el-input v-model.number="form.tenantId" placeholder="请输入租户ID" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="更新时间" prop="updatedTime">
                            <el-date-picker v-model="form.updatedTime" type="datetime" placeholder="选择日期时间" value-format="YYYY-MM-DD HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="更新人ID" prop="updatedBy">
                            <el-input v-model.number="form.updatedBy" placeholder="请输入更新人ID" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="创建时间" prop="createdTime">
                            <el-date-picker v-model="form.createdTime" type="datetime" placeholder="选择日期时间" value-format="YYYY-MM-DD HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="创建人ID" prop="createdBy">
                            <el-input v-model.number="form.createdBy" placeholder="请输入创建人ID" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" placeholder="请输入备注" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="库存编号" prop="locationCode">
                            <el-input v-model="form.locationCode" placeholder="请输入库存编号" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="成本影响金额" prop="costImpact">
                            <el-input v-model="form.costImpact" placeholder="请输入成本影响金额" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="质检员" prop="qualityInspector">
                            <el-input v-model="form.qualityInspector" placeholder="请输入质检员" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="状态:草稿,待审批,已批准,已拒绝" prop="status">
                            <el-radio-group v-model="form.status">
                                <el-radio v-for="item in options.statusOptions" :key="item.dictValue" :value="item.dictValue">
                                    {{ item.dictLabel }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="审批日期" prop="approvalDate">
                            <el-date-picker v-model="form.approvalDate" type="datetime" placeholder="选择日期时间" value-format="YYYY-MM-DD HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="不良品日期" prop="scrapDate">
                            <el-date-picker v-model="form.scrapDate" type="datetime" placeholder="选择日期时间" value-format="YYYY-MM-DD HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="审核人" prop="supervisorName">
                            <el-input v-model="form.supervisorName" placeholder="请输入审核人" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="操作员" prop="operator">
                            <el-input v-model="form.operator" placeholder="请输入操作员" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12" v-if="opertype != 1">
                        <el-form-item label="主键ID" prop="id">
                            <el-input-number v-model.number="form.id" controls-position="right" placeholder="请输入主键ID" :disabled="true" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="处置方式" prop="disposalMethod">
                            <el-input v-model="form.disposalMethod" placeholder="请输入处置方式" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="不良品类型:质量缺陷,过期,损坏,工艺错误,其他" prop="scrapType">
                            <el-select v-model="form.scrapType" placeholder="请选择不良品类型:质量缺陷,过期,损坏,工艺错误,其他">
                                <el-option
                                    v-for="item in options.scrapTypeOptions"
                                    :key="item.dictValue"
                                    :label="item.dictLabel"
                                    :value="item.dictValue"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="不良品原因" prop="scrapReason">
                            <el-input v-model="form.scrapReason" placeholder="请输入不良品原因" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="单位" prop="unit">
                            <el-input v-model="form.unit" placeholder="请输入单位" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="不良品数量" prop="scrapQuantity">
                            <el-input v-model="form.scrapQuantity" placeholder="请输入不良品数量" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="原材料批次号" prop="batchNo">
                            <el-input v-model="form.batchNo" placeholder="请输入原材料批次号" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="物料名称" prop="materialName">
                            <el-input v-model="form.materialName" placeholder="请输入物料名称" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="物料编码" prop="materialCode">
                            <el-input v-model="form.materialCode" placeholder="请输入物料编码" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="产品名称" prop="productName">
                            <el-input v-model="form.productName" placeholder="请输入产品名称" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="产品编号" prop="productCode">
                            <el-input v-model="form.productCode" placeholder="请输入产品编号" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="炉号" prop="stoveCode">
                            <el-input v-model="form.stoveCode" placeholder="请输入炉号" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="线别" prop="lineCode">
                            <el-input v-model="form.lineCode" placeholder="请输入线别" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="工单号" prop="workorder">
                            <el-input v-model="form.workorder" placeholder="请输入工单号" />
                        </el-form-item>
                    </el-col>

                    <el-col :lg="12">
                        <el-form-item label="不良品单号" prop="scrapOrderNo">
                            <el-input v-model="form.scrapOrderNo" placeholder="请输入不良品单号" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer v-if="opertype != 3">
                <el-button text @click="cancel">{{ $t('btn.cancel') }}</el-button>
                <el-button type="primary" @click="submitForm">{{ $t('btn.submit') }}</el-button>
            </template>
        </el-dialog>

        <!-- 创建报废单对话框 -->
        <el-dialog title="创建报废单" :lock-scroll="false" v-model="scrapOrderOpen">
            <el-form ref="scrapOrderFormRef" :model="scrapOrderForm" :rules="scrapOrderRules" label-width="100px">
                <el-row :gutter="20">
                    <el-col :lg="12">
                        <el-form-item label="物料编码" prop="materialCode">
                            <el-select
                                value-key="id"
                                @change="(val) => handleMaterialChange(val, 'scrap')"
                                v-model="selectedScrapMaterial"
                                filterable
                                placeholder="请选择">
                                <el-option
                                    v-for="(item, index) in options.materialOptions"
                                    :key="item.id"
                                    :label="`${item.type || ''} ${item.materialCode} ${item.materialName} [${item.supplierName || ''}]`"
                                    :value="item">
                                    <span style="float: left"
                                        >{{ item.type || '' }} {{ item.materialCode }} {{ item.materialName }} [{{ item.supplierName || '' }}]</span
                                    >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="物料名称" prop="materialName">
                            <el-input v-model="scrapOrderForm.materialName" placeholder="请输入物料名称" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="原材料批次号" prop="batchNo">
                            <el-input v-model="scrapOrderForm.batchNo" placeholder="请输入原材料批次号" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="不良品数量" prop="scrapQuantity">
                            <el-input v-model="scrapOrderForm.scrapQuantity" placeholder="请输入不良品数量" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="不良品类型" prop="scrapType">
                            <el-select v-model="scrapOrderForm.scrapType" placeholder="请选择不良品类型" disabled>
                                <el-option label="报废" value="报废"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="不良品原因" prop="scrapReason">
                            <el-input v-model="scrapOrderForm.scrapReason" placeholder="请输入不良品原因" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="处置方式" prop="disposalMethod">
                            <el-input v-model="scrapOrderForm.disposalMethod" placeholder="请输入处置方式" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="操作员" prop="operator">
                            <el-input v-model="scrapOrderForm.operator" placeholder="请输入操作员" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="质检员" prop="qualityInspector">
                            <el-input v-model="scrapOrderForm.qualityInspector" placeholder="请输入质检员" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="报废日期" prop="scrapDate">
                            <el-date-picker v-model="scrapOrderForm.scrapDate" type="datetime" placeholder="选择日期时间" value-format="YYYY-MM-DD HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="scrapOrderForm.remark" placeholder="请输入备注" type="textarea" :rows="3" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button text @click="cancelScrapOrder">{{ $t('btn.cancel') }}</el-button>
                <el-button type="primary" @click="submitScrapOrder">{{ $t('btn.submit') }}</el-button>
            </template>
        </el-dialog>

        <!-- 创建转用单对话框 -->
        <el-dialog title="创建转用单" :lock-scroll="false" v-model="transferOrderOpen">
            <el-form ref="transferOrderFormRef" :model="transferOrderForm" :rules="transferOrderRules" label-width="100px">
                <el-row :gutter="20">
                    <el-col :lg="12">
                        <el-form-item label="物料编码" prop="materialCode">
                            <el-select
                                value-key="id"
                                @change="(val) => handleMaterialChange(val, 'transfer')"
                                v-model="selectedTransferMaterial"
                                filterable
                                placeholder="请选择">
                                <el-option
                                    v-for="(item, index) in options.materialOptions"
                                    :key="item.id"
                                    :label="`${item.type || ''} ${item.materialCode} ${item.materialName} [${item.supplierName || ''}]`"
                                    :value="item">
                                    <span style="float: left"
                                        >{{ item.type || '' }} {{ item.materialCode }} {{ item.materialName }} [{{ item.supplierName || '' }}]</span
                                    >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="物料名称" prop="materialName">
                            <el-input v-model="transferOrderForm.materialName" placeholder="请输入物料名称" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="工单号" prop="workorder">
                            <el-input v-model="transferOrderForm.workorder" placeholder="请输入工单号" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="不良品数量" prop="scrapQuantity">
                            <el-input v-model="transferOrderForm.scrapQuantity" placeholder="请输入不良品数量" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="不良品类型" prop="scrapType">
                            <el-select v-model="transferOrderForm.scrapType" placeholder="请选择不良品类型" disabled>
                                <el-option label="转用" value="转用"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="不良品原因" prop="scrapReason">
                            <el-input v-model="transferOrderForm.scrapReason" placeholder="请输入不良品原因" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="处置方式" prop="disposalMethod">
                            <el-input v-model="transferOrderForm.disposalMethod" placeholder="请输入处置方式" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="操作员" prop="operator">
                            <el-input v-model="transferOrderForm.operator" placeholder="请输入操作员" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="质检员" prop="qualityInspector">
                            <el-input v-model="transferOrderForm.qualityInspector" placeholder="请输入质检员" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="报废日期" prop="scrapDate">
                            <el-date-picker v-model="transferOrderForm.scrapDate" type="datetime" placeholder="选择日期时间" value-format="YYYY-MM-DD HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="transferOrderForm.remark" placeholder="请输入备注" type="textarea" :rows="3" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button text @click="cancelTransferOrder">{{ $t('btn.cancel') }}</el-button>
                <el-button type="primary" @click="submitTransferOrder">{{ $t('btn.submit') }}</el-button>
            </template>
        </el-dialog>

        <!-- 审批报废记录对话框 -->
        <el-dialog title="审批报废记录" :lock-scroll="false" v-model="approveOpen">
            <el-form ref="approveFormRef" :model="approveForm" :rules="approveRules" label-width="100px">
                <el-row :gutter="20">
                    <el-col :lg="12">
                        <el-form-item label="审批结果" prop="isApproved">
                            <el-radio-group v-model="approveForm.isApproved">
                                <el-radio :value="true">批准</el-radio>
                                <el-radio :value="false">拒绝</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :lg="12">
                        <el-form-item label="审批人" prop="approver">
                            <el-input v-model="approveForm.approver" placeholder="请输入审批人姓名" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                        <el-form-item label="审批备注" prop="remark">
                            <el-input v-model="approveForm.remark" placeholder="请输入审批备注" type="textarea" :rows="3" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button text @click="cancelApprove">{{ $t('btn.cancel') }}</el-button>
                <el-button type="primary" @click="submitApprove">{{ $t('btn.submit') }}</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="QcScrapRecords">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue'
import {
    listQcScrapRecords,
    addQcScrapRecords,
    delQcScrapRecords,
    updateQcScrapRecords,
    getQcScrapRecords,
    createScrapOrder,
    createTransferOrder,
    approveScrapRecord,
    revokeScrapRecord
} from '@/api/qualityManagement/IPQC/qcscraprecords.js'
import { getMaterialOption } from '@/api/materialManagement/productionMaterial/mminventory.js'

// 获取组件实例
const { proxy } = getCurrentInstance()
const ids = ref([])
const loading = ref(false)
const showSearch = ref(true)
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    sort: '',
    sortType: 'asc',
    materialCode: '',
    productCode: '',
    batchNo: '',
    scrapOrderNo: '',
    scrapType: '',
    lineCode: ''
})
const selectedMaterial = ref(null)
const selectedScrapMaterial = ref(null)
const selectedTransferMaterial = ref(null)
const columns = ref([
    { visible: true, align: 'center', type: '', prop: 'scrapOrderNo', label: '不良品单号', showOverflowTooltip: true },
    { visible: true, align: 'center', type: '', prop: 'workorder', label: '工单号', showOverflowTooltip: true },
    { visible: true, align: 'center', type: '', prop: 'materialCode', label: '物料编码', showOverflowTooltip: true },
    { visible: true, align: 'center', type: '', prop: 'materialName', label: '物料名称', showOverflowTooltip: true },
    { visible: true, align: 'center', type: '', prop: 'productCode', label: '产品编号', showOverflowTooltip: true },
    { visible: true, align: 'center', type: '', prop: 'productName', label: '产品名称', showOverflowTooltip: true },
    { visible: true, align: 'center', type: '', prop: 'batchNo', label: '原材料批次号', showOverflowTooltip: true },
    { visible: true, align: 'center', type: 'dict', prop: 'scrapType', label: '不良品类型', showOverflowTooltip: true },
    { visible: true, align: 'center', type: '', prop: 'scrapReason', label: '不良品原因', showOverflowTooltip: true },
    { visible: true, align: 'center', type: '', prop: 'scrapQuantity', label: '不良品数量' },
    { visible: true, align: 'center', type: '', prop: 'unit', label: '单位', showOverflowTooltip: true },
    { visible: true, align: 'center', type: 'dict', prop: 'status', label: '状态', showOverflowTooltip: true },
    { visible: true, align: 'center', type: '', prop: 'lineCode', label: '线别', showOverflowTooltip: true },
    { visible: true, align: 'center', type: '', prop: 'workStation', label: '工位', showOverflowTooltip: true },
    { visible: true, align: 'center', type: '', prop: 'operator', label: '操作员', showOverflowTooltip: true },
    { visible: true, align: 'center', type: '', prop: 'qualityInspector', label: '质检员', showOverflowTooltip: true },
    { visible: true, align: 'center', type: '', prop: 'supervisorName', label: '审核人', showOverflowTooltip: true },
    { visible: true, align: 'center', type: '', prop: 'disposalMethod', label: '处置方式', showOverflowTooltip: true },
    { visible: true, align: 'center', type: '', prop: 'scrapDate', label: '不良品日期', showOverflowTooltip: true },
    { visible: true, align: 'center', type: '', prop: 'approvalDate', label: '审批日期', showOverflowTooltip: true },
    { visible: true, align: 'center', type: '', prop: 'remark', label: '备注', showOverflowTooltip: true },
    { visible: true, align: 'center', type: '', prop: 'createdTime', label: '创建时间', showOverflowTooltip: true },
    // 以下为隐藏的技术字段
    { visible: false, align: 'center', type: '', prop: 'stoveCode', label: '炉号', showOverflowTooltip: true },
    { visible: false, align: 'center', type: '', prop: 'locationCode', label: '库存编号', showOverflowTooltip: true },
    { visible: false, align: 'center', type: '', prop: 'costImpact', label: '成本影响金额' },
    { visible: false, align: 'center', type: '', prop: 'updatedTime', label: '更新时间', showOverflowTooltip: true },
    { visible: false, align: 'center', type: '', prop: 'version', label: '版本号' },
    { visible: false, align: 'center', type: '', prop: 'tenantId', label: '租户ID' },
    { visible: false, align: 'center', type: '', prop: 'updatedBy', label: '更新人ID' },
    { visible: false, align: 'center', type: '', prop: 'createdBy', label: '创建人ID' },
    { visible: false, align: 'center', type: '', prop: 'id', label: '主键ID' }
    //{ visible: false, prop: 'actions', label: '操作', type: 'slot', width: '160' }
])
const total = ref(0)
const dataList = ref([])
const queryRef = ref()
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])

var dictParams = []

function getList() {
    loading.value = true
    listQcScrapRecords(queryParams)
        .then((res) => {
            const { code, data } = res
            if (code === 200) {
                dataList.value = data.result
                total.value = data.totalNum
            }
            loading.value = false
        })
        .catch(() => {
            loading.value = false
        })
}

// 查询
function handleQuery() {
    queryParams.pageNum = 1
    getList()
}

// 重置查询操作
function resetQuery() {
    proxy.resetForm('queryRef')
    selectedMaterial.value = null
    handleQuery()
}
// 处理排序
function sortChange(column) {
    let sort = undefined
    let sortType = undefined

    if (column.prop !== null && column.order !== null) {
        sort = column.prop
        sortType = column.order
    }
    queryParams.sort = sort
    queryParams.sortType = sortType
    handleQuery()
}

// 获取物料列表
function getMaterialCodeList() {
    try {
        getMaterialOption('materialCode').then((res) => {
            const { code, data } = res
            if (code === 200) {
                options.value.materialOptions = data
            }
        })
    } catch (error) {
        proxy.$modal.msgError(error.message)
    }
}

// 物料选择器改变事件
function handleSearchMaterialChange(val) {
    if (val) {
        queryParams.materialCode = val.materialCode
    } else {
        queryParams.materialCode = ''
    }
}

// 处理物料选择改变（表单用）
function handleMaterialChange(val, formType) {
    if (!val) return

    if (formType === 'scrap') {
        scrapOrderForm.value.materialCode = val.materialCode
        scrapOrderForm.value.materialName = val.materialName
        scrapOrderForm.value.supplierName = val.supplierName || ''
    } else if (formType === 'transfer') {
        transferOrderForm.value.materialCode = val.materialCode
        transferOrderForm.value.materialName = val.materialName
        transferOrderForm.value.supplierName = val.supplierName || ''
    }
}

/*************** form操作 ***************/
const formRef = ref()
const scrapOrderFormRef = ref()
const transferOrderFormRef = ref()
const approveFormRef = ref()
const title = ref('')
// 操作类型：1=add, 2=edit, 3=view
const operType = ref(0)
const open = ref(false)

// 新增对话框状态
const scrapOrderOpen = ref(false)
const transferOrderOpen = ref(false)
const approveOpen = ref(false)

// 选中的记录ID
const selectedId = ref(null)

const state = reactive({
    single: true,
    multiple: true,
    form: {},
    scrapOrderForm: {},
    transferOrderForm: {},
    approveForm: {
        isApproved: true,
        approver: ''
    },
    rules: {
        updatedTime: [{ required: true, message: '更新时间不能为空', trigger: 'blur' }],
        createdTime: [{ required: true, message: '创建时间不能为空', trigger: 'blur' }],
        createdBy: [{ required: true, message: '创建人ID不能为空', trigger: 'blur', type: 'number' }],
        scrapDate: [{ required: true, message: '不良品日期不能为空', trigger: 'blur' }],
        scrapQuantity: [{ required: true, message: '不良品数量不能为空', trigger: 'blur' }],
        scrapOrderNo: [{ required: true, message: '不良品单号不能为空', trigger: 'blur' }]
    },
    scrapOrderRules: {
        materialCode: [{ required: true, message: '物料编码不能为空', trigger: 'blur' }],
        scrapReason: [{ required: true, message: '不良品原因不能为空', trigger: 'blur' }],
        scrapQuantity: [{ required: true, message: '不良品数量不能为空', trigger: 'blur' }],
        batchNo: [{ required: true, message: '原材料批次号不能为空', trigger: 'blur' }],
        disposalMethod: [{ required: true, message: '处置方式不能为空', trigger: 'blur' }],
        operator: [{ required: true, message: '操作员不能为空', trigger: 'blur' }],
        qualityInspector: [{ required: true, message: '质检员不能为空', trigger: 'blur' }],
        scrapDate: [{ required: true, message: '报废日期不能为空', trigger: 'blur' }]
    },
    transferOrderRules: {
        materialCode: [{ required: true, message: '物料编码不能为空', trigger: 'blur' }],
        workorder: [{ required: true, message: '工单号不能为空', trigger: 'blur' }],
        scrapReason: [{ required: true, message: '不良品原因不能为空', trigger: 'blur' }],
        scrapQuantity: [{ required: true, message: '不良品数量不能为空', trigger: 'blur' }],
        disposalMethod: [{ required: true, message: '处置方式不能为空', trigger: 'blur' }],
        operator: [{ required: true, message: '操作员不能为空', trigger: 'blur' }],
        qualityInspector: [{ required: true, message: '质检员不能为空', trigger: 'blur' }],
        scrapDate: [{ required: true, message: '报废日期不能为空', trigger: 'blur' }]
    },
    approveRules: {
        isApproved: [{ required: true, message: '请选择是否批准', trigger: 'change' }],
        approver: [{ required: true, message: '审批人不能为空', trigger: 'blur' }]
    },
    options: {
        // 状态:草稿,待审批,已批准,已拒绝 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
        statusOptions: [
            { dictLabel: '草稿', dictValue: '草稿' },
            { dictLabel: '待审批', dictValue: '待审批' },
            { dictLabel: '已批准', dictValue: '已批准' },
            { dictLabel: '已拒绝', dictValue: '已拒绝' }
        ],
        // 不良品类型选项列表
        scrapTypeOptions: [
            { dictLabel: '报废', dictValue: '报废' },
            { dictLabel: '转用', dictValue: '转用' },
            { dictLabel: '退货', dictValue: '退货' },
            { dictLabel: '其他', dictValue: '其他' }
        ],
        // 线别选项列表
        lineCodeOptions: [],
        // 物料选项列表
        materialOptions: []
    }
})

const { form, rules, scrapOrderForm, scrapOrderRules, transferOrderForm, transferOrderRules, approveForm, approveRules, options, single, multiple } =
    toRefs(state)

// 关闭dialog
function cancel() {
    open.value = false
    reset()
}

// 重置表单
function reset() {
    form.value = {
        workStation: null,
        version: null,
        tenantId: null,
        updatedTime: null,
        updatedBy: null,
        createdTime: null,
        createdBy: null,
        remark: null,
        locationCode: null,
        costImpact: null,
        qualityInspector: null,
        status: null,
        approvalDate: null,
        scrapDate: null,
        supervisorName: null,
        operator: null,
        id: null,
        disposalMethod: null,
        scrapType: null,
        scrapReason: null,
        unit: null,
        scrapQuantity: null,
        batchNo: null,
        materialName: null,
        materialCode: null,
        productName: null,
        productCode: null,
        stoveCode: null,
        lineCode: null,
        workorder: null,
        scrapOrderNo: null
    }
    proxy.resetForm('formRef')
}

// 重置报废单表单
function resetScrapOrderForm() {
    scrapOrderForm.value = {
        materialCode: null,
        materialName: null,
        batchNo: null,
        scrapQuantity: null,
        scrapType: '报废',
        scrapReason: null,
        disposalMethod: null,
        operator: null,
        qualityInspector: null,
        scrapDate: null,
        remark: null
    }
    selectedScrapMaterial.value = null
    proxy.resetForm('scrapOrderFormRef')
}

// 重置转用单表单
function resetTransferOrderForm() {
    transferOrderForm.value = {
        materialCode: null,
        materialName: null,
        workorder: null,
        scrapQuantity: null,
        scrapType: '转用',
        scrapReason: null,
        disposalMethod: null,
        operator: null,
        qualityInspector: null,
        scrapDate: null,
        remark: null
    }
    selectedTransferMaterial.value = null
    proxy.resetForm('transferOrderFormRef')
}

// 重置审批表单
function resetApproveForm() {
    approveForm.value = {
        isApproved: true,
        approver: '',
        remark: null
    }
    proxy.resetForm('approveFormRef')
}

// 添加按钮操作
function handleAdd() {
    reset()
    open.value = true
    title.value = '添加不良品记录表'
    operType.value = 1
}
// 修改按钮操作
function handleUpdate(row) {
    reset()
    const id = row.id || ids.value
    getQcScrapRecords(id).then((res) => {
        const { code, data } = res
        if (code == 200) {
            open.value = true
            title.value = '修改不良品记录表'
            operType.value = 2

            form.value = {
                ...data
            }
        }
    })
}

// 提交表单
function submitForm() {
    proxy.$refs['formRef'].validate((valid) => {
        if (valid) {
            const request = form.value.id !== undefined && operType.value === 2 ? updateQcScrapRecords(form.value) : addQcScrapRecords(form.value)

            request.then((res) => {
                if (res.code === 200) {
                    proxy.$modal.msgSuccess(operType.value === 2 ? '修改成功' : '新增成功')
                    open.value = false
                    getList()
                }
            })
        }
    })
}

// 处理删除
function handleDelete(row) {
    const idsToDelete = row.id || ids.value

    if (!idsToDelete) {
        proxy.$modal.msgWarning('请选择要删除的记录')
        return
    }

    proxy
        .$confirm(`是否确认删除参数编号为"${idsToDelete}"的数据项？`, '警告', {
            confirmButtonText: proxy.$t('common.ok'),
            cancelButtonText: proxy.$t('common.cancel'),
            type: 'warning'
        })
        .then(() => {
            return delQcScrapRecords(idsToDelete)
        })
        .then(() => {
            getList()
            proxy.$modal.msgSuccess('删除成功')
        })
}

// 打开创建报废单对话框
function handleCreateScrapOrder() {
    resetScrapOrderForm()
    scrapOrderOpen.value = true
}

// 关闭创建报废单对话框
function cancelScrapOrder() {
    scrapOrderOpen.value = false
    resetScrapOrderForm()
}

// 提交报废单
function submitScrapOrder() {
    proxy.$refs['scrapOrderFormRef'].validate((valid) => {
        if (valid) {
            createScrapOrder(scrapOrderForm.value).then((res) => {
                if (res.code === 200) {
                    proxy.$modal.msgSuccess('创建报废单成功')
                    scrapOrderOpen.value = false
                    getList()
                }
            })
        }
    })
}

// 打开创建转用单对话框
function handleCreateTransferOrder() {
    resetTransferOrderForm()
    transferOrderOpen.value = true
}

// 关闭创建转用单对话框
function cancelTransferOrder() {
    transferOrderOpen.value = false
    resetTransferOrderForm()
}

// 提交转用单
function submitTransferOrder() {
    proxy.$refs['transferOrderFormRef'].validate((valid) => {
        if (valid) {
            createTransferOrder(transferOrderForm.value).then((res) => {
                if (res.code === 200) {
                    proxy.$modal.msgSuccess('创建转用单成功')
                    transferOrderOpen.value = false
                    getList()
                }
            })
        }
    })
}

// 打开审批报废记录对话框
function handleApprove(row) {
    selectedId.value = row?.id || ids.value
    if (!selectedId.value) {
        proxy.$modal.msgWarning('请选择要审批的记录')
        return
    }
    resetApproveForm()
    approveOpen.value = true
}

// 关闭审批报废记录对话框
function cancelApprove() {
    approveOpen.value = false
    resetApproveForm()
    selectedId.value = null
}

// 提交审批
function submitApprove() {
    proxy.$refs['approveFormRef'].validate((valid) => {
        if (valid) {
            approveScrapRecord(selectedId.value, approveForm.value).then((res) => {
                if (res.code === 200) {
                    proxy.$modal.msgSuccess('审批成功')
                    approveOpen.value = false
                    getList()
                    selectedId.value = null
                }
            })
        }
    })
}

// 处理撤销
function handleRevoke(row) {
    const id = row?.id || ids.value
    if (!id) {
        proxy.$modal.msgWarning('请选择要撤销的记录')
        return
    }

    proxy
        .$confirm('是否确认撤销该报废记录？', '警告', {
            confirmButtonText: proxy.$t('common.ok'),
            cancelButtonText: proxy.$t('common.cancel'),
            type: 'warning'
        })
        .then(() => {
            return revokeScrapRecord(id)
        })
        .then(() => {
            getList()
            proxy.$modal.msgSuccess('撤销成功')
        })
}

handleQuery()
getMaterialCodeList()
</script>
