<template>
    <lj-win-popup
        ref="winPopup"
        :popupStyle="{ 'height': height}"
        position="bottom"
        class="widget-spin-off-wrapper"
        :closeable="false"
        :close-on-click-overlay="false"
        :class="{'sale-small': ifSamll}"
        @click-overlay="beforeClose"
    >
        <template #title>
            <div class="title">
                {{ editTitle }}
            </div>
            <div class="close-part" @click="beforeClose">
                <!-- <template v-if="ifEdit">
                    <i class="iconfont icon-wrong_light"></i>
                </template> -->
                <template v-if="!barcodeList.length">
                    我再想想
                </template>
            </div>
        </template>
        <template #body>
            <van-cell-group inset title="原码" class="barcode-wrapper">
                <barcode-mx-item  
                    :item="barcodeMx"
                    barcode="0"
                    :unit="barcodeMx.unit"
                    :is-link="true"
                    @confirm="handleGotoBarcode"
                    :class="{'barcode-isuse': dataStorage.kind == 0 && barcodeList.length}"
                >
                    <template slot="title" slot-scope="{data, clickTitle}">
                        <div class="card-barcode__title" @click.stop="clickTitle">
                            <i class="card-icon iconfont icon-erweima"></i>
                            <span class="card-title" :class="{'text-line-through': dataStorage.kind == 0 && barcodeList.length}">
                                {{ data.barcode }}
                            </span>
                            <i class="card-icon-right iconfont icon-right"></i>
                            <van-tag v-if="dataStorage.kind == 0 && barcodeList.length" plain class="isuse-tag">
                                作废
                            </van-tag>
                        </div>
                    </template>
                    <div slot="label" slot-scope="{data}">
                        <i class="iconfont icon-Calendar_light" style="font-size: 14px"></i>
                        <span class="field-value">{{ data.opdate | shortDateFilter }}</span>
                    </div>
                    <template slot="default" slot-scope="{data}">
                        <div class="card-default">
                            <van-tag style="margin-right:2px" type="primary" v-if="dataStorage.kind == 1 && barcodeList.length">
                                改
                            </van-tag>
                            <span class="field">
                                基数
                            </span>
                            <span class="field-value-primary">
                                {{ data.packqty }}
                            </span>
                            <span class="field-value">
                                {{ data.unit }}
                            </span>
                        </div>
                        <div class="card-default">
                            <span class="field">
                                {{ data.opemp }}
                            </span>
                        </div>
                    </template>
                </barcode-mx-item>
                <div class="other-more" v-if="barcodeMx.barcode_ori">
                    {{ `源条码【${barcodeMx.barcode_ori}】` }}
                </div>
            </van-cell-group>

            <template v-if="!barcodeList.length">
                <van-cell-group inset title="选择拆分方式" class="spinoff-model-wrapper">
                    <van-field
                        v-model="spinOffNumber"
                        :error="fieldError"
                        :error-message="fieldErrorMsg"
                        readonly
                        clickable
                        placeholder="输入需要拆分数量"
                        input-align="right"
                        label-width="10.2em"
                        @click="handleFocusSpinOff"
                    >
                        <template slot="label">
                            条码数量
                            <div class="field-label-extra">最多还可输入:{{barcodeMx.packqty}}{{barcodeMx.unit}}</div>
                        </template>
                        <template slot="extra">
                            {{ barcodeMx.unit }}
                        </template>
                    </van-field>
                    <van-cell
                        title="拆分方式"
                        :value="dataStorage.kindStr"
                        is-link
                        class="event-edit-cell"
                        @click="handleOpenSpinoffKind"
                    >
                    </van-cell>
                </van-cell-group>
                <div class="other-more" v-if="dataStorage.kind != -1">
                    {{isOtherMoreText}}
                </div>
            </template>
            <template v-else>
                <van-cell-group inset title="新条码" class="barcode-wrapper">
                    <barcode-mx-item 
                        v-for="(item, idx) in barcodeList"
                        :key="idx"
                        :item="item"
                        barcode="0"
                        :unit="barcodeMx.unit"
                        :is-link="true"
                        @confirm="handleGotoBarcode"
                    >
                        <template slot="title" slot-scope="{data, clickTitle}">
                            <div class="card-barcode__title" @click.stop="clickTitle">
                                <qrcode :value="data.barcode" type="img" :id="data.barcode" :ref="data.barcode" v-show="false"></qrcode>
                                <i class="card-icon iconfont icon-erweima"></i>
                                <span class="card-title">
                                    {{ data.barcode }}
                                </span>
                                <i class="card-icon-right iconfont icon-right"></i>
                                <van-tag type="success">
                                    新
                                </van-tag>
                            </div>
                        </template>
                        <div slot="label" slot-scope="{data}">
                            <i class="iconfont icon-Calendar_light" style="font-size: 14px"></i>
                            <span class="field-value">{{ data.opdate | shortDateFilter }}</span>
                        </div>
                        <template slot="default" slot-scope="{data}">
                            <div class="card-default">
                                <span class="field">
                                    基数
                                </span>
                                <span class="field-value-primary">
                                    {{ data.packqty }}
                                </span>
                                <span class="field-value">
                                    {{ data.unit }}
                                </span>
                            </div>
                            <div class="card-default">
                                <span class="field">
                                    {{ data.opemp }}
                                </span>
                            </div>
                        </template>
                    </barcode-mx-item>
                </van-cell-group>
                <div class="other-more print-set">
                    <span @click="handleGotoPrintSet">
                        <i class="iconfont icon-settings"></i>
                        打印格式
                    </span>
                </div>
            </template>

            <van-action-sheet
                v-model="spinoffKindState"
                :actions="spinoffKindActions"
                description="请选择拆分方式"
                cancel-text="取消"
                close-on-click-action
                get-container="body"
                @select="handleSelSpinoffKind"
                @close="ifSamll = false"
            >
            </van-action-sheet>
            <van-number-keyboard
                v-model="spinOffNumber"
                :show="showKeyboard"
                theme="custom"
                :extra-key="['00', '.']"
                close-button-text="完成"
                @blur="showKeyboard = false"
                @input="handleKBInput"
                @delete="handleKBDelete"
            />
        </template>
        <template #footer>
            <div class="footer">
                <template v-if="!barcodeList.length">
                    <van-button
                        class="btn lj-linear-status-blue"
                        block 
                        round
                        :disabled="fieldError || dataStorage.kind == -1"
                        :loading="loading_spinOff"
                        @click="handleConfirmToSpinoff"
                    >
                        拆分
                    </van-button>
                </template>
                <template v-else>
                    <van-button
                        class="btn"
                        block 
                        round
                        @click="handlePrintBarcode"
                    >
                        打印新条码
                    </van-button>
                    <van-button
                        class="btn lj-linear-status-blue"
                        block 
                        round
                        @click="handleConfirm"
                    >
                        {{ isConfirmText }}
                    </van-button>
                </template>
            </div>
        </template>
    </lj-win-popup>
