import { AuthDataService } from '/js/ApiDataServer/Auth.js?tf=202411121501';
import { UniversalDataService } from '/js/ApiDataServer/Universal.js?tf=202411131831';
import { PackingSaleOrderDataService } from '/js/ApiDataServer/PackingSaleOrder.js';
import { RESPONSE_STATUS } from '/js/constants.js';
import { Decorator } from '/js/util/dacorator.js';
import { StorageKey } from '/js/constants.js?tf=202503201821';
import { enMessage } from '/js/constants.js';
import { UJ } from '/js/util/uj.js';

let twzipcode;
let twzipcodeToBill;
var vMain = new Vue({
    el: "#dvMain",
    data: function () {
        return {
            pageTitle: "佳醫銷售出貨單",
            authDesc: "訂單_出貨管理",
            isSystemManager: false,
            isLoading: false,
            isFinishRequest: true,
            isBindFancybox: true,
            memberObj: {},
            ltPayMethod: [],
            ltPaymentStatus: [],
            ltInvoiceTypes: [],
            ltBillTypes: [],
            modifyObj: {
                id: -1,
                shippingDate: "",
                delivery: {
                    zipCode: "",
                    county: "",
                    city: "",
                    address: "",
                },
                totalPrice: 0,
                enPayMethod: -1,
                enPaymentStatus: -1,
                paymentDatetime: "",
                invoice: {
                    enInvoiceType: -1,
                    enBillType: -1,
                    zipCode: "",
                    county: "",
                    city: "",
                    address: ""
                },
                details: []
            },
            originalObj: {},
            packingObj: {
                id: -1,
                enStatus: 100
            }
        };
    },
    created: async function () {
        var v = this;
        var res = await AuthDataService.Me();
        if (res.status == RESPONSE_STATUS.OK) {
            v.memberObj = res.data;
            v.isSystemManager = v.memberObj.isSystemManager;

            v.ltPayMethod = await UniversalDataService.GetOrderMainPayMethod();
            v.ltPaymentStatus = await UniversalDataService.GetPaymentStatus();
            v.ltInvoiceTypes = await UniversalDataService.GetInvoiceType();
            v.ltBillTypes = await UniversalDataService.GetBillType();

            v.modifyObj.id = UJ.getParameterByName("id");
            v.resetItem();
        } else {
            var data = res.data;
            if (data.enMessage == enMessage.NotLogin) {
                await AuthDataService.Logout();
                location.href = '/';
            }
        }
    },
    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;
        }
    },
    components: {
        'date-picker': DatePicker
    },
    methods: {
        clearStorage() {
            UJ.ResetStorage(StorageKey.packingCreateOrder);
            UJ.ResetStorage(StorageKey.packingCreateOrderDetails);
            UJ.ResetStorage(StorageKey.packingCreateOrderStocks);
        },
        async resetItem() {
            var v = this;
            if (v.modifyObj.id != null && v.modifyObj.id > 0) {
                v.isFinishRequest = false;

                var res = await PackingSaleOrderDataService.GetOrder(v.modifyObj.id);
                if (res.status == RESPONSE_STATUS.OK) {
                    v.modifyObj = res.data;
                    v.modifyObj.shippingDate = Decorator.ChangeISODateTimeToDate(v.modifyObj.shippingDate);
                    v.modifyObj.paymentDatetime = Decorator.ChangeISODateTimeToDate(v.modifyObj.paymentDatetime);
                    v.modifyObj.createDate = Decorator.ChangeServerDateTimeToISODateTime(v.modifyObj.createDatetime);
                    v.modifyObj.modifyDate = Decorator.ChangeServerDateTimeToISODateTime(v.modifyObj.modifyDatetime);
                    //Clone Obj
                    v.originalObj = $.extend(true, {}, v.modifyObj);

                    v.packingObj = await PackingSaleOrderDataService.GetPackingByOrderId(v.modifyObj.id);

                    v.isFinishRequest = true;
                    v.isLoading = false;
                    v.isBindFancybox = false;//重新綁定fancybox
                } else {
                    var data = res.data;
                    showErrMsg(data.message, "", "", function () {
                        if (data.enMessage == enMessage.NotFound) {
                            v.backToList();
                        }
                    });
                }
            } else {
                v.isFinishRequest = true;
                v.isLoading = false;
                v.modifyObj.id = -v.memberObj.id;
            }

            var storageObj = UJ.GetStorage(StorageKey.packingCreateOrder + v.modifyObj.id + "_");
            if (storageObj != null) {
                v.modifyObj = storageObj;
            }

            var addressInfo = UJ.GetStorage(StorageKey.packingCreateOrderAddressInfo + v.modifyObj.id + "_");
            if (addressInfo != null) {
                v.modifyObj.shippingDate = addressInfo.shippingDate;
                v.modifyObj.delivery = $.extend(true, {}, addressInfo.delivery);
                v.modifyObj.invoice = $.extend(true, {}, addressInfo.invoice);
                v.modifyObj.enPayMethod = addressInfo.enPayMethod;
                UJ.ResetStorage(StorageKey.packingCreateOrderAddressInfo);
            }

            var storageDetails = UJ.GetStorage(StorageKey.packingCreateOrderDetails + v.modifyObj.id + "_");
            if (storageDetails != null) {
                if (v.modifyObj.details == null || v.modifyObj.details.length == 0) { v.modifyObj.details = []; }
                v.modifyObj.details = storageDetails;
            }

            setTimeout(function () {
                v.zipcode('delivery');
                v.zipcode('invoice');
                if (v.modifyObj.enPayMethod > 0) { v.toggleBTN('payMethod', v.modifyObj.enPayMethod); }
                if (v.modifyObj.enPaymentStatus > 0) { v.toggleBTN('paymentStatus', v.modifyObj.enPaymentStatus); }
                if (v.modifyObj.invoice.enInvoiceType > 0) { v.toggleBTN('invoiceType', v.modifyObj.invoice.enInvoiceType); }
                if (v.modifyObj.invoice.enBillType > 0) { v.toggleBTN('billType', v.modifyObj.invoice.enBillType); }
            }, 100);
        },
        zipcode(type) {
            var v = this;
            setTimeout(function () {
                if (type == "delivery") {
                    twzipcode = new TWzipcodeFull(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 == "delivery") {
                    let zipRes = twzipcode.get();
                    v.modifyObj.delivery.zipCode = zipRes.zipcode;
                } else if (type == "invoice") {
                    let zipRes = twzipcodeToBill.get();
                    v.modifyObj.invoice.zipCode = zipRes.zipcode;
                }
            }, 300);
        },
        toggleBTN(type, val) {
            var v = this;
            switch (type) {
                case "payMethod":
                    v.modifyObj.enPayMethod = val;
                    break;
                case "paymentStatus":
                    v.modifyObj.enPaymentStatus = val;
                    break;
                case "invoiceType":
                    v.modifyObj.invoice.enInvoiceType = val;
                    if (v.modifyObj.invoice.enInvoiceType == 200) {
                        v.toggleBTN('billType', 100);
                    }
                    break;
                case "billType":
                    v.modifyObj.invoice.enBillType = val;
                    v.zipcode('invoice');
                    break;
            }

            ToggleBTN(type, val);
        },
        showProductList() {
            var v = this;
            UJ.SaveStorage(StorageKey.packingCreateOrder + v.modifyObj.id + "_", v.modifyObj);
            UJ.SaveStorage(StorageKey.packingCreateOrderDetails + v.modifyObj.id + "_", v.modifyObj.details);
            var stocks = [];
            v.modifyObj.details.forEach(function (detail) {
                detail.stocks.forEach(function (stock) {
                    stocks.push(stock);
                });
            });
            UJ.SaveStorage(StorageKey.packingCreateOrderStocks + v.modifyObj.id + "_", stocks);
        },
        checkData() {
            var v = this;
            //收件資訊
            if (v.modifyObj.shippingDate == null || v.modifyObj.shippingDate == "") {
                alert("請輸入預計出貨日!");
                $("#shippingDate").focus();
                return false;
            }
            if (v.modifyObj.delivery.receiver == null || v.modifyObj.delivery.receiver == "") {
                alert("請填寫收件人姓名");
                v.$refs.deliveryreceiver.focus();
                return false;
            }
            if (v.modifyObj.delivery.mobile == null || v.modifyObj.delivery.mobile == "") {
                alert("請填寫收件人電話");
                v.$refs.deliverymobile.focus();
                return false;
            }
            if (v.modifyObj.delivery.zipCode == null || v.modifyObj.delivery.zipCode.length == 0) {
                alert("請選擇收件人縣市");
                return false;
            }
            if (v.modifyObj.delivery.address == null || v.modifyObj.delivery.address.length == 0) {
                alert("請填寫收件人地址!");
                v.$refs.deliveryaddress.focus();
                return false;
            }
            //發票資訊
            if (v.modifyObj.enPayMethod <= 0 || v.modifyObj.enPayMethod.length == 0) {
                alert("請選擇付款方式");
                return false;
            }
            if (v.modifyObj.enPaymentStatus <= 0 || v.modifyObj.enPaymentStatus.length == 0) {
                alert("請選擇付款狀態");
                return false;
            } else {
                //已付款
                if (v.modifyObj.enPaymentStatus == 300) {
                    if (v.modifyObj.paymentDatetime == null || v.modifyObj.paymentDatetime.length == 0) {
                        alert("請填寫付款日期!");
                        $("#paymentDatetime").focus();
                        return false;
                    }
                }
            }
            if (v.modifyObj.invoice.enInvoiceType <= 0 || v.modifyObj.invoice.enInvoiceType.length == 0) {
                alert("請選擇發票格式");
                return false;
            } else {
                if (v.modifyObj.invoice.enInvoiceType == 200) {
                    if (v.modifyObj.invoice.invoiceTaxNo == null || v.modifyObj.invoice.invoiceTaxNo.length == 0) {
                        alert("請填寫統一編號");
                        v.$refs.invoiceTaxNo.focus();
                        return false;
                    }
                    if (v.modifyObj.invoice.invoiceTitle == null || v.modifyObj.invoice.invoiceTitle.length == 0) {
                        alert("請填寫公司名稱");
                        v.$refs.invoiceTitle.focus();
                        return false;
                    }
                }
            }
            if (v.modifyObj.invoice.enBillType <= 0 || v.modifyObj.invoice.enBillType.length == 0) {
                alert("請選擇索取方式");
                return false;
            } else {
                if (v.modifyObj.invoice.enBillType == 100) {
                    if (v.modifyObj.invoice.receiver == null || v.modifyObj.invoice.receiver.length == 0) {
                        alert("請填寫收件姓名");
                        v.$refs.invoiceReceiver.focus();
                        return false;
                    }
                    if (v.modifyObj.invoice.mobile == null || v.modifyObj.invoice.mobile.length == 0) {
                        alert("請填寫收件電話");
                        v.$refs.invoiceMobile.focus();
                        return false;
                    }
                    if (v.modifyObj.invoice.zipCode == null || v.modifyObj.invoice.zipCode.length == 0) {
                        alert("請選擇發票寄送縣市");
                        return false;
                    }
                    if (v.modifyObj.invoice.address == null || v.modifyObj.invoice.address.length == 0) {
                        alert("請填寫發票寄送地址");
                        v.$refs.invoiveaddress.focus();
                        return false;
                    }
                } else if (v.modifyObj.invoice.enBillType == 200) {
                    if (v.modifyObj.invoice.mobileBarcode == null || v.modifyObj.invoice.mobileBarcode.length == 0) {
                        alert("請填寫手機條碼載具");
                        v.$refs.mobileBarcode.focus();
                        return false;
                    }
                }
            }
            if (v.modifyObj.details == null || v.modifyObj.details.length == 0) {
                alert("請加入輔具!");
                return false;
            } else {
                var isValid = true;
                v.modifyObj.details.forEach(function (item) {
                    if (item.unitPrice < 0) {
                        isValid = false;
                    }
                });
                if (!isValid) {
                    alert("請輸入售價!");
                    return false;
                }
            }
            return true;
        },
        async createItem() {
            var v = this;
            if (v.checkData()) {
                UJ.SaveStorage(StorageKey.packingCreateOrder + v.modifyObj.id + "_", v.modifyObj);
                v.isFinishRequest = false;
                v.isLoading = true;

                let oObj = JSON.parse(JSON.stringify(v.modifyObj));
                oObj.shippingDate = Decorator.ChangeISODateTimeToServerDateTime(oObj.shippingDate);
                oObj.paymentDatetime = Decorator.ChangeISODateTimeToServerDateTime(oObj.paymentDatetime);

                let res = await PackingSaleOrderDataService.Create(oObj);
                if (res.status == RESPONSE_STATUS.OK) {
                    v.modifyObj.id = res.data.id;
                    showMsg('新增成功!', null, null, null, null, function () {
                        v.clearStorage();
                        window.location.href = "orderEdit?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;
                }
            }
        },
        async updateItem() {
            var v = this;
            if (v.checkData()) {
                swal({
                    title: "確定要儲存出貨單？",
                    html: "",
                    type: "question",
                    showCancelButton: true,
                    confirmButtonText: "確定",
                    cancelButtonText: "取消"
                }).then(async result => {
                    if (result.value) {
                        v.isFinishRequest = false;
                        v.isLoading = true;

                        let oObj = JSON.parse(JSON.stringify(v.modifyObj));
                        oObj.shippingDate = Decorator.ChangeISODateTimeToServerDateTime(oObj.shippingDate);
                        oObj.paymentDatetime = Decorator.ChangeISODateTimeToServerDateTime(oObj.paymentDatetime);

                        let res = await PackingSaleOrderDataService.Update(oObj);
                        if (res.status == RESPONSE_STATUS.OK) {
                            showMsg('更新成功!', null, null, null, null, function () {
                                v.clearStorage();
                                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;
                        }
                    }
                });
            }
        },
        deleteItem() {
            var v = this;
            swal({
                title: "確定要刪除購物出貨單？",
                html: "",
                type: "question",
                showCancelButton: true,
                confirmButtonText: "確定",
                cancelButtonText: "取消"
            }).then(async result => {
                if (result.value) {
                    v.isFinishRequest = false;
                    v.isLoading = true;

                    let res = await PackingSaleOrderDataService.Delete(v.modifyObj.id);
                    if (res.status == RESPONSE_STATUS.OK) {
                        showMsg('刪除成功!', null, null, null, null, function () {
                            v.clearStorage();
                            v.backToList();
                        });
                    } else {
                        var data = res.data;
                        showErrMsg(data.message, "", "", function () {
                            if (data.enMessage == enMessage.NotFound) {
                                v.clearStorage();
                                v.backToList();
                            }
                        });
                        v.isFinishRequest = true;
                        v.isLoading = false;
                    }
                }
            });
        },
        removeStock(stockId) {
            var v = this;

            var stocks = [];
            v.modifyObj.details.forEach(function (detail, index) {
                detail.stocks.forEach(function (stock, idx) {
                    if (stock.stockId == stockId) {
                        detail.stocks.splice(idx, 1);
                    } else {
                        stocks.push(stock);
                    }
                });

                detail.qty = detail.stocks.length;
                if (detail.qty == 0) {
                    v.modifyObj.details.splice(index, 1);
                }
            });

            UJ.SaveStorage(StorageKey.packingCreateOrderDetails + v.modifyObj.id + "_", v.modifyObj.details);
            UJ.SaveStorage(StorageKey.packingCreateOrderStocks + v.modifyObj.id + "_", stocks);

            //強制更新vue物件
            v.$forceUpdate();
        },
        isNotify() {
            var v = this;
            var notify = false;
            if (v.modifyObj.id > 0) {
                if (v.originalObj.shippingDate != v.modifyObj.shippingDate) { return true; }
                if (v.originalObj.delivery.receiver != v.modifyObj.delivery.receiver) { return true; }
                if (v.originalObj.delivery.mobile != v.modifyObj.delivery.mobile) { return true; }
                if (v.originalObj.delivery.zipCode != v.modifyObj.delivery.zipCode) { return true; }
                if (v.originalObj.delivery.address != v.modifyObj.delivery.address) { return true; }
                if (v.originalObj.enPayMethod != v.modifyObj.enPayMethod) { return true; }
                if (v.originalObj.enPaymentStatus != v.modifyObj.enPaymentStatus) { return true; }
                if (v.originalObj.paymentDatetime != v.modifyObj.paymentDatetime) { return true; }
                if (v.originalObj.invoice.enInvoiceType != v.modifyObj.invoice.enInvoiceType) { return true; }
                if (v.originalObj.invoice.invoiceTaxNo != v.modifyObj.invoice.invoiceTaxNo) { return true; }
                if (v.originalObj.invoice.invoiceTitle != v.modifyObj.invoice.invoiceTitle) { return true; }
                if (v.originalObj.invoice.enBillType != v.modifyObj.invoice.enBillType) { return true; }
                if (v.originalObj.invoice.receiver != v.modifyObj.invoice.receiver) { return true; }
                if (v.originalObj.invoice.mobile != v.modifyObj.invoice.mobile) { return true; }
                if (v.originalObj.invoice.zipCode != v.modifyObj.invoice.zipCode) { return true; }
                if (v.originalObj.invoice.address != v.modifyObj.invoice.address) { return true; }
                if (v.originalObj.invoice.mobileBarcode != v.modifyObj.invoice.mobileBarcode) { return true; }

                v.modifyObj.details.forEach(function (detail) {
                    if (detail.id <= 0) {
                        notify = true;
                    } else {
                        detail.stocks.forEach(function (stock) {
                            if (stock.orderDetailId <= 0) {
                                notify = true;
                            }
                        });
                    }
                });
                if (!notify) {
                    v.originalObj.details.forEach(function (obj) {
                        var isExistProd = false;
                        v.modifyObj.details.forEach(function (detail) {
                            if (obj.id == detail.id) {
                                if (obj.unitPrice != detail.unitPrice) { notify = true; }
                                obj.stocks.forEach(function (s) {
                                    var isExists = false;
                                    detail.stocks.forEach(function (stock) {
                                        if (s.stockId == stock.stockId) {
                                            isExists = true;
                                        }
                                    });
                                    if (!isExists) { notify = true; }
                                });
                                isExistProd = true;
                            }
                        });
                        if (!isExistProd) { notify = true; }
                    });
                }
            }
            return notify;
        },
        confirmQC() {
            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 PackingSaleOrderDataService.ConfirmQC(v.modifyObj.id);
                    if (res.status == RESPONSE_STATUS.OK) {
                        showMsg('已轉為出貨準備中!', null, null, null, null, function () {
                            v.backToList();
                        });
                    } 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;
                    }
                }
            });
        },
        restoreQC() {
            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 PackingSaleOrderDataService.RestoreQC(v.modifyObj.id);
                    if (res.status == RESPONSE_STATUS.OK) {
                        showMsg('已轉回待出貨!', null, null, null, null, function () {
                            v.clearStorage();
                            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;
                    }
                }
            });
        },
        backToList() {
            this.clearStorage();
            var page = UJ.getParameterByName("p");
            location.href = '/order/shiplist?tf=' + UJ.TF() + "&p=" + (page == 'null' ? page : 1);
        },
        openAddressList() {
            UJ.SaveStorage(StorageKey.packingCreateOrder + this.modifyObj.id + "_", this.modifyObj);
        }
    }
});

$(function () {
    setTimeout(function () {
        openLeftMenu('/order/shiplist');
    }, 100);
});