<template>

    <div>
        <div class="col userInp " style="display: flex; align-items: center;">
            <div class="label lable150 rx-cc" style="width: 100px !important;">规格选择：</div>
            <el-select v-model="Usertype" placeholder="请选择" @change="changeUserType">
                <el-option v-for="item in localdataList" :key="item.value" :label="item.text" :value="item.value">
                </el-option>
            </el-select>
            <!-- multiple -->
            <!-- <zxz-uni-data-select :localdata="localdataList" v-model="Usertype"
				@change="changeUserType"></zxz-uni-data-select> -->
        </div>
        <div v-for="(item, i) in DispositionList" :key="i">
            <div class="title_box rx-bc mt6">
                <div class="name">{{ item.titel }}</div>

                <div class="rx-bc"> </div>
            </div>

            <div>
                <div class="material ">

                    <div class="content_table">
                        <div class="item">
                            <div class="lable rx-cc">包装总数 </div>
                            <div class="content content_num">
                                <el-input class="uni-el-input" v-model="formedNumLast" type="number"
                                   v-if="i == 0"  @input="changeinput" style="width: 200px;"></el-input>
                                <el-input class="uni-el-input" v-model="item.formedNumLast" type="number"
                                   v-else disabled  style="width: 200px;"></el-input>
                                <div class="unit">{{ item.packageUnit }}</div>

                            </div>
                        </div>

                        <div class="item rx-sc">
                            <div class="rx ww55 ">
                                <div class="lable lable200 rx-cc ">{{ item.titel }}单元</div>
                                <div class="content content_num">
                                    <el-input class="uni-el-input" v-model="item.packageCell" disabled
                                        style="width: 200px;"></el-input>
                                    <div class="unit">{{ item.packageUnit }}</div>/<div class="unit">{{
                                        item.conversionUnit }}</div>
                                </div>
                            </div>

                        </div>

                    </div>

                    <div class="content_table2" v-if='item.splitList.length'>
                        <el-table :data="item.splitList" style="width: 100%">
                            <el-table-column prop="computeSize" label="序号" width="65">
                                <template v-slot="{ row, $index }">
                                    {{ row.computeSize }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="name" label="数量">
                                <template v-slot="{ row, $index }">
                                    <div style="display: flex;align-items: center;">
                                        <el-input class="uni-el-input" v-model="row.quantity" disabled type="digit"
                                            style="width: 200px;"></el-input>
                                        <div style="width: 260rpx; font-size: 22rpx;"> {{ row.unit }}/{{
                                            row.packageUnit }}
                                        </div>
                                    </div>

                                </template>
                            </el-table-column>
                            <el-table-column prop="totalQuantity" label="计量数" width="100">
                            </el-table-column>
                            <el-table-column prop="code" label="条码">
                            </el-table-column>
                        </el-table>


                    </div>



                </div>
            </div>

            <!-- <SearchPopup mode="center" v-if='show'>
			<template v-slot:list>
				<div class="search_list">

					<u-form labelPosition="left" :model="formData" labelWidth="180" labelAlign="left" class="baseForm">

						<u-form-item label="外包装数:" class="required-form" borderBottom prop="assetType">
							<el-input class="uni-el-input" v-model="formData.wPackNum" style="width: 280rpx;"
								placeholder="外包装数"></el-input> / {{ splitList[0].unit }}
						</u-form-item>

					</u-form>

				</div>
			</template>

<template v-slot:operate>
				<div class="operate_box rx-bc">
					<u-button size="small" class="u-reset-button" @click="calculationClose()">
						取消
					</u-button>

					<u-button type="success" size="small" class="u-reset-button" @click="calculationReset()">
						重置
					</u-button>


					<u-button type="success" size="small" class="u-reset-button" @click="calculationSave()">
						确定
					</u-button>

				</div>
			</template>

</SearchPopup> -->
        </div>
    </div>
</template>

<script>
import {
    packageDisposition,
    packingReport
} from '@/api/produce/workOrder';

// import {
// 	getByCode
// } from '@/api/pda/common.js'
// import {
// 	cancelPacking,
// 	packingReport,
// 	getPackingReport,
// 	packingReportRepeat,
// 	packageDisposition,
// 	getPackingReportRepeat
// } from '@/api/pda/workOrder.js'
// import SearchPopup from '../../components/searchPopup.vue'
export default {
    // components: {
    // 	SearchPopup
    // },
    props: {
        objData: {
            type: Object,
            default: () => { }
        },

        taskId: {
            type: String,
            default: ''
        },

        workOrderId: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            formedNumLast: 100,

            quantity: '',
            unit: '',
            Usertype: "",// 规格
            unitList: [],
            resObj: {},
            splitList: [],
            localdataList: [],
            newDispositionList: [],
            withinQuantity: '',//内包装数量
            withinUnit: '',//内包装单位
            outsideQuantity: '',//外包装数量
            outsideUnit: '',//外包装单位
            timeout: null,
            packUnit: null,
            temporaryNum: 0,
            temporaryCount: 0,
            temporaryList: [],
            packTwoList: [],

            selectList: [],
            span: '',
            value: '',
            minimumPackage: [],// 最小包装
            withinPackage: [],// 内包装
            minimumUnit: '',
            outsidePackage: [], //外包装
            newCategoryId: '',
            DispositionList:[],
            show: false,
            formData: {
                wPackNum: null,
            },
            // clientEnvironmentId: uni.getStorageSync("userInfo") && uni.getStorageSync("userInfo").clientEnvironmentId,

        }
    },
    watch: {

        objData: {
            handler(newVal) {
                if (newVal.product && newVal.product.length) {

                    this.newCategoryId = newVal.product[0].categoryId;
                    this.formedNumLast = newVal.formedNumLast || newVal.product[0].feedQuantity;
                } else {
                    this.formedNumLast = 0;
                }
                console.log(newVal);

                console.log(this.newCategoryId,'5555555555');
                this.packageDispositionFn();
                
            },
            deep: true,
            immediate: true
        }
    },
    created() {
        // this.formedNumLast = this.objData.product[0].feedQuantity;

        // this.byCode();

        // this.packageDispositionFn();
        // this.getPackingDetails()
        // this.getPackingDetailsTwo()
    },

    methods: {


        // 输入数量变化
        changeinput(e) {

  
            clearTimeout(this.timeout)
            // 设置新的定时器
            this.timeout = setTimeout(() => {
                this.formedNumLast = e;
          
                this.initFn(this.selectList);
            }, 500) // 500毫秒后触发

        },

        changeUserType(e) {
            let list = this.localdataList.find(item => item.value === e)
            // this.text = e.text;
            // this.value = e.value;
            this.selectList = list.arr;
            this.initFn(list.arr);
        },
        groupBy(arr, key) {
            return arr.reduce((acc, obj) => {
                const groupKey = obj[key];
                if (!acc[groupKey]) {
                    acc[groupKey] = [];
                }
                console.log();
                acc[groupKey].push(obj);
                return acc;
            }, {});
        },

        async packageDispositionFn() {
            console.log();
            if(!this.newCategoryId) return;

            let that = this;
            const res = await packageDisposition(this.newCategoryId);

            console.log(res,'66666666666');

            if (res.length) {
                res.shift();
                let data = JSON.parse(JSON.stringify(res));
                let list = this.groupBy(data, 'code');
                this.localdataList = [];
                Object.entries(list).forEach(([key, value]) => {

                    let obj = {
                        text: value[0].name,
                        arr: value,
                        value: key
                    }
                    this.localdataList.push(obj);
                });

                this.Usertype = this.localdataList[0].value;
                this.text = this.localdataList[0].text;
                this.value = this.localdataList[0].value;
                res.map(v => {
                    v.splitList = [];
                })
                this.newDispositionList = res;
                this.selectList = res;

                this.initFn(this.localdataList[0].arr);
                // this.listFn(this.localdataList[0].arr);

            }

        },

        initFn(v) {
            if (v.length) {
                this.withinQuantity = v[1].packageCell;//内包装数量
                this.withinUnit = v[1].conversionUnit;//内包装单位
                this.outsideQuantity = v[2].packageCell;//外包装数量
                this.outsideUnit = v[2].conversionUnit;//外包装单位
                this.minimumUnit = v[0].conversionUnit;
            };
            this.handleSplit(v[0]);
        },

        async listFn(res) {

            let { minimumPackage, withinQuantity, outsidePackage, outsideQuantity, withinPackage } = res;
            let textList = ['最小包装', '内包装', '外包装'];
            let arr = [{ list: minimumPackage }, { list: withinPackage, num: withinQuantity }, { list: outsidePackage, num: outsideQuantity }];

            this.minimumPackage = minimumPackage;// 最小包装
            this.withinPackage = withinPackage;// 内包装
            this.outsidePackage = outsidePackage; //外包装

            this.newDispositionList.map((v, i) => {
                v.splitList = arr[i].list;
                v.titel = textList[i];
                if (i == 0) {
                    v.formedNumLast = this.formedNumLast;
                } else {
                    v.formedNumLast = arr[i].num;
                }
            })
            this.$nextTick(() => {
                this.$set(this, 'DispositionList', this.newDispositionList);
            })
        },


        sunNum(v, i) {
            let _this = this;
            this.$nextTick(() => {
                switch (i) {
                    case 0:
                        console.log(_this.formedNumLast);
                        return _this.formedNumLast;
                    case 1:
                        return v.splitList.length || 0
                    case 2:

                        return v.splitList.length || 0

                }
            })


        },

        byCode() {
            getByCode('packing_unit').then(res => {

                this.unitList = []

                res.forEach((obj, index) => {
                    for (let key in obj) {
                        if (obj.hasOwnProperty(key)) { // 确保key是对象自身的属性

                            this.unitList.push({
                                Key: `${key}`,
                                Value: ` ${obj[key]}`
                            })


                        }
                    }
                });

            })
        },


        getPackingDetails() {
            let param = {
                workOrderId: this.workOrderId,
                taskId: this.taskId,
                tier: 1
            }

            getPackingReport(param).then(res => {
                this.splitList = res.detailList
                this.formedNumLast = res.totalQuantity
                this.quantity = res.quantity
                this.unit = res.unit

            })
        },



        // 第一次调用
        handleSplit(v) {
            console.log(v, 99655);

            if (this.splitList.length) {
                this.$message.error('产品已分包');

                return false
            }

            if (!this.formedNumLast) {
                this.$message.error('包装总数数量不能为空');

                return false
            }

            if (!v.packageCell) {
                this.$message.error('内包装数量不能为空');

                return false
            }

            if (!v.packageUnit) {
                this.$message.error('包装单位不能为空');

                return false

            }
           
            let param = {
                workOrderId: this.workOrderId,//工单id
                taskId: this.taskId,
                tier: 1,
                totalQuantity: this.formedNumLast,//总数量
                quantity: v.packageCell,//数量
                unit: v.packageUnit,//单位
                minimumUnit: this.minimumUnit,//最小包装单位
                withinQuantity: this.withinQuantity,//内包装数量
                withinUnit: this.withinUnit,//内包装单位
                outsideQuantity: this.outsideQuantity,//外包装数量
                outsideUnit: this.outsideUnit,//外包装单位
                packageUnit: v.conversionUnit,

            }


            packingReport(param).then(res => {

                console.log(res,'111111111111');

                this.listFn(res);

            })




        },

        handleCheck(idx, it) {



            if (it.quantity <= 0) {
                uni.showToast({
                    icon: 'none',
                    title: '数量为空不能勾选'
                })

                return false
            }

            this.$set(this.splitList[idx], 'check', it.check ? 0 : 1)

            this.temporaryList = []


            this.temporaryList = this.splitList.filter(e => {
                return e.check == 1
            })
            this.temporaryNum = 0
            this.temporaryCount = 0
            if (this.temporaryList.length > 0) {
                this.temporaryList.forEach(e => {
                    this.temporaryNum = this.temporaryNum + 1
                    this.temporaryCount = this.temporaryCount + Number(e.quantity)
                })
            }


        },


        handclose(it) {
            this.splitList.forEach(f => {
                if (f.computeSize == it.computeSize) {
                    f.check = 0
                }
            })

            this.temporaryList = []


            this.temporaryList = this.splitList.filter(e => {
                return e.check == 1
            })
        },

        getPackingDetailsTwo(v) {
            console.log(v);
            let param = {
                totalQuantity: v.formedNumLast,
                quantity: v.packageCell,
                unit: v.conversionUnit,
                workOrderId: this.workOrderId,
                taskId: this.taskId,
                tier: 2,

            }

            getPackingReportRepeat(param).then(res => {
                resolve(res.detailList)
            })

        },

        handlePack(v, s) {
            let _arr = []
            _arr = s.map(m => {
                return {
                    ...m,
                    isChecked: 1
                }
            })
            console.log(_arr, '123');

            let param = {
                detailList: _arr,
                quantity: v.temporaryCount,
                totalQuantity: v.formedNumLast,
                unit: v.packageUnit,
                taskId: this.taskId,
                workOrderId: this.workOrderId,
                tier: 2
            }
            return new Promise((resolve, reject) => {
                packingReportRepeat(param).then(res => {
                    console.log(res);
                    // this.temporaryList = []
                    this.getPackingDetails()
                    // this.getPackingDetailsTwo()
                })
            })
        },


        scrolltolower() {

        },

        getData() {
            let _packingReportMarginList = []

            _packingReportMarginList = this.splitList.filter(e => {
                return !e.parentId
            })

            console.log(this.DispositionList);

            let packInfo = {
                // this.DispositionList[0]


                specText: this.span,
                specValue: this.value,
                minimumPackage: this.minimumPackage,// 最小包装
                minimumPackageCell: this.DispositionList[0].packageCell,// 最小包装
                minimumPackageUnit: this.DispositionList[0].packageUnit,// 最小包装单位
                minimumConversionUnit: this.DispositionList[0].conversionUnit,// 最小包装单位
                minimumFormedNumLast: this.DispositionList[0].formedNumLast,// 总包装数量


                withinPackage: this.withinPackage,// 内包装

                withinPackageCell: this.DispositionList[1].packageCell,// 最小包装名称
                withinPackageUnit: this.DispositionList[1].packageUnit,// 最小包装单位
                withinConversionUnit: this.DispositionList[1].conversionUnit,// 最小包装单位
                withinFormedNumLast: this.DispositionList[1].formedNumLast,// 总包装数量
                // packingReportList: this.packTwoList,
                // packingReportMarginList: _packingReportMarginList,
                outsidePackage: this.outsidePackage, //外包装
                outsidePackageCell: this.DispositionList[2].packageCell,// 最小包装名称
                outsidePackageUnit: this.DispositionList[2].packageUnit,// 最小包装单位
                outsideConversionUnit: this.DispositionList[2].conversionUnit,// 最小包装单位
                outsideFormedNumLast: this.DispositionList[2].formedNumLast,// 总包装数量
            }

            this.objData.packInfo = packInfo;
            this.objData.taskType = this.objData.currentTaskDiagram.type;

        },

        calculation() {
            this.show = true
        },

        calculationSave() {
            let count = this.splitList.filter(item => item.isChecked != 1).length;

            if (this.formData.wPackNum <= count && count != 0) {
                for (let i = 0; i < this.formData.wPackNum; i++) {
                    this.splitList[i].check = 1
                }
                this.handleCheck(0, 0)
                this.calculationClose()

            } else {
                if (count != 0) {
                    for (let i = 0; i < count; i++) {
                        this.splitList[i].check = 1
                    }
                    this.handleCheck(0, 0)
                    this.calculationClose()
                }
                uni.showToast({
                    icon: 'none',
                    title: '外包装数超出内包装条数'
                })


            }

        },

        calculationClose() {
            this.show = false
        },

        calculationReset() {

            this.formData.wPackNum = null
            this.splitList.forEach(f => {
                f.check = null
            })
            this.temporaryList = []
            this.show = false

        }
    },
}
</script>

