<template>
    <view class="page-box">
        <view class="title row bothSide verCenter">
            <text class="t1">入仓号</text>
            <text class="t2">{{ erp_order_sn }}</text>
        </view>
        <view class="select-split">
            <view class="box">
                <view class="label row verCenter">
                    <text class="t1">*</text>
                    <text class="t2">选择需要拆分型号</text>
                </view>
                <view class="pick-list row bothSide verCenter">
                    <picker @change="bindPickerChange($event, 1)" :value="goods_index" :range="goods_list" :range-key="'model'" style="width: 80%;">
                        <view class="uni-text">{{ goods_list[goods_index].model || '请选择型号' }}</view>
                    </picker>
                    <text class="iconfont icon-sanjiaoxing1"></text>
                </view>
            </view>
            <view class="box">
                <view class="label row verCenter">
                    <text class="t1">*</text>
                    <text class="t2">&nbsp;&nbsp;选择拆分数量</text>
                </view>
                <view class="pick-list row bothSide verCenter">
                    <picker @change="bindPickerChange($event, 2)" :value="index" :range="num_arr" style="width: 80%;">
                        <view class="uni-text">{{ num_arr[index] || '请选择拆分数量' }}</view>
                    </picker>
                    <text class="iconfont icon-sanjiaoxing1"></text>
                </view>
            </view>
        </view>
        <view class="text-details" v-if="tally_num > 0">
            <view class="text-row row verCenter bothSide" style="margin-bottom: 20rpx;">
                <view class="left">
                    <text class="t1">原产国家:</text>
                    <text class="t2">{{ goods_list[goods_index].country || '' }}</text>
                </view>
                <view class="right"></view>
            </view>
            <view class="text-row row verCenter bothSide">
                <view class="left">
                    <text class="t1">订单数量:</text>
                    <text class="t2">{{ goods_list[goods_index].qty }}</text>
                </view>
                <view class="right">
                    <text class="t1">剩余拆分:</text>
                    <text class="t2">{{ parseInt(goods_list[goods_index].qty) - parseInt(total) }}</text>
                </view>
            </view>
        </view>
        <view class="select-split-detail" v-if="tally_num > 0">
            <view class="box" v-for="(item, index) in tally_num" :key="index">
                <view class="label">产地拆分&nbsp;{{ index + 1 }}</view>
                <view class="pick-list row bothSide verCenter">
                    <view class="wrap row verCenter">
                        <view class="uni-text" @click="open(index)">{{ detail_json[index].origin ? detail_json[index].origin : '请选择国家地区' }}</view>
                        <text class="iconfont icon-sanjiaoxing1"></text>
                    </view>
                    <view class="input-wrap"><input @input="onInputNum" type="number" inputmode="numeric" placeholder="请输入拆分数量" class="uni-input" placeholder-style="color:#404547;font-weight:bold;" v-model="detail_json[index].tally_num" /></view>
                </view>
            </view>
        </view>
        <template v-if="tally_num > 0 && goods_index != -1">
            <view class="btn row rowCenter verCenter" @click="submit()">确认拆分</view>
        </template>
        <template v-else>
            <view class="btn row rowCenter verCenter" @click="submit()" style="margin-top: 40rpx;">确认拆分</view>
        </template>
        <!-- 选择国家 -->
        <uni-popup ref="popup" background-color="#F1F4F6">
            <view class="popup-content">
                <view class="search-baar row verCenter">
                    <text class="iconfont icon-a-riqi11"></text>
                    <input type="text" class="uni-input" placeholder="请输入国家或地区名称(支持中英文)" placeholder-style="font-size:26rpx;color:#6E767A;" @input="onInput" v-model="origin" style="width: 100%;" />
                </view>
                <view class="data-list">
                    <view class="box row bothSide verCenter" v-for="(item, index) in origin_list" :key="index" :class="{ curr: filter_status[index] }" @click="filterChange(index)">
                        <text class="text">{{ item }}</text>
                        <view class="check-ico"></view>
                    </view>
                </view>
                <view class="pop-btn row rowCenter verCenter" @click="confirmChange">确 认</view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
    import { API } from '@/util/api.js';
    import { createArray } from '@/util/util.js';

    export default {
        data() {
            return {
                originIndex: 0, //默认第一个
                curr: -1, //当前打开的是哪个产地
                erp_order_sn: '',
                goods_index: -1,
                goods_list: [],
                num_arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
                index: -1,
                filter_status: [], //控制状态
                origin_list: [], //产地
                origin: '', //搜索国家携带的参数
                tally_num: 0, //拆分数量
                detail_json: [], //收集的数据
                dataStates: {}, // 用于记录数据状态的对象
                total: 0
            };
        },
        onLoad(options) {
            this.erp_order_sn = options.erp_order_sn || '';
            this.originIndex = options.originIndex;

            // 从本地缓存中获取数据
            const dataFromSourcePage = uni.getStorageSync('paramsOrigin');

            // 使用Object.assign()将dataFromSourcePage的属性合并到data中
            Object.assign(this.$data, dataFromSourcePage[this.originIndex]);
        },
        onShow() {
            this.getData();
            this.getOrigin();
        },
        methods: {
            open(index) {
                this.curr = index;
                this.filter_status.fill(false);
                this.$refs.popup.open('bottom');
            },
            /**
             * 找出false对应的下标
             * @param {Object} arr
             * @param {Object} target
             */
            findIndex(arr, target) {
                const result = [];
                arr.map((item, index) => {
                    if (item === target) {
                        result.push(index);
                    }
                });
                return result;
            },
            onInputNum() {
                const total = this.detail_json.reduce((sum, item) => {
                    if (item.tally_num) {
                        return sum + item.tally_num * 1;
                    } else {
                        return sum * 1;
                    }
                }, 0);

                var num = this.goods_list[this.goods_index].qty * 1;

                if (total > num) {
                    uni.showModal({
                        title: '错误提示',
                        content: '拆分数量总和必须等于订单数量(不可大于或者小于)',
                        showCancel: false
                    });
                    return false;
                }

                this.total = total;
            },
            onInput() {
                // 清除之前的定时器
                clearTimeout(this.timer);
                this.timer = setTimeout(() => {
                    this.origin_list = []; //数组清空
                    this.getOrigin();
                }, 800);
            },
            bindPickerChange: function(e, type) {
                console.log('picker发送选择改变,携带值为', e.target.value);
                if (type == 1) {
                    this.goods_index = e.target.value;
                } else if (type == 2) {
                    this.tally_num = parseInt(e.target.value) + 1;
                    this.index = e.target.value;
                    this.total = 0;
                    this.detail_json = Array.from({ length: this.tally_num }, () => ({ origin: '', tally_num: '', entryID: this.goods_list[this.goods_index].entryID }));
                }
            },
            getOrigin() {
                this.request(API.getOrigin, 'GET', { origin: this.origin }, true).then(res => {
                    if (res.err_code === 0) {
                        this.origin_list = Object.values(res.data);
                        this.filter_status = createArray(this.origin_list.length, false);
                    } else {
                        uni.showToast({
                            title: res.err_msg,
                            icon: 'error'
                        });
                    }
                });
            },
            getData() {
                this.request(API.getTallyGoods, 'GET', { erp_order_sn: this.erp_order_sn }, true).then(res => {
                    if (res.err_code === 0) {
                        if (res.data.entrys.length > 0) {
                            this.goods_list = res.data.entrys;
                        }
                    } else {
                        uni.showToast({
                            title: res.err_msg,
                            icon: 'error'
                        });
                    }
                });
            },
            /**
             *筛选过滤出选中的元素
             */
            filterChange(index) {
                this.$set(this.filter_status, index, (this.filter_status[index] = !this.filter_status[index]));
                let filter_arr = this.findIndex(this.filter_status, true);
                var name = filter_arr.map(i => this.origin_list[i]);
                this.detail_json[this.curr].origin = name[0];
                this.$forceUpdate();
                this.$refs.popup.close();
            },
            confirmChange() {
                this.$refs.popup.close();
            },
            /**
             * 判断是否有重复的产地
             */
            hasDuplicateOrigin(arr) {
                const uniqueOrigins = new Set();
                for (const item of arr) {
                    if (uniqueOrigins.has(item.origin)) {
                        return true;
                    }
                    uniqueOrigins.add(item.origin);
                }
                return false;
            },
            submit() {
                if (this.goods_index == -1) {
                    uni.showToast({
                        title: '请选择型号',
                        icon: 'none'
                    });
                    return false;
                }
                if (this.tally_num == 0) {
                    uni.showToast({
                        title: '请选择拆分数量',
                        icon: 'none'
                    });
                    return false;
                }

                const shouldContinue = !this.detail_json.some(item => {
                    if (!item.origin) {
                        uni.showToast({
                            title: '请选择拆分国家',
                            icon: 'none'
                        });
                        return true;
                    }
                    return false;
                });

                const hasDuplicates = this.hasDuplicateOrigin(this.detail_json);
                if (hasDuplicates) {
                    uni.showToast({
                        title: '不允许有相同产地,请重新选择产地',
                        icon: 'none'
                    });
                    return false;
                }

                if (shouldContinue) {
                    const totalTallyNum = this.detail_json.reduce((total, item) => total + parseInt(item.tally_num), 0);
                    const total = this.goods_list[this.goods_index].qty * 1;
                    if (totalTallyNum != total) {
                        uni.showModal({
                            title: '错误提示',
                            content: '拆分数量总和必须等于订单数量(不可大于或者小于)',
                            showCancel: false
                        });
                        return false;
                    }
                }

                uni.$emit('updateOriginData', this.$data);
                uni.navigateBack({
                    delta: 1
                });
            }
        }
    };
</script>

<style scoped lang="scss">
    @import '../../assets/css/tallyGoods/originSplit.scss';
</style>