</template>

<script>
import LjTagDouble from "components/lj-tag-double";
import LjWinPopup from "components/lj-win-popup"
import MtrldefItem from "components/L1APP/pda/mtrldef-item"
import BarcodeMxItem from "components/L1APP/pda/barcode-mx-item"
import {Qrcode} from 'vux';

export default {
    name: 'L1appSpinoffWidget',
    components: {
        LjWinPopup,
        LjTagDouble,
        MtrldefItem,
        BarcodeMxItem,
        Qrcode
    },
    data() {
        return {
            editTitle: "",
            orderActive: [],
            spinOffNumber: '', // 拆分数量
            spinoffKindState: false,
            spinoffKindActions: [
               {id: 0, name: '变更', subname: '原码作废，分拆两个新码', dscrp: '原码作废，并分拆成两个新码'},
               {id: 1, name: '拆分', subname: '原码保留，创建一个新码', dscrp: '原码保留，且基数减少，并拆分出一个新码'},
            ],
            dataStorage: {
                kind: -1,
                kindStr: '请选择',
            },
            showKeyboard: false,
            fieldError: false, // 输入框错误状态
            fieldErrorMsg: '', // 输入框错误信息
            barcodeList: [], // 变更或拆分的条码, 空：未变更或拆分
            loading_spinOff: false, // 正在拆分

            giveUpAppeal: false, // 放弃上诉
            showGiveUp: false, // 显示放弃上诉
            evOne: {},
            empList: [],
            relList: [],
            reasonKindState: false,
            fjmxState: false,
            fjActions: [
               {id: 0, name: '图片'},
               {id: 1, name: '视频'}
            ],
            ifSamll: false, // 是否缩小
            showReasonRel: false, // 是否显示相关资料模块
            btnKind: 0,
            ifChange: false, // 是否有修改？
            ifEdit: false, // 是否是修改？
        };
    },
    props: {
        height: { // 弹窗高度
            type: String,
            default: 'auto'
        },
        barcodeMx: {
            type: Object,
            default: () => {
                return {}
            }
        },
        printModule: {
            type: String,
            default: ''
        }
    },
    computed: {
        isOtherMoreText() {
            let dscrp = '';
            for (const kind of this.spinoffKindActions) {
                if (kind.id == this.dataStorage.kind) {
                    dscrp = kind.dscrp;
                    break;
                }
            }
            return `*温馨提示：${dscrp}`
        },
        isConfirmText() {
            switch (this.dataStorage.kind) {
                case 1:
                    if (this.barcodeList.length == 1 && this.barcodeList[0].packqty <= this.barcodeMx.packqty) {
                        return '确认并添加新条码';
                    } else {
                        return '确认'
                    }
                default:
                    return '确认';
            }
        }
    },
    mounted() {
        
    },
    methods: {
        /**打开组件 */
        open(title) {
            this.editTitle = title;
            this.ifSamll = false;
            this.orderActive = [];
            this.barcodeList = [];

            let outwareSaleSpinOff = $lj.getStorage('outwareSaleSpinOff') || {};
            let kind = outwareSaleSpinOff.hasOwnProperty('kind') ? outwareSaleSpinOff.kind : -1;
            let kindStr = '请选择';
            for (const item of this.spinoffKindActions) {
                if (item.id == kind) {
                    kindStr = item.name;
                    break;
                }
            }
            this.dataStorage.kind = kind;
            this.dataStorage.kindStr = kindStr;

            this.$refs.winPopup.open();
        },
        beforeClose() {
            this.$refs.winPopup.close();
        },
        /**选择拆分方式类型 */
        handleSelSpinoffKind(action, index) {
            this.dataStorage.kindStr = action.name;
            this.dataStorage.kind = action.id;
            this.ifSamll = false;

            let outwareSaleSpinOff = $lj.getStorage('outwareSaleSpinOff') || {};
            outwareSaleSpinOff.kind = action.id;
            $lj.setStorage('outwareSaleSpinOff', outwareSaleSpinOff);
        },
        /**点击弹出拆分方式弹窗 */
        handleOpenSpinoffKind() {
            // this.ifChange = true;
            this.spinoffKindState = true;
            this.ifSamll = true;
        },
        /**聚焦输入框 */
        handleFocusSpinOff() {
            // ev.currentTarget.select();
            // let tgSearch = document.querySelector("input.van-field__control");
            // tgSearch.select();
            this.spinOffNumber = '';
            this.fieldError = false;
            this.fieldErrorMsg = '';
            this.orderActive = []; // 收起订单明细
            if (!this.showKeyboard) {
                this.showKeyboard = true;
            }
        },
        /**van键盘输入 */
        handleKBInput(value) {
            console.log(' value :>>>>>>>>>>>>   >>>>>>>>>', JSON.stringify(value));
            console.log(' this.spinOffNumber.indexOf :>>>>>>>>>>>>   >>>>>>>>>', JSON.stringify(this.spinOffNumber));

            this.fieldError = false;
            this.fieldErrorMsg = '';
            if (this.spinOffNumber.indexOf('.') == -1) {
                if (Number(this.spinOffNumber) == 0) {
                    this.$nextTick(() => {
                        this.spinOffNumber = value + '';
                    })
                }
            } else if (this.spinOffNumber && this.spinOffNumber.indexOf('.') > -1) {
                if (value == '.') {
                    this.$nextTick(() => {
                        this.spinOffNumber = this.spinOffNumber.replace(/\.$/g, '')
                    })
                } else {
                    if (this.spinOffNumber.indexOf('.') == 0) {
                        this.$nextTick(() => {
                            this.spinOffNumber = '0' + this.spinOffNumber;
                        })
                    }
                }
            }
            if (Number(this.spinOffNumber + value) > Number(this.barcodeMx.packqty)) {
                this.$nextTick(() => {
                    this.spinOffNumber = this.barcodeMx.packqty + '';
                    this.fieldError = true;
                    this.fieldErrorMsg = '需少于原码基数';
                })
            }
        },
        /**van键盘删除 */
        handleKBDelete() {
            this.fieldError = false;
            this.fieldErrorMsg = '';
            this.$nextTick(() => {
                if (!this.spinOffNumber) {
                    this.spinOffNumber = 0 + '';
                }
                if (Number(this.spinOffNumber) > Number(this.barcodeMx.packqty)) {
                    this.$nextTick(() => {
                        this.spinOffNumber = this.barcodeMx.packqty + '';
                        this.fieldError = true;
                        this.fieldErrorMsg = '需少于原码基数';
                    })
                }
            })
        },
        /**底部按钮： 整拆 */
        handleConfirmToAllSpinoff() {
            this.$emit('allconfirm', this.barcodeMx)
            this.beforeClose()
        },
        /**底部按钮： 拆分 */
        handleConfirmToSpinoff() {
            if (this.dataStorage.kind == -1) {
                $lj.toast("请选择拆分方式", 1000, "bottom");
                return false;
            }
            if (Number(this.spinOffNumber) <= 0) {
                this.fieldError = false;
                this.fieldErrorMsg = '数量必须大于0';
                $lj.toast("请填写需要发货的数量", 1000, "bottom");
                return false;
            }
            let requestBody;
            let self = this;
            let qtyList = [];
            let mxQty = $lj.floatSub(this.barcodeMx.packqty, this.spinOffNumber);

            this.loading_spinOff = true;
            if (this.dataStorage.kind == 0) {
                // 变更
                qtyList.push(mxQty);
                qtyList.push(Number(this.spinOffNumber));
                requestBody = {
                    token: $lj.getStorage("token"),
                    userid: $lj.getStorage("user").usercode,
                    qtyList: qtyList,
                    barcode: this.barcodeMx.barcode,
                    spinoff: false,
                };
            } else {
                // 拆分
                qtyList.push(Number(this.spinOffNumber));
                requestBody = {
                    token: $lj.getStorage("token"),
                    userid: $lj.getStorage("user").usercode,
                    qtyList: qtyList,
                    barcode: this.barcodeMx.barcode,
                    spinoff: true
                };
            }
            $lj.postLJRequest('PDA_SaveSpinOffBarcode', requestBody, function (ret) {
                if (ret) {
                    self.loading_spinOff = false;
                    if (ret.barcodeList.length > 0) {
                        $lj.toast("条码变更成功", 1000, "bottom");
                        self.barcodeList = ret.barcodeList;
                        if (requestBody.spinoff) {
                            self.$set(self.barcodeMx, 'packqty', mxQty);
                            self.$emit('confirm', []);
                        }
                    }
                }
            }, function(err) {
                self.loading_spinOff = false;
                api.alert({
                    title: "条码变更失败",
                    msg: err.ErrMsg
                });
                $lj.FailSound();
            });
        },
        /**底部按钮：打印 */
        handlePrintBarcode() {
            let self = this;
            $BlueToothPrintTemplate.getAlreadySaveTemplateInfo().then(function(){
                let self2 = self;
                $BlueToothPrintTemplate.setBlutToothPrintUseModule("outware-sale").then(function() {
                    $BlueToothPrintTemplate.getBlueToothPrintUseTemplate();
                    for(let i = 0;i < self2.barcodeList.length;i++){
                        self2.barcodeList[i].p_qty = `${self2.barcodeList[i].packqty * self2.barcodeList[i].qty}`;
                        self2.barcodeList[i].p_date = $lj.dateformat(new Date(),'yyyy-MM-dd');
                        $BlueToothPrintTemplate.GetBlueToothPrint(self2.barcodeList[i]);
                    }
                    $BlueToothPrintTemplate.getBlueToothPrintUsePrinter().print();
                })
            })
        },
        /**按钮：打开打印设置 */
        handleGotoPrintSet() {
            $lj.openWin('print-template', {
                winMode: 1,
                moduleName: this.printModule,
                bluetoothData: null
            })
        },
        /**底部按钮：确定 */
        handleConfirm() {
            if (this.dataStorage.kind == 1) {
                // 拆分时，新条码满足需求时返回
                if (this.barcodeList[0].packqty <= this.barcodeMx.packqty) {
                    this.$emit('confirm', this.barcodeList)
                }
            } else {
                this.$emit('confirm', []);
            }
            this.beforeClose();
        },
        /**查看条码拆分记录 */
        handleGotoBarcode(data) {
            $lj.openWin('rp-barcode-mx', {barcode: data.barcode});
        },
    },
    filters: {
        shortDateFilter(data) {
            return $lj.formatTime(data, '{y}-{m}-{d} {h}:{i}', true)
        }
    }
};
</script>