<style lang="scss" scoped>
.userInp {
    border: 1px solid #e5e5e5;
    border-top: none;
    padding: 2px 0;
}

.lable150 {
    width: 200px;
}

.title_box {
    margin-top: 20rpx;

    .ww20 {
        width: 20%;
    }

    .name {
        font-size: 28rpx;
        font-style: normal;
        font-weight: 400;
        padding-left: 20rpx;

        position: relative;

    }
}


.material {
    margin-top: 10rpx;



    .content_table {
        width: 100%;

        .item {
            display: flex;


            .lable {
                width: 132rpx;
                span-align: center;
                background-color: #F7F9FA;
                font-size: 26rpx;
                flex-shrink: 0;
            }

            .lable220 {
                width: 220rpx !important;
                font-size: 24rpx;
            }

            .lable150 {
                width: 156rpx !important;
                font-size: 24rpx;
            }

            .ww80 {
                width: 80rpx;
            }

            .content {
                width: 518rpx;
                min-height: 64rpx;
                font-size: 28rpx;
                line-height: 28rpx;
                font-style: normal;
                font-weight: 400;
                // padding: 18rpx 8rpx;
                box-sizing: border-box;
                word-wrap: break-word;
                flex-grow: 1 !important;


                .unit {
                    padding: 0 4rpx;
                    font-size: 24rpx;
                    color: #404446;
                }



            }




        }



        .ww55 {
            width: 55%;
        }

        .ww45 {
            width: 45%;
        }


    }
}




