import { AuthDataService } from '/js/ApiDataServer/Auth.js?tf=202411121501';
import { UniversalDataService } from '/js/ApiDataServer/Universal.js?tf=202411131831';
import { OrderDataService } from '/js/ApiDataServer/Order.js?tf=202507260355';
import { StoreDataService } from '/js/ApiDataServer/Store.js';
import { PackingDataService } from '/js/ApiDataServer/Packing.js?tf=202411201826';
import { NotifyDataService } from '/js/ApiDataServer/Notify.js?tf=202501211855';
import { UserDataService } from '/js/ApiDataServer/User.js?tf=202501091214';
import { RESPONSE_STATUS } from '/js/constants.js';
import { enMessage } from '/js/constants.js';
import { Decorator } from '/js/util/dacorator.js?tf=202506251701';
import { StorageKey } from '/js/constants.js';
import { UJ } from '/js/util/uj.js';

let twzipcode;
let twzipcodeToTenant;
let twzipcodeToBill;
var vMain = new Vue({
    el: "#dvMain",
    data: function () {
        return {
            pageTitle: "訂單內容",
            authDesc: "訂單_訂單管理",
            isSystemManager: false,
            isLoading: false,
            isFinishRequest: false,
            isBindFancybox: true,
            ltPayMethod: [],
            ltPaymentStatus: [],
            ltShippingMethod: [],
            ltMarkets: [],
            ltStores: [],
            ltInvoiceTypes: [],
            ltBillTypes: [],
            orderObj: {
                id: -1,
                delivery: {},
                total: 0
            },
            modifyObj: {
                id: -1,
                delivery: {},
                invoice: {},
                details: {
                    list: [],
                    subTotal: 0,
                    consumableFee: 0,
                    deposit: 0,
                    depositRefund: 0,
                    freightage: 0,
                    suppliesTotal: 0,
                    additionsTotal: 0,
                    total: 0
                },
                others: {
                    list: [],
                    userBilling: {
                        freightage: 0,
                        repair: 0,
                        total: 0
                    },
                    storeBilling: {
                        freightage: 0,
                        repair: 0,
                        total: 0
                    },
                    total: 0
                },
                codFee: 0,
                total: 0
            },
            receipt: [],
            paymentRecords: [],
            paymentAmt: 0,
            invoiceAmt: 0,
            storeObj: {},
            contracts: [],
            ownerStore: {
                marketId: -1,
                marketName: "",
                storeId: -1,
                storeName: ""
            }
        };
    },
    components: {
        'date-picker': DatePicker
    },
    created: async function () {
        this.isSystemManager = await AuthDataService.IsSystemManager();
        this.modifyObj.id = UJ.getParameterByName("id");
        this.ltPayMethod = await UniversalDataService.GetOrderMainPayMethod();
        this.ltPaymentStatus = await UniversalDataService.GetPaymentStatus();
        this.ltShippingMethod = await UniversalDataService.GetShippingMethod();
        this.ltMarkets = await OrderDataService.GetMarketList();
        this.ltStores = await OrderDataService.GetMarketStoreList(-1);
        this.ltInvoiceTypes = await UniversalDataService.GetInvoiceType();
        this.ltBillTypes = await UniversalDataService.GetBillType();
        this.initAutocomplete();

        this.resetItem();
    },
    updated: function () {
        var v = this;
        if (!v.isBindFancybox) {
            bindFancybox();
            v.isBindFancybox = true;
        }

        initAdminutil();

        if (v.isFinishRequest) {
            setTimeout(function () {
                v.isLoading = false;
            }, 100);
        } else {
            v.isLoading = true;
        }
    },
    methods: {
        async resetItem() {
            var v = this;
            if (v.modifyObj.id != null && v.modifyObj.id > 0) {
                v.isFinishRequest = false;

                var res = await OrderDataService.Get(v.modifyObj.id);
                if (res.status == RESPONSE_STATUS.OK) {
                    v.modifyObj = res.data;
                    //Clone Obj
                    v.orderObj = $.extend(true, {}, res.data);
                    v.orderObj.createDate = Decorator.ChangeServerDateTimeToISODateTime(v.orderObj.createDatetime);
                    v.orderObj.modifyDate = Decorator.ChangeServerDateTimeToISODateTime(v.orderObj.modifyDatetime);
                    v.modifyObj.details.list.forEach(function (item) {
                        item.startDate = Decorator.ChangeISODateTimeToDate(item.startDate);
                        item.endDate = Decorator.ChangeISODateTimeToDate(item.endDate);
                    });

                    v.modifyObj.others.list.forEach(function (item) {
                        item.createDatetime = Decorator.ChangeServerDateTimeToISODateTime(item.createDatetime);
                        item.repaireDate = Decorator.ChangeISODateTimeToDate(item.repaireDate);
                        item.paymentDatetime = Decorator.ChangeISODateTimeToDate(item.paymentDatetime);
                    });

                    if (v.orderObj.enPayMethod == 100 || v.orderObj.enPayMethod == 300) {
                        v.receipt = await OrderDataService.GetReceiptList(v.orderObj.id);
                    }
                    v.paymentRecords = await OrderDataService.GetPaymentRecordList(v.orderObj.id);
                    if (v.paymentRecords != null && v.paymentRecords.length > 0) {
                        v.paymentRecords.forEach(function (item) {
                            v.paymentAmt += item.paymentAmount;
                            v.invoiceAmt += item.invoiceAmount;
                            item.paymentDate = Decorator.ChangeISODateTimeToDate(item.paymentDate);
                            item.invoiceDate = Decorator.ChangeISODateTimeToDate(item.invoiceDate);
                        });
                    }
                    v.contracts = await OrderDataService.GetContractList(v.orderObj.id);

                    v.getStore();

                    v.modifyObj.delivery.marketId = -1;
                    if (v.modifyObj.delivery.storeId > 0) {
                        v.ltStores.forEach(function (item) {
                            if (item.id == v.modifyObj.delivery.storeId) {
                                v.modifyObj.delivery.marketId = item.marketId;
                            }
                        });
                    }

                    if (v.orderObj.enStatus != 9999) {
                        v.zipcode('tenant');
                        v.zipcode('delivery');
                        v.zipcode('invoice');
                        setTimeout(function () {
                            v.toggleBTN('payMethod', v.modifyObj.enPayMethod);
                            v.toggleBTN('paymentStatus', v.modifyObj.enPaymentStatus);
                            v.toggleBTN('shippingMethod', v.modifyObj.enShippingMethod);
                            v.toggleBTN('invoiceType', v.modifyObj.invoice.enInvoiceType);
                            v.toggleBTN('billType', v.modifyObj.invoice.enBillType);
                            $(".changetype").fancybox({
                                focus: false
                            });
                        }, 100);
                    }

                    v.isBindFancybox = false;//重新綁定fancybox
                    v.isFinishRequest = true;
                    v.isLoading = false;

                } else {
                    var data = res.data;
                    showErrMsg(data.message, "", "", function () {
                        v.backToList();
                    });
                }
            } else {
                v.backToList();
            }
        },
        async getStore() {
            var v = this;
            if (v.modifyObj.ownerStoreId > 0) {
                var res = await StoreDataService.Get(v.modifyObj.ownerStoreId);
                if (res.status == RESPONSE_STATUS.OK) {
                    v.storeObj = res.data;
                    v.isFinishRequest = true;
                } else {
                    var data = res.data;
                    showErrMsg(data.message, "", "", function () {
                        if (data.enMessage == enMessage.NotFound) {
                            v.backToList();
                        }
                    });
                }
            }
            else {
                v.storeObj = {};
            }
        },
        zipcode(type) {
            var v = this;
            setTimeout(function () {
                if (type == "tenant") {
                    twzipcodeToTenant = new TWzipcodeFull(document.querySelectorAll('#twzipcodeToTenant'));
                    if (v.modifyObj.tenantZipCode == null || v.modifyObj.tenantZipCode.length == 0) {
                        v.modifyObj.tenantCounty = "";
                        v.modifyObj.tenantCity = "";
                        v.modifyObj.tenantZipCode = "";
                    }
                    twzipcodeToTenant.set(v.modifyObj.tenantZipCode);

                } else if (type == "delivery") {
                    twzipcode = new TWzipcode(document.querySelectorAll('#twzipcode'));
                    if (v.modifyObj.delivery.zipCode == null || v.modifyObj.delivery.zipCode.length == 0) {
                        v.modifyObj.delivery.county = "";
                        v.modifyObj.delivery.city = "";
                        v.modifyObj.delivery.zipCode = "";
                    }
                    twzipcode.set(v.modifyObj.delivery.zipCode);

                } else if (type == "invoice") {
                    twzipcodeToBill = new TWzipcodeFull(document.querySelectorAll('#twzipcodeToBill'));
                    if (v.modifyObj.invoice.zipCode == null || v.modifyObj.invoice.zipCode.length == 0) {
                        v.modifyObj.invoice.county = "";
                        v.modifyObj.invoice.city = "";
                        v.modifyObj.invoice.zipCode = "";
                    }
                    twzipcodeToBill.set(v.modifyObj.invoice.zipCode);
                }
            }, 100);
        },
        changeCity(type) {
            var v = this;
            setTimeout(function () {
                if (type == "tenant") {
                    let zipRes = twzipcodeToTenant.get();
                    v.modifyObj.tenantZipCode = zipRes.zipcode;
                } else if (type == "delivery") {
                    let zipRes = twzipcode.get();
                    v.modifyObj.delivery.zipCode = zipRes.zipcode;
                    v.calculate();
                } else if (type == "invoice") {
                    let zipRes = twzipcodeToBill.get();
                    v.modifyObj.invoice.zipCode = zipRes.zipcode;
                }
            }, 300);
        },
        async calculate() {
            var v = this;
            if (v.modifyObj.delivery.zipCode != v.orderObj.delivery.zipCode) {
                if (v.orderObj.enType == 100) {
                    let oObj = JSON.parse(JSON.stringify(v.modifyObj));
                    oObj.startDatetime = Decorator.ChangeISODateTimeToServerDateTime(oObj.startDatetime);
                    oObj.endDatetime = Decorator.ChangeISODateTimeToServerDateTime(oObj.endDatetime);
                    oObj.details.list.forEach(function (item) {
                        item.startDate = Decorator.ChangeISODateTimeToServerDateTime(item.startDate);
                        item.endDate = Decorator.ChangeISODateTimeToServerDateTime(item.endDate);
                    });

                    var res = await OrderDataService.Calculate(oObj);
                    if (res.status == RESPONSE_STATUS.OK) {
                        var obj = res.data;

                        v.modifyObj.details = obj.details;
                        v.modifyObj.details.list.forEach(function (item) {
                            item.startDate = Decorator.ChangeISODateTimeToDate(item.startDate);
                            item.endDate = Decorator.ChangeISODateTimeToDate(item.endDate);
                        });
                        v.modifyObj.subTotal = obj.subTotal;
                        v.modifyObj.freightage = obj.freightage;
                        v.modifyObj.consumableFee = obj.consumableFee;
                        v.modifyObj.deposit = obj.deposit;
                        v.modifyObj.total = obj.total;
                        v.modifyObj.freightAreaId = obj.freightAreaId;

                        v.isFinishRequest = true;
                    } else {
                        var data = res.data;
                        showErrMsg(data.message, "", "", function () {
                            if (data.enMessage == enMessage.NotFound) {
                                v.backToList();
                            }
                        });
                    }
                }
            }
        },
        isChange() {
            var v = this;
            if (v.orderObj.enShippingMethod != v.modifyObj.enShippingMethod) {
                return true;
            }
            if (v.orderObj.enShippingMethod == 200) {
                if (v.orderObj.delivery.zipCode != v.modifyObj.delivery.zipCode) {
                    return true;
                }
            }
            return false;
        },
        isChangeFreightage() {
            var v = this;
            return (v.orderObj.freightage != v.modifyObj.freightage);
        },
        toggleBTN(type, val) {
            var v = this;
            switch (type) {
                case "payMethod":
                    v.modifyObj.enPayMethod = val;
                    break;
                case "shippingMethod":
                    v.modifyObj.enShippingMethod = val;
                    v.calculate();
                    v.zipcode('delivery');
                    break;
                case "paymentStatus":
                    v.modifyObj.enPaymentStatus = val;
                    break;
                case "invoiceType":
                    v.modifyObj.invoice.enInvoiceType = val;
                    break;
                case "billType":
                    v.modifyObj.invoice.enBillType = val;
                    v.zipcode('invoice');
                    break;
            }

            ToggleBTN(type, val);
        },
        checkData() {
            var v = this;
            if (v.orderObj.enRentedFor == 100) {
                //承租人
                if (v.modifyObj.tenantName == null || v.modifyObj.tenantName.length == 0) {
                    alert("請填寫承租人姓名");
                    v.$refs.tenantname.focus();
                    return false;
                }
                if (v.orderObj.enSource != 200) {
                    //改為非必填，年紀稍長的客戶就沒辦法提供信箱，2025/04/22
                    if (v.modifyObj.email == null || v.modifyObj.email.length == 0) {
                        //alert("請填寫電子信箱!");
                        //v.$refs.email.focus();
                        //return false;
                    } else {
                        if (!v.modifyObj.email.isEmail()) {
                            alert("電子信箱格式有誤!");
                            v.$refs.email.focus();
                            return false;
                        }
                    }
                }
                if (v.modifyObj.tenantMobile == null || v.modifyObj.tenantMobile.length == 0) {
                    alert("請填寫承租人手機號碼");
                    v.$refs.tenantmobile.focus();
                    return false;
                } else {
                    if (!v.modifyObj.tenantMobile.isMobile()) {
                        alert("承租人手機號碼格式有誤!");
                        v.$refs.tenantmobile.focus();
                        return false;
                    }
                }
                if (v.orderObj.enSource != 200) {
                    if (v.modifyObj.tenantZipCode == null || v.modifyObj.tenantZipCode.length == 0) {
                        alert("請選擇承租人縣市");
                        v.$refs.tenantcounty.focus();
                        return false;
                    }
                    if (v.modifyObj.tenantAddress == null || v.modifyObj.tenantAddress.length == 0) {
                        alert("請填寫承租人聯絡地址");
                        v.$refs.tenantaddress.focus();
                        return false;
                    }
                }
                //使用人
                if (v.modifyObj.delivery.receiver == null || v.modifyObj.delivery.receiver.length == 0) {
                    alert("請填寫使用人姓名");
                    v.$refs.deliveryreceiver.focus();
                    return false;
                }
                if (v.modifyObj.tenantRelation == null || v.modifyObj.tenantRelation.length == 0) {
                    alert("請填寫為承租人之關係");
                    v.$refs.tenantrelation.focus();
                    return false;
                }
                if (v.modifyObj.delivery.mobile == null || v.modifyObj.delivery.mobile.length == 0) {
                    alert("請填寫使用人手機號碼");
                    v.$refs.deliverymobile.focus();
                    return false;
                } else {
                    if (!v.modifyObj.delivery.mobile.isMobile()) {
                        alert("使用人手機號碼格式有誤!");
                        v.$refs.deliverymobile.focus();
                        return false;
                    }
                }
            }

            if (v.modifyObj.enShippingMethod == 100) {
                if (v.orderObj.enSource != 200) {
                    if (v.modifyObj.delivery.storeId == -1 || v.modifyObj.delivery.storeId.length == 0) {
                        alert("請選擇取還門市");
                        v.$refs.deliverystoreid.focus();
                        return false;
                    }
                }
            } else if (v.modifyObj.enShippingMethod == 200) {
                if (v.modifyObj.delivery.zipCode == null || v.modifyObj.delivery.zipCode.length == 0) {
                    alert("請選擇運送縣市");
                    v.$refs.deliverycounty.focus();
                    return false;
                }
                if (v.modifyObj.delivery.address == null || v.modifyObj.delivery.address.length == 0) {
                    alert("請填寫運送地址");
                    v.$refs.deliveryaddress.focus();
                    return false;
                }
            }

            return true;
        },
        async updateOrder() {
            var v = this;
            if (v.checkData()) {
                v.isFinishRequest = false;
                v.isLoading = true;

                let oObj = JSON.parse(JSON.stringify(v.modifyObj));
                oObj.startDatetime = Decorator.ChangeISODateTimeToServerDateTime(oObj.startDatetime);
                oObj.endDatetime = Decorator.ChangeISODateTimeToServerDateTime(oObj.endDatetime);
                oObj.details.list.forEach(function (item) {
                    oObj.startDate = Decorator.ChangeISODateTimeToServerDateTime(oObj.startDate);
                    oObj.endDate = Decorator.ChangeISODateTimeToServerDateTime(oObj.endDate);
                });
                oObj.others.list.forEach(function (item) {
                    item.createDatetime = Decorator.ChangeISODateTimeToServerDateTime(item.createDatetime);
                    item.paymentDatetime = Decorator.ChangeISODateTimeToServerDateTime(item.paymentDatetime);
                });

                let res = await OrderDataService.Update(oObj);
                if (res.status == RESPONSE_STATUS.OK) {
                    showMsg('更新成功!', null, null, null, null, function () {
                        v.resetItem();
                        v.isFinishRequest = true;
                    });
                } else {
                    var data = res.data;
                    if (data.title != undefined) {
                        var errMsg = Object.keys(data.errors) + " is required.";
                        showErrMsg("", errMsg, "", null);
                    } else {
                        showErrMsg(data.message, "", "", null);
                    }
                    v.isFinishRequest = true;
                    v.isLoading = false;
                }
            }
        },
        deleteOrder() {
            var v = this;
            swal({
                title: "確定要刪除？",
                type: "question",
                showCancelButton: true,
                confirmButtonText: "確定",
                cancelButtonText: "取消"
            }).then(result => {
                if (result.value) {
                    v.delete();
                }
            });
        },
        async delete() {
            var v = this;
            v.isFinishRequest = false;
            v.isLoading = true;

            let res = await OrderDataService.Delete(this.modifyObj.id);
            if (res.status == RESPONSE_STATUS.OK) {
                showMsg('刪除成功!', null, null, null, null, function () {
                    v.backToList();
                });
            } else {
                var data = res.data;
                showErrMsg(data.message, "", "", function () {
                    if (data.enMessage == enMessage.NotFound) {
                        v.backToList();
                    }
                });
                v.isFinishRequest = true;
                v.isLoading = false;
            }
        },
        removeDetail(item) {
            var v = this;
            swal({
                title: "確定要刪除？",
                type: "question",
                showCancelButton: true,
                confirmButtonText: "確定",
                cancelButtonText: "取消"
            }).then(async function (result) {
                if (result.value) {
                    v.isFinishRequest = false;
                    v.isLoading = true;

                    let res = await OrderDataService.DeleteDetail(item.id);
                    if (res.status == RESPONSE_STATUS.OK) {
                        showMsg('刪除成功!', null, null, null, null, function () {
                            v.resetItem();
                        });
                    } else {
                        var data = res.data;
                        showErrMsg(data.message, "", "", function () {
                            if (data.enMessage == enMessage.NotFound) {
                                v.resetItem();
                            }
                        });
                        v.isFinishRequest = true;
                        v.isLoading = false;
                    }
                }
            });
        },
        removeOther(item) {
            var v = this;
            swal({
                title: "確定要刪除？",
                type: "question",
                showCancelButton: true,
                confirmButtonText: "確定",
                cancelButtonText: "取消"
            }).then(async function (result) {
                if (result.value) {
                    v.isFinishRequest = false;
                    v.isLoading = true;

                    let res = await OrderDataService.DeleteOther(item.id);
                    if (res.status == RESPONSE_STATUS.OK) {
                        showMsg('刪除成功!', null, null, null, null, function () {
                            v.resetItem();
                        });
                    } else {
                        var data = res.data;
                        showErrMsg(data.message, "", "", function () {
                            if (data.enMessage == enMessage.NotFound) {
                                v.resetItem();
                            }
                        });
                        v.isFinishRequest = true;
                        v.isLoading = false;
                    }
                }
            });
        },
        sendPayEmail(mail) {
            var v = this;
            if (mail == null || mail.length == 0) {
                alert("請填寫收件信箱");
                v.$refs.notifyEmail.focus();
                return false;
            }

            swal({
                title: "確定要寄出付款通知信？",
                html: "Mail To: " + mail,
                type: "question",
                showCancelButton: true,
                confirmButtonText: "確定",
                cancelButtonText: "取消"
            }).then(async function (result) {
                if (result.value) {
                    v.isFinishRequest = false;
                    v.isLoading = true;

                    await NotifyDataService.SendPaymentMail({
                        receiver: mail,
                        orderId: v.orderObj.id
                    });
                    showMsg('通知信已寄出!', null, null, null, null, null);
                    v.isFinishRequest = true;
                    v.isLoading = false;
                }
            });
        },
        sendPaySMS(mobile) {
            var v = this;
            if (mobile == null || mobile.length == 0) {
                alert("請填寫手機號碼");
                v.$refs.notifyMobile.focus();
                return false;
            }

            swal({
                title: "確定要發送付款通知簡訊？",
                html: "發送簡訊給: " + mobile,
                type: "question",
                showCancelButton: true,
                confirmButtonText: "確定",
                cancelButtonText: "取消"
            }).then(async function (result) {
                if (result.value) {
                    v.isFinishRequest = false;
                    v.isLoading = true;

                    await NotifyDataService.SendPaymentSMS({
                        receiver: mobile,
                        orderId: v.orderObj.id
                    });
                    showMsg('簡訊已發送!', null, null, null, null, null);
                    v.isFinishRequest = true;
                    v.isLoading = false;
                }
            });
        },
        triggerUpload(obj) {
            $(obj).trigger("click");
        },
        onFileChange(e) {//合約上傳
            var files = e.target.files || e.dataTransfer.files;
            if (!files.length) return;
            var type = e.target.id.replace(/fu/g, '').toLowerCase();
            this.uploadImg(files[0], e, type);
        },
        async uploadImg(f, e, type) {
            //自動上傳
            var v = this;
            v.isFinishRequest = false;
            v.isLoading = true;
            var fData = new FormData();
            fData.append("files", f);
            fData.append("type", type);
            fData.append("orderId", v.orderObj.id);

            let res = await OrderDataService.UploadImage(fData);
            if (res.status != RESPONSE_STATUS.OK) {
                var data = res.data;
                if (res.httpStatus === 401) {
                    showErrMsg(data.message, "", "", null);
                } else {
                    showErrMsg('上傳失敗!!', "", "", null);
                }
                v.resetFile(type);
                return;
            }
            else {
                alert('上傳完成.');
                if (type == "contract") {
                    v.contracts = await OrderDataService.GetContractList(v.orderObj.id);
                } else if (type == "receipt") {
                    v.receipt = await OrderDataService.GetReceiptList(v.orderObj.id);
                }

                v.resetFile(type);
            }
        },
        resetFile(type) {
            if (type == "contract") {
                const input = this.$refs.fuContract;
                input.type = 'text';
                input.type = 'file';

            } else if (type == "receipt") {
                const input = this.$refs.fuReceipt;
                input.type = 'text';
                input.type = 'file';
            }
            this.isLoading = false;
            this.isFinishRequest = true;
            this.isBindFancybox = false;//重新綁定fancybox
        },
        async deleteReceipt(item, idx) {
            if (!confirm("確定要刪除？")) {
                return false;
            } else {
                var v = this;
                let res = await OrderDataService.DeleteReceipt(item.id);
                if (res.status == RESPONSE_STATUS.OK) {
                    alert('刪除成功!');
                    v.receipt.splice(idx, 1);
                } else {
                    var data = res.data;
                    showErrMsg(data.message, "", "", async function () {
                        if (data.enMessage == enMessage.NotFound) {
                            v.receipt = await OrderDataService.GetReceiptList(v.orderObj.id);
                        }
                    });
                }
            }
        },
        async deleteContract(item, idx) {
            if (!confirm("確定要刪除？")) {
                return false;
            } else {
                var v = this;
                let res = await OrderDataService.DeleteContract(item.id);
                if (res.status == RESPONSE_STATUS.OK) {
                    alert('刪除成功!');
                    v.contracts.splice(idx, 1);
                } else {
                    var data = res.data;
                    showErrMsg(data.message, "", "", async function () {
                        if (data.enMessage == enMessage.NotFound) {
                            v.contracts = await OrderDataService.GetContractList(v.orderObj.id);
                        }
                    });
                }
            }
        },
        transToInquiry() {
            var v = this;
            swal({
                title: "確定要轉回詢問單？",
                type: "question",
                showCancelButton: true,
                confirmButtonText: "確定",
                cancelButtonText: "取消"
            }).then(async function (result) {
                if (result.value) {
                    v.isFinishRequest = false;
                    v.isLoading = true;

                    let res = await OrderDataService.TransToInquiry(v.modifyObj.id);
                    if (res.status == RESPONSE_STATUS.OK) {
                        showMsg('已轉回詢問單!', null, null, null, null, function () {
                            location.href = "inquiryedit?id=" + v.modifyObj.id;
                        });
                    } else {
                        var data = res.data;
                        if (data.title != undefined) {
                            var errMsg = Object.keys(data.errors) + " is required.";
                            showErrMsg("", errMsg, "", null);
                        } else {
                            showErrMsg(data.message, "", "", null);
                        }
                        v.isFinishRequest = true;
                        v.isLoading = false;
                    }
                }
            });
        },
        transToBeShipped() {
            var v = this;
            swal({
                title: "確定轉 [待出貨]？",
                html: "轉為待出貨狀態",
                type: "question",
                showCancelButton: true,
                confirmButtonText: "確定",
                cancelButtonText: "取消"
            }).then(async function (result) {
                if (result.value) {
                    if (v.checkData()) {
                        v.isFinishRequest = false;
                        v.isLoading = true;

                        let res = await OrderDataService.TransToShip(v.modifyObj.id);
                        if (res.status == RESPONSE_STATUS.OK) {
                            var list = res.data;
                            v.isFinishRequest = true;
                            v.isLoading = false;
                            var packingNums = [];
                            list.forEach(function (obj) {
                                packingNums.push(obj.packingNum);
                            });
                            v.getPacking(packingNums);

                        } else {
                            var data = res.data;
                            if (data.title != undefined) {
                                var errMsg = Object.keys(data.errors) + " is required.";
                                showErrMsg("", errMsg, "", null);
                            } else {
                                showErrMsg(data.message, "", "", null);
                            }
                            v.isFinishRequest = true;
                            v.isLoading = false;
                        }
                    }
                }
            });
        },
        async getPacking(packingNums) {
            var v = this;
            v.isLoading = true;

            let res = await PackingDataService.GetShipList({
                ltPackingNums: packingNums,
                packingStatuss: -1,
                oemMarketId: -1,
                currentPage: 1,
                pageSize: 20
            });
            if (res.status == RESPONSE_STATUS.OK) {
                var data = res.data;
                data.list.forEach(function (item) {
                    item.scheduleDate = Decorator.ChangeISODateTimeToDate(item.scheduleDate);
                    item.qcDate = Decorator.ChangeISODateTimeToDate(item.qcDate);
                    item.shippingDate = Decorator.ChangeISODateTimeToDate(item.shippingDate);
                    item.receivedDate = Decorator.ChangeISODateTimeToDate(item.receivedDate);
                    item.orderDetails.forEach(function (obj) {
                        obj.startDate = Decorator.ChangeISODateTimeToDate(obj.startDate);
                        obj.endDate = Decorator.ChangeISODateTimeToDate(obj.endDate);

                        var sd = new Date(obj.startDate);
                        var ed = new Date(obj.endDate);
                        if (sd.getFullYear() != ed.getFullYear()) {
                            obj.startDateShort = Decorator.ChangeISODateTimeToYYMMdd(obj.startDate);
                            obj.endDateShort = Decorator.ChangeISODateTimeToYYMMdd(obj.endDate);
                        } else {
                            obj.startDateShort = Decorator.ChangeISODateTimeToMMdd(obj.startDate);
                            obj.endDateShort = Decorator.ChangeISODateTimeToMMdd(obj.endDate);
                        }
                    });
                    item.ownerStoreName = "";
                });
                v.isLoading = false;

                UJ.SaveStorage(StorageKey.shipqcOrder + v.modifyObj.orderNum + "_", data.list);
                $("#hlkPacking").prop("href", '_shipqc?orn=' + v.modifyObj.orderNum);
                $("#hlkPacking").trigger("click");

            } else {
                var data = res.data;
                if (res.httpStatus === 401) {
                    showErrMsg('訂單已轉為待出貨!', "請前往出貨管理進行出貨品管.", "", function () {
                        v.resetItem();
                    });
                } else {
                    showErrMsg(data.message, "", "", null);
                    v.isFinishRequest = true;
                }
            }
        },
        transToRenew() {
            var v = this;
            swal({
                title: "確定轉 [續租]？",
                html: "訂單轉為續租狀態",
                type: "question",
                showCancelButton: true,
                confirmButtonText: "確定",
                cancelButtonText: "取消"
            }).then(async function (result) {
                if (result.value) {
                    if (v.checkData()) {
                        v.isFinishRequest = false;
                        v.isLoading = true;

                        let res = await OrderDataService.TransToRenew(v.modifyObj.id);
                        if (res.status == RESPONSE_STATUS.OK) {
                            showMsg('更新成功!', null, null, null, null, function () {
                                v.resetItem();
                            });
                        } else {
                            var data = res.data;
                            if (data.title != undefined) {
                                var errMsg = Object.keys(data.errors) + " is required.";
                                showErrMsg("", errMsg, "", null);
                            } else {
                                showErrMsg(data.message, "", "", null);
                            }
                            v.isFinishRequest = true;
                            v.isLoading = false;
                        }
                    }

                }
            });
        },
        pauseOrder() {
            var v = this;
            swal({
                title: "確定要轉待通知訂單？",
                html: "訂單暫停，待客戶通知再啟用租借。",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "確定",
                cancelButtonText: "取消"
            }).then(async function (result) {
                if (result.value) {
                    v.isFinishRequest = false;
                    v.isLoading = true;

                    let res = await OrderDataService.PauseOrder(v.modifyObj.id);
                    if (res.status == RESPONSE_STATUS.OK) {
                        showMsg('更新成功!', null, null, null, null, function () {
                            v.resetItem();
                            CloseFancyBox();
                        });
                    } else {
                        var data = res.data;
                        if (data.title != undefined) {
                            var errMsg = Object.keys(data.errors) + " is required.";
                            showErrMsg("", errMsg, "", null);
                        } else {
                            showErrMsg(data.message, "", "", null);
                        }
                        v.isFinishRequest = true;
                        v.isLoading = false;
                    }
                } else {
                    CloseFancyBox();
                }
            });
        },
        restoreOrder() {
            var v = this;
            swal({
                title: "確定要恢復訂單？",
                html: "訂單繼續，客戶通知啟用租借。",
                type: "question",
                showCancelButton: true,
                confirmButtonText: "確定",
                cancelButtonText: "取消"
            }).then(async function (result) {
                if (result.value) {
                    v.isFinishRequest = false;
                    v.isLoading = true;

                    let res = await OrderDataService.RestoreOrder(v.modifyObj.id);
                    if (res.status == RESPONSE_STATUS.OK) {
                        showMsg('訂單已恢復!', null, null, null, null, function () {
                            v.resetItem();
                            CloseFancyBox();
                        });
                    } else {
                        var data = res.data;
                        if (data.title != undefined) {
                            var errMsg = Object.keys(data.errors) + " is required.";
                            showErrMsg("", errMsg, "", null);
                        } else {
                            showErrMsg(data.message, "", "", null);
                        }
                        v.isFinishRequest = true;
                        v.isLoading = false;
                    }
                } else {
                    CloseFancyBox();
                }
            });
        },
        closedOrder() {
            var v = this;
            swal({
                title: "訂單確定要轉已結案？",
                html: "結束訂單",
                type: "question",
                showCancelButton: true,
                confirmButtonText: "確定",
                cancelButtonText: "取消"
            }).then(async function (result) {
                if (result.value) {
                    v.isFinishRequest = false;
                    v.isLoading = true;

                    let res = await OrderDataService.ClosedOrder(v.modifyObj.id);
                    if (res.status == RESPONSE_STATUS.OK) {
                        showMsg('訂單已結案!', null, null, null, null, function () {
                            v.resetItem();
                            v.closeFancyBox();
                        });
                    } else {
                        var data = res.data;
                        if (data.title != undefined) {
                            var errMsg = Object.keys(data.errors) + " is required.";
                            showErrMsg("", errMsg, "", null);
                        } else {
                            showErrMsg(data.message, "", "", null);
                        }
                        v.isFinishRequest = true;
                        v.isLoading = false;
                        v.closeFancyBox();
                    }
                } else {
                    v.closeFancyBox();
                }
            });
        },
        allowAddProduct() {
            var v = this;
            if (v.orderObj.enSource == 200) {
                if (v.orderObj.enStatus < 300) {
                    return true;
                }
            } else {
                if (v.orderObj.enStatus == 100) {
                    return true;
                }
            }
            return false;
        },
        allowAppendProduct() {
            var v = this;
            if (v.orderObj.enSource == 200) {
                if (v.orderObj.enStatus == 300 || v.orderObj.enStatus == 400) {
                    return true;
                }
            }
            return false;
        },
        trCss(item) {
            if (item.enStatus == 700) {
                if (Decorator.ChangeStringToDate(item.endDate).getTime() < new Date().setHours(0, 0, 0, 0)) {
                    return "bg-expired";
                } else {
                    return "bg-running";
                }
            }
            if (item.enStatus == 800) return "bg-running";
            if (item.enStatus == 900) return "bg-closed";
            if (item.enStatus == 9999) return "bg-closed";
            return "";
        },
        statusCss(item) {
            if (item.enStatus == 500) return "order-pause";
            if (item.enStatus < 700) return "order-pending";
            if (item.enStatus == 700 || item.enStatus == 800) return "order-running";
            if (item.enStatus == 900) return "order-expired";
            if (item.enStatus == 9999) return "order-closed";
            return "";
        },
        orderCss() {
            var v = this;
            if (v.modifyObj.enStatus == 500) return "order-pause";
            if (v.modifyObj.enStatus <= 600) return "order-pending";
            if (v.modifyObj.enStatus == 700) return "order-running";
            if (v.modifyObj.enStatus == 9999) return "order-closed";
            return "";
        },
        showPauseOrderBtn() {
            var v = this;
            var res = false;
            if (v.orderObj.enStatus < 500) {
                res = true;
                v.orderObj.details.list.forEach(function (item) {
                    if (item.enStatus > 500) {
                        res = false;
                    }
                });
            }
            return res;
        },
        showDeleteOrderBtn() {
            var v = this;
            var res = false;
            if (v.orderObj.enStatus < 600) {
                if (v.orderObj.enStatus == 500) {
                    res = true;
                } else {
                    if (v.orderObj.details.list.length + v.orderObj.others.list.length == 0) {
                        res = true;
                    } else {
                        res = true;
                        v.orderObj.details.list.forEach(function (item) {
                            if (item.enStatus > 500) {
                                res = false;
                            }
                        });
                    }
                }
            }
            return res;
        },
        closeFancyBox() {
            try {
                parent.$.fancybox.close();
            }
            catch (e) {
                top.$.fancybox.close();
            }
        },
        changeOwnerStore(isAblh) {
            var v = this;
            var isValid = true;
            if (!isAblh) {
                if (v.ownerStore.storeId == null || v.ownerStore.storeId.length == 0 || v.ownerStore.storeId <= 0) {
                    alert("請選擇要變更的通路&門市!");
                    isValid = false;
                }
            }

            if (!isValid) {
                return false;
            }
            else {
                var title = "";
                var html = "";
                if (isAblh) {
                    title = "確定轉為佳醫訂單";
                    v.ownerStore.storeId = -1;
                } else {
                    title = "訂單確定儲存變更？儲存為";
                    html = "<h3>" + v.ownerStore.marketName + "</h3>" + "<h3>" + v.ownerStore.storeName + "</h3>";
                }
                swal({
                    title: title,
                    html: html,
                    type: "question",
                    showCancelButton: true,
                    confirmButtonText: "確定",
                    cancelButtonText: "取消"
                }).then(async function (result) {
                    if (result.value) {
                        v.isFinishRequest = false;
                        v.isLoading = true;

                        let res = await UserDataService.ChangeOwnerStore({
                            orderIds: [v.orderObj.id],
                            userId: v.orderObj.userId,
                            storeId: v.ownerStore.storeId
                        });
                        if (res.status == RESPONSE_STATUS.OK) {
                            showMsg('更新成功!', null, null, null, null, function () {
                                v.ownerStore.marketId = -1;
                                v.ownerStore.marketName = "";
                                $('#query-market').val('');
                                v.ownerStore.storeId = -1;
                                v.ownerStore.storeName = "";
                                $('#query-store').val('');
                                v.closeFancyBox();
                                v.resetItem();
                            });
                        } else {
                            var data = res.data;
                            if (data.title != undefined) {
                                var errMsg = Object.keys(data.errors) + " is required.";
                                showErrMsg("", errMsg, "", null);
                            } else {
                                showErrMsg(data.message, "", "", null);
                            }
                            v.isFinishRequest = true;
                            v.isLoading = false;
                        }
                    }
                });
            }
        },
        initAutocomplete() {
            var v = this;
            //setting autocomplete
            $('#query-market').autocomplete({
                minLength: 0,
                delay: 50, //延遲
                source: (request, response) => {
                    var markets = v.ltMarkets.filter(function (item) {
                        return item.name.toLowerCase().indexOf(request.term.toLowerCase()) > -1;
                    });

                    response($.map(markets, function (item) {
                        return {
                            // label和value是基本參數
                            label: `${item.name}`,  //列表所顯示的文字
                            value: item.name,  	//列表選項的值
                            id: item.id
                        };
                    }));
                },
                select: function (event, ui) {
                    //選取
                    v.ownerStore.marketId = ui.item.id;
                    v.ownerStore.marketName = ui.item.label;

                    if (v.ownerStore.storeName.trim().length > 0) {
                        var stores = v.ltStores.filter(function (item) {
                            if (v.ownerStore.marketId < 0 || (v.ownerStore.marketId > 0 && item.marketId == v.ownerStore.marketId)) {
                                return (v.ownerStore.storeName.toLowerCase().indexOf(item.name.toLowerCase()) > -1) ||
                                    (item.shortName != null && item.shortName != '' && v.ownerStore.storeName.toLowerCase().indexOf(item.shortName.toLowerCase()) > -1);
                            }
                        });

                        if (stores.length == 0) {
                            v.ownerStore.storeId = -1;
                            v.ownerStore.storeName = "";
                            $('#query-store').val('');
                        }
                    }
                },
                change: function (event, ui) {
                    //清空輸入框
                    if (ui.item == null) {
                        v.ownerStore.marketId = -1;
                        v.ownerStore.marketName = "";
                    }
                }
            }).focus(function () {
                //點輸入框就秀出下拉選單
                $(this).trigger("keydown");
            }).change(function () {
                if ($(this).val().trim() == '' || $(this).val() == '') {
                    v.ownerStore.marketId = -1;
                    v.ownerStore.marketName = "";
                }
            }).data("ui-autocomplete")._renderItem = function (ul, item) {
                return $("<li>")
                    .addClass("multiline-label")
                    .append("<div>" + item.label + "</div>")
                    .appendTo(ul);
            };

            //setting autocomplete
            $('#query-store').autocomplete({
                minLength: 0,
                delay: 50, //延遲
                source: (request, response) => {
                    var stores = v.ltStores.filter(function (item) {
                        if (v.ownerStore.marketId < 0 || (v.ownerStore.marketId > 0 && item.marketId == v.ownerStore.marketId)) {
                            return (item.name.toLowerCase().indexOf(request.term.toLowerCase()) > -1) ||
                                (item.shortName != null && item.shortName != '' && item.shortName.toLowerCase().indexOf(request.term.toLowerCase()) > -1);
                        }
                    });

                    if (request.term.trim().length > 0 && stores.length == 0) {
                        v.ownerStore.storeId = -1;
                        v.ownerStore.storeName = "";
                        $('#query-store').val('');
                    }

                    response($.map(stores, function (item) {
                        var name = item.name;
                        if (item.shortName != null && item.shortName != '') { name += "(" + item.shortName + ")"; }
                        return {
                            // label和value是基本參數
                            label: `${name}`,  //列表所顯示的文字
                            value: name,  	//列表選項的值
                            id: item.id
                        };
                    }));
                },
                select: function (event, ui) {
                    //選取
                    v.ownerStore.storeId = ui.item.id;
                    v.ownerStore.storeName = ui.item.label;
                },
                change: function (event, ui) {
                    //清空輸入框
                    if (ui.item == null) {
                        v.ownerStore.storeId = -1;
                        v.ownerStore.storeName = "";
                    }
                }
            }).focus(function () {
                //點輸入框就秀出下拉選單
                $(this).trigger("keydown");
            }).change(function () {
                if ($(this).val().trim() == '' || $(this).val() == '') {
                    v.ownerStore.storeId = -1;
                    v.ownerStore.storeName = "";
                    v.getList();
                }
            }).data("ui-autocomplete")._renderItem = function (ul, item) {
                return $("<li>")
                    .addClass("multiline-label")
                    .append("<div>" + item.label + "</div>")
                    .appendTo(ul);
            };


            //點輸入框或右側箭頭就秀出下拉選單
            $(".autocomplete").click(function (item) {
                var obj = $(this).children('input').eq(0);
                $(obj).trigger("keydown");
            });
        },
        closeFancyBox() {
            try {
                parent.$.fancybox.close();
            }
            catch (e) {
                top.$.fancybox.close();
            }
        },
        backToList() {
            var page = "";
            if (UJ.getParameterByName("p") != null) {
                page = "?p=" + UJ.getParameterByName("p");
            }

            var source = UJ.getParameterByName("s");
            if (source != null && source == "dl") {
                location.href = 'detaillist' + page;
            } else if (source != null && source == "sl") {
                location.href = 'shiplist' + page;
            } else {
                location.href = 'orderlist' + page;
            }
        }
    }
});


$(function () {
    setTimeout(function () {
        var source = UJ.getParameterByName("s");
        if (source != null && source == "dl") {
            openLeftMenu('/order/detaillist');
        } else {
            openLeftMenu('/order/orderlist');
        }
    }, 100);
});