<template>
    <div>
        <avue-crud :option="option" :table-loading="loading" :data="data" v-model="form" v-model:page="page" 
            v-model:search="searchParams" ref="crud"
            @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset"
            @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
            @refresh-change="refreshChange" @sort-change="sortChange">
            <!-- @on-load="onLoad" -->
            <template #menu-left>
                <el-form ref="form" :model="form" label-width="100px" :inline="true">
                    <el-form-item label="现执行价格:">
                        <el-input v-model="form.price"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="settlementFn">预结算</el-button>
                        <el-button type="primary" @click="settlementFnNum">结算</el-button>
                        <el-button type="danger" @click="onSubmit">无需结算</el-button>
                    </el-form-item>
                </el-form>
            </template>
            <template #menu-right>
                <el-button type="primary" @click="handleSupplement">补充结算</el-button>
            </template>
            <template #menu></template>
        </avue-crud>
        <!-- 预结算弹窗 -->
        <el-dialog title="预结算" append-to-body :modelValue="openSettle" width="30%">
            <el-form :model="settleForm" :rules="settleRules" ref="settleForm">
                <el-form-item label="镀后入库时间" prop="putStoreTime">
                    <el-date-picker
                        v-model="settleForm.putStoreTime"
                        type="daterange"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="结算数据状态" prop="settleStatus">
                    <el-checkbox-group v-model="settleForm.settleStatus">
                        <el-checkbox label="未结算" value="1"></el-checkbox>
                        <el-checkbox label="结算异常" value="2"></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="openSettle = false">取消</el-button>
                    <el-button type="primary" @click="summitSettle">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 补充结算弹窗 -->
        <el-dialog title="预结算" append-to-body :modelValue="openSupplement" width="30%">
            <el-form :model="supplementForm" :rules="supplementRules" ref="supplementForm" label-width="100px">
                <el-form-item label="镀后入库时间" prop="putStoreTime">
                    <el-date-picker
                        v-model="supplementForm.putStoreTime"
                        type="daterange"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="工序" prop="ppsId">
                    <jhSelect
                        :value="supplementForm.ppsId"
                        @input="val => (supplementForm.ppsId = val)"
                        placeholder="请搜索选择"
                        api-url="/api/blade-desk/mesOemProcess/page"
                        echo-api="/api/blade-desk/mesOemProcess/page"
                        echoParamsKey="ids"
                        echo-method="get"
                        api-method="get"
                        list-key="records"
                        total-key="total"
                        label-key="paName"
                        value-key="id"
                        search-key="paName"
                        :debounce-time="200"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="openSupplement = false">取消</el-button>
                    <el-button type="primary" @click="summitSupplement">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <settlementDailog v-if="isOpen" :showDialog="isOpen" :type="settlementType" :statementList="selectionList" :settleResult="settleResult" @closeDialog="closeDialog" @refresh="refreshTable"></settlementDailog>
    </div>
