<template>
    <div>
        <div class="container">
            <van-form class="formStyle" ref="formRef" @submit="onSubmit">
                <div class="formStyle-top">
                    <van-field style="width: 100%;" v-model="object.expressNo" name="expressNo" label="快递单号"
                        placeholder="快递单号" :rules="[{ required: true }]" />
                    <img class="formStyle-top-img" @click="wxScanCodeB()" src="@/assets/user/u4.png" alt="">
                </div>

                <van-field readonly clickable name="expressCompany" label="快递公司" :value="object.value"
                    placeholder="请选择快递公司" @click="onShowPicker" :rules="[{ required: true }]" />
                <van-popup v-model="showPicker" position="bottom">
                    <van-picker show-toolbar :columns="GeLogisticsList" @confirm="onConfirm"
                        @cancel="showPicker = false" />
                </van-popup>

                <van-field :value="onGroupObject.phone" @focus="onFocus" name="phone" label="收件人手机号"
                    placeholder="请输入手机号" :rules="[{ required: true }]" />

                <van-field :value="onGroupObject.NAME" @focus="onFocus" name="NAME" label="收件人姓名"
                    placeholder="请输入收件人姓名" />

                <van-field :value="onGroupObject.departmentName" name="departmentId" label="收件人部门" placeholder="自动填充"
                    readonly />
                <van-field :value="onGroupObject.mailRoomName" name="mailRoom" label="所属收发室" placeholder="自动填充"
                    readonly />
                <van-field :value="onGroupObject.seat_no" name="sendSeat" label="收件人座位" placeholder="自动填充" readonly />

                <van-field name="expressType" label="快件类型">
                    <template #input>
                        <van-radio-group v-model="object.radio" direction="horizontal">
                            <van-radio name="文件">文件</van-radio>
                            <van-radio name="物品">物品</van-radio>
                        </van-radio-group>
                    </template>
                </van-field>

                <van-field v-model="object.expressNum" name="expressQuantity" placeholder="请输入快递数量" label="快递数量" />

                <van-field readonly clickable name="shelfInformation" label="货架信息" :value="object.value4"
                    placeholder="请选择货架" @click="shelf = true" :rules="[{ required: true }]" />
                <van-popup v-model="shelf" position="bottom">
                    <van-picker show-toolbar :columns="shelfs" @confirm="onShelf" @cancel="shelf = false" />
                </van-popup>

                <div style="display: flex; justify-content: flex-start;">
                    <van-field name="isPayOnDelivery" label="到付件">
                        <template #input>
                            <van-checkbox :disabled="ischeckDisabled" v-model="checkbox" @change="onCheckboxChange"
                                shape="square" />
                            <!-- <span style="margin-left: 4px;">到付</span> -->
                        </template>
                    </van-field>
                    <van-field :rules="[{ required: checkbox }]" :disabled="isdisabled" v-model="object.payMoney"
                        name="payMoney" placeholder="请输入到付金额" />
                </div>

                <van-field v-model="object.remark" label="快递备注" name="remark" placeholder="请输入快递备注" />

                <div
                    style=" display: flex; justify-content: space-between; background-color: #fff;  padding: 10px 20px;">
                    <van-button size="small" style="border-radius: 5px; width: 40vw; " block type="info"
                        @click="handleSubmit(true)" native-type="button">保存并打印</van-button>

                    <van-button size="small" style="border-radius: 5px; width: 30vw;" block type="info"
                        @click="handleSubmit(false)" native-type="button">仅保存</van-button>
                </div>
            </van-form>
        </div>

        <!-- 输入手机号后弹出 -->
        <van-popup v-model="phoneShow" class="popupStyle">
            <form action="" class="popupStyle-top">
                <van-search style="width: 100%;" ref="isSearchFocus" @search="searchCrux" v-model="searchKey"
                    placeholder="请输入搜索关键词" />
                <van-icon class="popupStyle-top-icon" @click="searchCrux" name="search" color="#1989fa" size="20" />
            </form>
            <div style="height: calc(100vh - 105px); overflow-y: auto;">
                <van-cell-group class="vanPopup" @click="onGroup(item)" v-for="(item, index) in searchKeyList"
                    :key="index" inset>
                    <van-cell style="font-size: 16px;">{{ item.phone }}--{{ item.NAME }}</van-cell>
                    <!-- < :value="item.phone" />
                    <van-cell :value="item.NAME" /> -->
                    <!-- <van-cell title="收件人部门" :value="item.departmentName" />
                    <van-cell title="所属收发室" :value="item.mailRoomName" />
                    <van-cell title="收件人楼层" :value="item.mailFloor" />
                    <van-cell title="收件人座位" :value="item.seat_no" />
                    <van-cell title="收发室Id" :value="item.ROOM_ID" style="display: none;" />
                    <van-cell title="收件人userID" :value="item.USER_ID" style="display: none;" /> -->
                </van-cell-group>
            </div>
            <van-button class="goback" @click="phoneShow = false" type="info">
                退出
            </van-button>
        </van-popup>

        <!-- 打印机选择器 -->
        <van-popup v-model="printerShow" position="bottom">
            <van-picker show-toolbar :columns="getPrintersList" @confirm="onPrinter" @cancel="printerShow = false">
                <template v-slot:option="value">
                    {{ value.printerName }}
                </template>
            </van-picker>
        </van-popup>
    </div>