<style lang="less">
.widget-spin-off-wrapper {
    transition: all cubic-bezier(0.77, 0, 0.18, 1) 0.4s;
    border-top-left-radius: 16px;
    border-top-right-radius: 16px;
    transform-origin: bottom center;
    background-color: @light-barkground-primary;

    &.sale-small {
        transform: scale(0.96);
    }
    .popup_header {
        background-color: #fff!important;
        display: flex;

        .title {
            flex: 1;
            text-align: left;
            margin-left: 16px;
        }
        .close-part {
            flex-shrink: 0;
            color: @light-label-tertiary;
            font-size: 14px;
            margin-right: 16px;
            font-weight: normal;
        }
    }

    .mtrldef-wrapper {
        margin: 12px 16px;
        margin-bottom: 4px;
        background-color: @light-barkground-elevated-primary;
        border-radius: 8px;
        overflow: hidden;

        &::after {
            content: none;
        }
        .lj_card_mtrldef--wrapper {
            &::after {
                content: none;
            }
        }
        .info-cost {
            font-size: 14px!important;
            font-weight: 500;
            .field {
                font-weight: normal;
            }
        }
    }
    .order-wrapper {
        // margin: 12px 16px;
        // margin-top: 8px;
        .van-cell, .van-collapse-item__content {
            background: unset;
        }
        .van-collapse-item__content {
            overflow: hidden;
            border-radius: 4px;
            padding: 0;
            margin: 4px 8px;
        }
        .lj-card__header {
            background-color: @light-barkground-elevated-primary;
        }
        .collapse-title {
            color: @light-label-secondary;
        }
        .iconfont {
            color: @light-label-secondary;
            font-size: 14px;
        }
    }
    .barcode-wrapper {
        .lj-card__header {
            min-height: 52px;
        }
        .field-value-primary {
            color: @light-label-primary;
        }
        .barcode-isuse {
            &.card-barcode {
                background-color: @light-fill-primary!important;

                .van-tag {
                    background-color: unset;
                }
            }
        }
    }
    .spinoff-model-wrapper {
        .van-field__control {
            color: @musePrimary;
            padding-right: 8px;
        }
        .van-field--error {
            .van-field__control {
                color: @light-system-red;
            }
        }
        .van-field__error-message {
            text-align: right;
        }
        .van-cell__title {
            color: @light-label-primary;
        }
        .field-label-extra {
            color: @light-label-tertiary;
            font-size: 12px;
        }
    }
    .van-number-keyboard {
        z-index: 2000;
    }
    .footer {
        flex: 1;
        display: flex;
        .btn {
            flex: 1;
            transition: all cubic-bezier(0.77, 0, 0.18, 1) 0.8s;
            &.van-button--disabled {
                -webkit-filter: grayscale(100%); /* Chrome, Safari, Opera */
                filter: grayscale(100%);
            }
            &.lj-linear-status-blue {
                color: #fff;
            }
            & + .btn {
                margin-left: 16px;
            }
        }
    }

    .event-edit-cell {
        .van-cell__right-icon {
            font-size: 16px;
            color: @musePrimary!important;
        }
        .van-cell__value {
            color: @musePrimary;
        }
        .van-cell__title {
            color: @light-label-primary;
        }
    }
    .van-cell-group::after {
        content: none;
    }
    .other-more {
        margin: 8px 16px;
        color: @light-label-tertiary;

        span {
            color: @musePrimary;
        }
        .iconfont {
            font-size: 14px;
        }
        &.print-set {
            padding-left: 16px;
        }
    }
}
</style>