</template>
<script>
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { downloadXls } from '@/utils/util';
import settlementDailog from './SettlementDailog.vue'
import {getStatement,noSettlementItem,calculate,preSettlement,supplement} from "@/api/outsourcingManagement/oemOrderSettlement"
export default {
    components: {
        settlementDailog
    },
    data() {
        return {
            selectionList: [],
            data:[],
            loading:false,
            query:{},
            searchParams:{
                rosStatusList:1,
            },
            option: {
                height: 'auto',
                calcHeight: 32,
                tip: false,
                simplePage: true,
                searchShow: true,
                searchMenuSpan: 6,
                searchIcon: true,
                searchIndex: 3,
                tree: false,
                border: true,
                index: false,
                selection: true,
                rowKey: 'wpId',
                editBtn: false,
                viewBtn: false,
                delBtn: false,
                addBtn: false,
                editBtnText: '修改',
                viewBtnIcon: ' ',
                delBtnIcon: ' ',
                editBtnIcon: ' ',
                viewBtnText: '详情',
                labelWidth: 120,
                searchLabelWidth:90,
                menuWidth: 180,
                dialogWidth: 640,
                dialogClickModal: false,
                searchEnter: true,
                excelBtn: true,
                filterBtn: true,
                searchShowBtn: false,
                columnSort: true,
                showOverflowTooltip: true,
                menu: false,
                searchLabelPosition: 'left',
                searchGutter: 24,
                searchSpan: 6,
                menuAlign: 'left',
                gridBtn: false,
                searchMenuPosition: 'right',
                addBtnIcon: ' ',
                viewBtnIcon: ' ',
                delBtnIcon: ' ',
                editBtnIcon: ' ',
                align: 'center',
                column: [
                    {
                        // label: '外协单号',
                        label: '计划单号',
                        prop: 'ypCode',
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: true,
                        width: 120,
                        searchOrder:3,
                    },
                    {
                        label: '车间订单单号',
                        prop: 'woCode',
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: true,
                        width: 140,
                        searchOrder:2,
                    },
                    {
                        label: '零件号',
                        prop: 'partCode',
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: true,
                        width: 120,
                        searchOrder:7,
                    },
                    {
                        label: '零件名称',
                        prop: 'partName',
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: false,
                        width: 120,
                    },
                    {
                        label: '批次号',
                        prop: 'batchNo',
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: false,
                        width: 120,
                    },
                    {
                        label: '质量等级',
                        prop: 'productIdent',
                        // sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: true,
                        width: 120,
                        type:'select',
                        searchOrder:5,
                        dicUrl:"/api/blade-scheduling/qualityGrade/getGrades",
                        props:{
                            label:'qualityGrade',
                            value:"id"
                        }
                    },
                    {
                        label:"流程卡号",
                        prop:"cardNo",
                        // sortable: 'custom',
                        span:24,
                        search:true,
                        width: 120,
                        searchOrder:1,
                    },
                    {
                        label: '工序',
                        prop: 'ppsId',
                        // sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: true,
                        width: 120,
                        type:'select',
                        dicUrl:"/api/blade-desk/mesOemProcess/page?current=1&&size=99999",
                        props:{
                            label: 'paName',
                            value: 'oemProcessCode',
                            res: 'data.records',
                        },
                        searchOrder:9,

                    },
                    {
                        label: '工艺能力',
                        prop: 'caId',
                        type:"select",
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: true,
                        width: 120,
                        dicUrl:"/api/blade-desk/BA/craftAbility/findList",
                        props:{
                            label:"caName",
                            value:"id"
                        },
                        searchOrder:8,
                    },
                    {
                        label: '厂家代码',
                        prop: 'ocCode',
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: false,
                        width: 120,
                    },
                    {
                        label: '厂家名称',
                        prop: 'ocName',
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: false,
                        width: 120,
                    },
                    {
                        label: '结算数量',
                        prop: 'makeQty',
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: false,
                        width: 120,
                    },
                    {
                        label: '单位面积(d㎡)',
                        prop: 'ypArea',
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: false,
                        width: 140,

                    },
                    {
                        label: '总面积(d㎡)',
                        prop: 'totalArea',
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: false,
                        width: 140,

                    },
                    {
                        label: '镀种',
                        prop: 'plate',
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: true,
                        width: 120,
                        searchOrder:6,
                    },
                    {
                        label: '镀层厚度',
                        prop: 'plateThickness',
                        // sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: false,
                        width: 120,

                    },
                    {
                        label: '工序标准代码',
                        prop: 'standardProcessCode',
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: false,
                        width: 120,

                    },
                    {
                        label: '涂色标个数',
                        prop: 'tsbNum',
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: false,
                        width: 120,

                    },
                    {
                        label: '涂色带个数',
                        prop: 'tsdNum',
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: false,
                        width: 120,

                    },
                    {
                        label: '涂箭头个数',
                        prop: 'tjtNum',
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: false,
                        width: 120,

                    },
                    {
                        label: '计划部门编号',
                        prop: 'planDeptcode',
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: false,
                        width: 120,
                    },
                    {
                        label: '使用部门编号',
                        prop: 'useDeptCode',
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: false,
                        width: 120,
                    },
                    {
                        label: '镀后入库时间',
                        prop: 'putStoreTime',
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: true,
                        width: 140,
                        type: "date",
                        searchRange: true,
                        format: 'YYYY-MM-DD',
                        valueFormat: 'YYYY-MM-DD',
                        startPlaceholder: '开始时间',
                        endPlaceholder: '结束时间',
                        searchOrder:11,
                    },
                    {
                        label: '结算状态',
                        prop: 'rosStatusName',
                        // sortable: 'custom',
                        filter: true,
                        span: 24,
                        search: false,
                        width: 120,
                    },
                    // {
                    //     label: '生产数量',
                    //     prop: 'makeQty',
                    //     sortable: 'custom',
                    //     filter: true,
                    //     span: 24,
                    //     search: false,
                    //     width: 120,

                    // },
                    {
                        label: '结算状态',
                        prop: 'rosStatusList',
                        sortable: true,
                        filter: true,
                        span: 24,
                        hide: true,
                        search: true,
                        width: 120,
                        type:'select',
                        searchOrder:10,
                        clearable:false,
                        dicData:[
                            // 未结算：1，待确认：2，结算异常：3，结算完成：4，待审核：5，审核中：6，待推送：7
                            {
                                label:'未结算',
                                value:1
                            }
                        ]
                    },
                    
                    {
                        label: '外协厂商',
                        prop: 'ocIds',
                        sortable: 'custom',
                        filter: true,
                        span: 24,
                        hide: true,
                        search: true,
                        width: 120,
                        type:'select',
                        searchOrder:10,
                        dicUrl:"/api/blade-desk/BA/Oem/listForSelect",
                        props:{
                            label:'ocName',
                            value:"id"
                        }
                    },
                    
                    

                ]
            },
            form: {
                name: '',
            },
            page: {
                pageSize: 10,
                currentPage: 1,
                total: 0,
            },
            isOpen: false,
            settleResult: null,
            openSettle:false,
            openSupplement:false,
            supplementForm:{},
            supplementRules:{
                putStoreTime:[{required: true, message: '请选择镀后入库时间', trigger: 'change'}],
                ppsId:[{required: true, message: '请选择工序', trigger: ['change','blur']}]
            },
            settleForm:{},
            settleRules:{
                settleStatus:[{required: true, message: '请选择结算状态', trigger: 'change'}]
            }
        }
    },
    methods: {
        // 表格排序
        sortChange({ prop, order }) {
            console.log('prop----------',prop)
            console.log('order----------',order)
            this.query.ascs = undefined;
            this.query.descs = undefined;
            const orderByFieldKey = order === 'ascending' ? 'ascs' : 'descs';
            const orderByField = prop.replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase();
            this.query[orderByFieldKey] = orderByField;
            // // 重新加载数据
            this.onLoad(this.page, this.query);
        },
        searchChange(params, done) {
            this.query = {
                ...params,
                rosStatusList:'1',
            };
            this.page.currentPage = 1;
            this.onLoad();
            done && done();
        },
        searchReset() {
            this.query = {
                rosStatusList:1,
            };
            this.searchParams = {
                rosStatusList:1,
            }
            this.onLoad();
        },
        currentChange(currentPage) {
            this.page.currentPage = currentPage;
            this.onLoad();
        },
        sizeChange(pageSize) {
            this.page.pageSize = pageSize;
            this.onLoad();
        },
        refreshChange() {
            this.onLoad();
        },
        //结算
        settlementFnNum() {
            // if (this.selectionList.length === 0) {
            //     this.$message.error('请选择至少一条数据');
            //     return;
            // }
            // if (!this.form.price) {
            //     this.$message.error('请输入现执行价格');
            //     return;
            // }

            if(this.data.length == 0){
                this.$message.error('请先查询数据！');
                return;
            }

            this.$confirm('确定要进行结算吗?', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                // 调用结算接口
                const params = {
                    ...this.query,
                    price: this.form && this.form.price,
                    postPlatingStorageTimeStart:this.query && this.query.putStoreTime && this.query.putStoreTime.length != 0 && this.query.putStoreTime[0],
                    postPlatingStorageTimeEnd:this.query && this.query.putStoreTime && this.query.putStoreTime.length != 0 && this.query.putStoreTime[1],
                };
                if(params.putStoreTime) delete params.putStoreTime;
                console.log('params',params)

                calculate(params).then(res => { 
                    if(res.data.code == 200){
                        this.$message.success('结算成功');
                        this.onLoad();
                    }
                }).catch(() => {
                    // this.$message.error('结算失败');
                });

                // oemSettleAccountsItem(params).then(res => {
                //     // 获取返回的数据
                //     if (res.data && res.data.data) {
                //         this.settleResult = res.data.data;
                //         // 打开settlementDailog并显示结果
                //         this.isOpen = true;
                //     } else {
                //         this.$message.success('结算成功');
                //         this.onLoad();
                //     }
                // }).catch(() => {
                //     this.$message.error('结算失败');
                // });
            }).catch(() => {
                // 用户点击取消
            });
        },
        //预结算
        settlementFn() {
            this.settleForm = {}
            this.openSettle = true

            // if (this.selectionList.length === 0) {
            //     this.$message.error('请选择至少一条数据');
            //     return;
            // }
            // if (!this.form.price) {
            //     this.$message.error('请输入现执行价格');
            //     return;
            // }

            // this.$confirm('确定要进行预结算吗?', {
            //     confirmButtonText: '确定',
            //     cancelButtonText: '取消',
            //     type: 'error',
            // }).then(() => {
            //     // 调用预结算接口
            //     const params = {
            //         statementList: this.selectionList,
            //         price: this.form.price
            //     };

            //     preSettlementItem(params).then(() => {
            //         this.$message.success('预结算成功');
            //         this.onLoad();
            //     }).catch(() => {
            //         this.$message.error('预结算失败');
            //     });
            // }).catch(() => {
            //     // 用户点击取消
            // });
        },
        // 确定预结算
        summitSettle(){
            this.$refs.settleForm.validate(valid =>{
                if(valid){
                    console.log('settleForm----------',this.settleForm)
                    let params = {
                        postPlatingStorageTimeStart:this.settleForm && this.settleForm.putStoreTime && this.settleForm.putStoreTime[0],
                        postPlatingStorageTimeEnd:this.settleForm && this.settleForm.putStoreTime && this.settleForm.putStoreTime[1],
                        rosStatusList:this.settleForm.settleStatus.join(','),
                    }
                    console.log('params----------',params)
                    preSettlement(params).then(res =>{
                        console.log('res----------',res)
                        if(res.data){
                            this.$message.success('预结算成功')
                            this.openSettle = false
                            NProgress.start();
                            downloadXls(res.data, `预结算数据表${this.$dayjs().format('YYYY-MM-DD')}.xlsx`);
                            NProgress.done();
                        }
                    })
                }
            })
        },
        
        closeDialog() {
            this.isOpen = false;
        },
        refreshTable() {
            this.onLoad();
        },
        // 补充结算
        handleSupplement(){
            this.supplementForm = {}
            this.openSupplement = true
        },
        // 确定补充结算
        summitSupplement(){
            this.$refs.supplementForm.validate(valid =>{
                if(valid){
                    let params = {
                        ...this.supplementForm,
                        postPlatingStorageTimeStart:this.supplementForm && this.supplementForm.putStoreTime && this.supplementForm.putStoreTime[0],
                        postPlatingStorageTimeEnd:this.supplementForm && this.supplementForm.putStoreTime && this.supplementForm.putStoreTime[1],
                    }
                    if(params.putStoreTime) delete params.putStoreTime;
                        console.log('params----------',params)
                        supplement(params).then(res =>{
                            if(res.data.code == 200){
                                this.$message.success('补充结算成功');
                                this.openSupplement = false
                                this.onLoad()
                            }
                        })
                    }
            })
        },
        onSubmit() {
            // if (this.selectionList.length === 0) {
            //     this.$message.warning('请选择至少一条数据');
            //     return;
            // }
            if(this.data.length == 0){
                this.$message.error('请先查询数据！')
                return
            }
            this.$confirm('确认页面所有数据无需结算？', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                let params = {
                    ...this.query,
                    postPlatingStorageTimeStart:this.query && this.query.putStoreTime && this.query.putStoreTime[0],
                    postPlatingStorageTimeEnd:this.query && this.query.putStoreTime && this.query.putStoreTime[1],
                }
                if(params.putStoreTime) delete params.putStoreTime;
                console.log('params----------',params)
                noSettlementItem(params).then(() => {
                    this.$message.success('无需结算成功');
                    this.onLoad();
                }).catch(() => {
                    // this.$message.error('无需结算失败');
                });
            }).catch(() => {
                // 用户点击取消
            });
        },
        handleDelete() {
            if (this.selectionList.length === 0) {
                this.$message.warning('请选择至少一条数据');
                return;
            }
            this.$confirm('确定将选择数据删除?', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
            })
        },
        // 多选
        selectionChange(list) {
            console.log('selectionChange 被调用，选中的数据:', list);
            console.log('当前表格数据:', this.data);
            this.selectionList = list;
        },
        onLoad() {
            this.loading = true
            // 清空选择状态
            this.selectionList = []
            if (this.$refs.crud) {
                this.$refs.crud.clearSelection()
            }
            let params = {
                current:this.page.currentPage,
                size:this.page.pageSize,
                ...this.query,
                postPlatingStorageTimeStart:this.query && this.query.putStoreTime && this.query.putStoreTime.length != 0 && this.query.putStoreTime[0],
                postPlatingStorageTimeEnd:this.query && this.query.putStoreTime && this.query.putStoreTime.length != 0 && this.query.putStoreTime[1],
            }
            if(params.putStoreTime) delete params.putStoreTime
            getStatement(params).then(res =>{
                this.data = res.data.data.records
                this.page.total = res.data.data.total
                this.loading = false
            })
            // this.data = [
            //     {
            //         "bsTeamSet": null,
            //         "bsWorkCenter": {
            //             "area": 13000.0,
            //             "batchNo": null,
            //             "bigBatch": false,
            //             "bsJfCenter": {
            //                 "createMan": {
            //                     "userId": 1,
            //                     "userName": "admin"
            //                 },
            //                 "createTime": "2024-12-09 00:00:00",
            //                 "deleted": false,
            //                 "jcCode": "RBZX",
            //                 "jcId": 1,
            //                 "jcName": "热表中心",
            //                 "keyValue": 1,
            //                 "updateTime": "2024-12-09 00:00:00"
            //             },
            //             "checkout": false,
            //             "craftAbility": "化学镀镍",
            //             "createMan": {
            //                 "userId": 1,
            //                 "userName": "admin"
            //             },
            //             "createTime": "2023-02-06 12:31:36",
            //             "deleted": false,
            //             "describe": null,
            //             "endPoint": null,
            //             "keyValue": 81,
            //             "leaderUser": {
            //                 "userId": 541,
            //                 "userName": "崔殿龙"
            //             },
            //             "limitType": 0,
            //             "processes": "上挂、下挂、交检、化学镀镍、喷砂",
            //             "quantity": null,
            //             "roundCycle": null,
            //             "saturation": 85.0,
            //             "sign": "4",
            //             "startPoint": null,
            //             "team": "化学镀镍一班崔胜伟、化学镀镍一班郭家梁",
            //             "updateTime": "2023-03-06 18:42:47",
            //             "wcCode": "001",
            //             "wcId": 81,
            //             "wcName": "化学镀镍作业中心",
            //             "whetherPlate": false
            //         },
            //         "createMan": {
            //             "userId": 1,
            //             "userName": "admin"
            //         },
            //         "createTime": "2025-04-09 11:27:09",
            //         "deEquipmentCard": {
            //             "bindQty": 4,
            //             "categorys": "产线设备",
            //             "deviceCode": "9652247",
            //             "deviceIp": "192.168.43.179",
            //             "deviceName": "化学镀镍",
            //             "docking": true,
            //             "ecId": 1,
            //             "keyValue": 1,
            //             "macCode": "9652247",
            //             "macSpec": null,
            //             "memo": null,
            //             "rfId": "SYM-HCP-L4",
            //             "status": true,
            //             "typeName": "9652247",
            //             "updateTime": null,
            //             "used": 1,
            //             "usedText": "正常服役",
            //             "virtualMac": false
            //         },
            //         "keyValue": 121,
            //         "pureWater": 1.0,
            //         "quotaArea": 0.0,
            //         "tapWater": 1.0,
            //         "updateTime": "2025-04-09 11:27:09",
            //         "uqDate": "2025-04-09",
            //         "uqId": 121,
            //         "uqType": 0,
            //         "useElectric": 0.0,
            //         "workCenterId": "[81]",
            //         "workCenterName": "[\"化学镀镍作业中心\"]",
            //         "workCenterNames": "化学镀镍作业中心"
            //     }
            // ]
            // this.page.total = this.data.length
            // this.loading = false
            // setTimeout(() => {
            //     this.selectionClear()
            // }, 500)
        }
    }
}
</script>
<style lang="scss" scoped></style>