</template>

<script>
import { appGetEmployeeInfoByPhone, appGeLogisticsList, appSaveExpressRecord, getSysUserInfoByUserIdAPI, getListOfPrinters, storagePrintSmallTab, appFindInsideInfoByExpressNo } from '@/api/index'
import { Toast } from 'vant';
import wx from "weixin-jsapi";
export default {
    data() {
        return {
            printNo: '',// 打印面单号
            isPrint: false,//是否需要打印
            expressInfo: {},// 快件信息
            gfg: {},
            isCompany: '否',
            inputValue: '',//输入手机号后四位聚焦
            phoneShow: false, //输入手机号后弹出搜索
            searchKey: '',//搜索关键
            searchKeyList: [], // 搜索后存储的数据
            onGroupObject: {},//点击后映射的参数
            GeLogisticsList: [],//存放快递公司
            object: {
                expressNum: 1,//快递数量
                remark: '',
                radio: '文件',
                payMoney: '',//应付金额
                expressNo: '',//快递单号
                value4: '', //货架信息
                value: '', //快递公司
            },
            value14: '',//添加下一个的货架信息
            checkbox: false,//到付是否选择
            ischeckDisabled: false,//到付是否必填
            isdisabled: true,//是否选中多选
            showPicker: false, //快递公司
            shelfs: [], //收发室
            shelf: false, //收发室
            pattern: /^\d*\.?\d+$/, // 有问题
            regex: /^[1-9]\d*$/,
            floorId: '',
            shelfsss: [],//
            getPrintersList: [],//打印机获取数据
            printerShow: false,//打印机出现
            printerName: '',//选中的打印机名称
            printerId: '',//选中的打印机id
            value14: '',
        };
    },
    async mounted() {
        this.getUser()
        this.floorId = this.$store.state.user.expressScope
        const expressData = await appFindInsideInfoByExpressNo({ insideNum: 'S6000000363245086' })
        this.handleAppFindInsideInfoByExpressNoCallback(expressData)
    },
    methods: {

        // 快递单号
        wxScanCodeB() {
            wx.scanQRCode({
                needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                success: async (res) => {
                    var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                    if (result.indexOf(",") != -1) {
                        let result1 = res.resultStr.split(",");
                        result = result1[result1.length - 1];
                    }
                    this.object.expressNo = result
                    const expressData = await appFindInsideInfoByExpressNo({ insideNum: result })
                    this.handleAppFindInsideInfoByExpressNoCallback(expressData.data)
                    console.log(expressData)
                },
                error: function (res) {
                    console.log(res, 'error++++++++++');
                }
            });
        },

        // 查询快递单号回调
        handleAppFindInsideInfoByExpressNoCallback(data) {
            if (!data) return
            this.expressInfo = data;
            this.object.value = this.$store.state.user.company;
            this.onGroupObject.phone = data.addressee_phone
            this.onGroupObject.NAME = data.addressee_name
            this.onGroupObject.departmentName = data.addressee_dept_name
            this.onGroupObject.mailRoomName = data.mailRoomName
            this.onGroupObject.seat_no = data.addressee_seat_no
            this.object.remark = data.express_remark
            this.onGroupObject.USER_ID = data.addressee_user_id
            this.onGroupObject.ROOM_ID = data.mainRoomId;
            this.object.radio = data.express_type == '1' ? '文件' : '物品'
        },
        // 手机号点击聚焦
        onFocus() {
            this.phoneShow = true
            this.$nextTick(() => {
                if (this.$refs.isSearchFocus) {
                    this.$refs.isSearchFocus.querySelector('input').focus()
                }
            })
        },
        // 搜索关键
        async searchCrux() {
            const res = await appGetEmployeeInfoByPhone({ inquire: this.searchKey }, { emulateJSON: true, loading: true, message: '获取数据中...' })
            this.searchKeyList = res.employeeInfo
        },
        // 点击group
        onGroup(item) {
            this.onGroupObject = item
            this.phoneShow = false
        },
        // 选择快递公司
        async onShowPicker() {
            const res = await appGeLogisticsList({ page: '', limit: '' }, { emulateJSON: true })
            if (res.msg == 'success') {
                this.GeLogisticsList = res.data.map((item) => {
                    return item.expressCompany
                })
                this.GeLogisticsList.unshift(this.$store.state.user.company)
            } else {
                Toast('系统异常')
            }
            this.showPicker = true
        },
        // 选择快递公司
        onConfirm(value) {
            this.object.value = value;
            if (this.$store.state.user.company == value) {
                this.isCompany = '是'
                this.ischeckDisabled = true
            } else {
                this.isCompany = '否'
                this.ischeckDisabled = false
            }

            this.showPicker = false;
        },
        // 货架信息
        onShelf(value) {
            this.object.value4 = value;
            this.shelf = false;
        },

        handleSubmit(isPrint) {
            this.isPrint = isPrint;
            this.$refs.formRef.submit()
            console.log('submit')
        },

        // 提交
        async onSubmit(values) {
            if (!this.regex.test(this.object.expressNum)) {
                this.$toast('快递数量不能为0以下或小数')
                throw '快递数量不能为0以下或小数'
            }
            console.log(!this.regex.test(this.object.expressNum))

            if (this.checkbox == true) {
                if (!this.pattern.test(this.object.payMoney)) {
                    this.$toast('到付金额只能输入数字')
                    throw '到付金额只能输入数字'
                }
            }

            const params = {
                isCompany: this.isCompany,
                mailRoomId: this.onGroupObject.ROOM_ID,//收发室Id
                userId: this.onGroupObject.USER_ID,//收件人userID

            }
            const originalObj = {
                isPayOnDelivery: values.isPayOnDelivery == true ? '是' : '否',
            };
            const value = {
                ...values,
                ...originalObj
            }

            if (values.isPayOnDelivery) {
                // 内部件
                value.senderName = this.expressInfo.send_name
                value.senderNumber = this.expressInfo.send_phone
                value.senderDepartmentId = this.expressInfo.send_dept_name
            }
            const _params = { ...params, ...value, departmentId: this.onGroupObject.departmentName }
            console.log(_params, ' _params===========')
            const res = await appSaveExpressRecord(_params, { emulateJSON: true, loading: true })
            this.value14 = this.object.value4
            if (res.msg == 'success') {
                this.$toast('入库成功')
                if (this.isPrint) {
                    this.printNo = _params.expressNo
                    this.printerGo();
                }
                this.isPrint = false;
                this.expressInfo = {};
                this.object = {
                    expressNum: 1,
                    remark: '',
                    radio: '文件',
                    payMoney: '',
                    expressNo: '',
                    value4: '',
                    value: '',
                }
                this.onGroupObject = {
                    phone: '',
                    NAME: '',
                    departmentName: "",
                    mailRoomName: "",
                    mailFloor: '',
                    seat_no: '',
                },
                    this.checkbox = false

            } else if (res.msg == 'already') {
                this.$toast('该账号已添加过')
                throw '该账号已添加过'
            } else if (res.msg == 'PermissionControl') {
                this.$toast('不在揽收范围')
                throw '不在揽收范围'
            } else if (res.code == 444) {
                this.$toast(res.error)
                // this.$toast(res.msg)
                throw res.error
            }
            this.object.value4 = this.value14
        },
        // 保存/打印小标签并添加下一个
        async printerGo() {
            const getPrinters = await getListOfPrinters({})
            console.log(getPrinters)
            if (getPrinters.data.length === 0) {
                Toast('该用户未绑定打印机')
                return;
            }
            if (getPrinters.data.length === 1) {
                this.onPrinter(getPrinters.data[0])
                console.log('1111111111111111111111111111111111', getPrinters.data[0])
                return;
            }
            if (getPrinters.code == 0) {
                // const qwe = {
                //     IMEI: "8672970676795912",
                //     companyId: "990b526776e74ff9ab141ff28e09f0922",
                //     correspondingRoles: "揽件员2",
                //     id: 72,
                //     printerName: "禁魔石打印机2",
                //     recordDate: "2024-04-12 15:10:12.4282",
                //     shareCode: "9077782",
                //     st: "12",
                //     type: "12",
                //     useTheId: "11392",
                // }     //脏数据
                // getPrinters.data.push(qwe)
                this.getPrintersList = getPrinters.data.map((item) => {
                    return { printerName: item.printerName, id: item.id }
                })
                this.printerShow = true
            } else {
                Toast('系统异常')
            }

        },
        // 打印机弹框确认
        async onPrinter(e) {
            console.log(e, 'eeeeeeeeeeeeeee')
            const toask = this.$toast.loading({
                duration: 0, // 持续展示 toast
                forbidClick: true,
                message: '加载中',
            });
            this.printerName = e.printerName;
            this.printerId = e.id;

            // 开始走打印机面单
            try {
                const res = await storagePrintSmallTab({ expressNo: this.printNo, id: e.id })
                if (res.msg == 'success') {
                    Toast('打印成功')
                    this.printNo = ''

                }
                this.printerShow = false;
            } catch (error) {

            }
            toask.clear();
        },
        // 到付change
        onCheckboxChange() {
            this.isdisabled = !this.isdisabled
        },
        // 获取用户信息
        async getUser() {
            const res = await getSysUserInfoByUserIdAPI({ userId: localStorage.getItem("courierUserId") })
            this.shelfs = res.sysUserInfo.shelf.split(',');

            this.$store.state.user = res.sysUserInfo
            console.log(this.$store.state.user, 'this.$state.state.user')
        }
    },
};
</script>