.content_table2 {
    width: 100%;
    margin-top: 16rpx;
    padding: 10px 0;
    height: 200px;
    overflow-y: auto;

    .row {
        width: 100%;


        .item {

            color: #404446;
            font-size: 28rpx;
            padding-left: 12rpx;

        }

        .ww30 {
            width: 30%;
        }

        .ww50 {
            width: 50%;

        }

        .ww90 {
            width: 90%;
        }

        .ww15 {
            width: 15%;
        }

        .ww10 {
            width: 10%;
        }

        .ww30 {
            width: 30%;
        }

        .ww20 {
            width: 20%;
        }

        .ww40 {
            width: 40%;
        }

        .jsColor {
            font-size: 20rpx;
        }

    }

    .head {
        height: 64rpx;
        background: #F7F9FA;
        border-top: 2rpx solid #E3E5E5;
        border-left: 2rpx solid #E3E5E5;

        .item {
            height: 64rpx;
            line-height: 64rpx;
            border-right: 2rpx solid #E3E5E5;
            box-sizing: border-box;
        }
    }



    .tr {
        border-top: 2rpx solid #E3E5E5;
        border-left: 2rpx solid #E3E5E5;


        .item {
            font-size: 24rpx;
            min-height: 64rpx;
            display: flex;
            align-items: center;
            border-right: 2rpx solid #E3E5E5;
            box-sizing: border-box;
            white-space: normal;
            word-break: break-all;

        }


    }
}

.label {
    display: flex;
    height: 30px;
    width: 86px !important;
    font-size: 13px;
    align-items: center;
    justify-content: center;
    background-color: #F7F9FA;
}


.content_num {
    display: flex;
    align-items: center;
    padding: 0 4rpx;


}

.penalize {
    width: 86rpx;
    line-height: 60rpx;
    font-size: 24rpx;
    span-align: center;
    color: #fff;
}

.check {
    width: 30rpx;
    height: 30rpx;
}

.z_list {
    max-height: 500rpx;
}


.search_list {
    min-height: 100rpx;
    width: 80vw;
}

.operate_box {
    padding: 10rpx 32rpx;

}

::v-deep .el-input__inner {
    height: 28px !important;
    line-height: 28px !important;
}
</style>