<style lang="less" scoped>
.searchCrux {
    position: fixed;
    height: 20px;
    width: 20px;
    top: 15px;
    right: 10px;

}

.goback {
    position: fixed;
    height: 50px;
    width: 100%;
    bottom: 0;
    left: 0;
}

.container {
    height: 100vh;

    background-color: #f2f2f2;

    .formStyle {

        &-top {
            display: flex;
            justify-content: space-between;
            background-color: #fff;

            &-img {
                width: .4rem;
                height: .4rem;
                margin-top: 10px;
                margin-right: 0.3rem;
            }
        }

    }





}

.vanPopup {

    border-bottom: 1px solid #eaeaea;
    padding: 12px 0;
    border-radius: 0px;

    .van-cell {
        padding: 0;
    }

    .van-cell::after {
        border: none;
    }
}

.popupStyle {
    height: 100vh;
    width: 100vw;
    margin-top: -1px;

    &-top {
        display: flex;
        justify-content: space-between;

        &-icon {
            margin-top: 15px;
            margin-right: 10px
        }
    }
}

// /deep/.van-checkbox__icon--checked .van-icon {
//     background-color: #00c4b8;
//     border-color: #00c4b8;
// }

// /deep/.van-radio__icon--checked .van-icon {
//     background-color: #00c4b8;
//     border-color: #00c4b8;
// }</style>
