import { AuthDataService } from '/js/ApiDataServer/Auth.js?tf=202411121501';
import { OemDataService } from '/js/ApiDataServer/Oem.js?tf=202411191029';
import { OemOrderDataService } from '/js/ApiDataServer/OemOrder.js';
import { RESPONSE_STATUS } from '/js/constants.js';
import { Decorator } from '/js/util/dacorator.js';
import { StorageKey } from '/js/constants.js?tf=202412301032';
import { enMessage } from '/js/constants.js';
import { UJ } from '/js/util/uj.js';

let twzipcode;
var vMain = new Vue({
    el: "#dvMain",
    data: function () {
        return {
            pageTitle: "[代工清消收送] 建立出貨單",
            authDesc: "代工_出貨管理",
            isSystemManager: false,
            isLoading: false,
            isFinishRequest: true,
            isBindFancybox: true,
            memberObj: {},
            ltOemMarketList: [],
            modifyObj: {
                id: -1,
                shippingDate: "",
                oemMarketId: -1,
                oemMarketName: "",
                freightage: 0,
                delivery: {
                    receiver: "",
                    mobile: ""
                },
                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;


            if (v.memberObj.marketId > 0) {
                $('#query-market').prop("readonly", "readonly");
            }
        } else {
            var data = res.data;
            if (data.enMessage == enMessage.NotLogin) {
                await AuthDataService.Logout();
                location.href = '/';
            }
        }

        if (! await OemDataService.IsAuthModifyOrder()) {
            showErrMsg("權限不足", "", null, function () {
                v.backToList();
            });
        } else {
            v.ltOemMarketList = await OemDataService.GetOemMarketList();
            v.modifyObj.id = UJ.getParameterByName("id");
            v.initAutocomplete();
            v.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;
        }
    },
    components: {
        'date-picker': DatePicker
    },
    methods: {
        clearStorage() {
            UJ.ResetStorage(StorageKey.oemOrderMain);
            UJ.ResetStorage(StorageKey.oemOrderDetails);
            UJ.ResetStorage(StorageKey.oemOrderStocks);
        },
        async resetItem() {
            var v = this;
            if (v.modifyObj.id != null && v.modifyObj.id > 0) {
                v.isFinishRequest = false;

                var res = await OemDataService.GetOrder(v.modifyObj.id);
                if (res.status == RESPONSE_STATUS.OK) {
                    v.modifyObj = res.data;//Clone Obj

                    v.modifyObj.createDate = Decorator.ChangeServerDateTimeToISODateTime(v.modifyObj.createDatetime);
                    v.modifyObj.modifyDate = Decorator.ChangeServerDateTimeToISODateTime(v.modifyObj.modifyDatetime);

                    v.originalObj = $.extend(true, {}, v.modifyObj);

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

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

                    $('#query-market').prop("readonly", "readonly");
                } 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.receiver = "";
                v.modifyObj.mobile = "";
                v.modifyObj.delivery.zipCode = "";
                v.modifyObj.delivery.county = "";
                v.modifyObj.delivery.city = "";
                v.modifyObj.delivery.address = "";

                if (v.memberObj.marketId > 0) {
                    v.modifyObj.oemMarketId = v.memberObj.marketId;
                }
                v.modifyObj.id = -v.memberObj.id;
                v.modifyObj.details = [];
            }

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

            var addressInfo = UJ.GetStorage(StorageKey.oemOrderAddressInfo + v.modifyObj.id + "_null_" + v.modifyObj.oemMarketId + "_");
            if (addressInfo != null) {
                v.modifyObj.receiver = addressInfo.receiver;
                v.modifyObj.mobile = addressInfo.mobile;
                v.modifyObj.delivery.zipCode = addressInfo.zipCode;
                v.modifyObj.delivery.county = addressInfo.county;
                v.modifyObj.delivery.city = addressInfo.city;
                v.modifyObj.delivery.address = addressInfo.address;
                UJ.ResetStorage(StorageKey.oemOrderAddressInfo);
            }

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

            v.zipcode();

            v.modifyObj.oemMarketName = "";
            if (v.modifyObj.oemMarketId > 0) {
                v.ltOemMarketList.forEach(function (item) {
                    if (item.id == v.modifyObj.oemMarketId) {
                        v.modifyObj.oemMarketName = item.name;
                    }
                });
            }
            $('#query-market').val(v.modifyObj.oemMarketName);
        },
        zipcode() {
            var v = this;
            setTimeout(function () {
                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);
                if (v.modifyObj.id < 0) {
                    v.calculateFreightage();
                }
            }, 100);
        },
        async calculateFreightage() {
            var v = this;
            if (v.modifyObj.delivery.zipCode != null && v.modifyObj.delivery.zipCode.length > 0) {
                v.isFinishRequest = false;
                v.isLoading = true;

                let res = await OemOrderDataService.CalculateFreightage({
                    mainObj: v.modifyObj,
                    ltDetails: v.modifyObj.details
                });
                if (res.status == RESPONSE_STATUS.OK) {
                    v.modifyObj = res.data.mainObj;
                    v.modifyObj.details = res.data.ltDetails;
                    if (v.modifyObj.details == null) { v.modifyObj.details = []; }

                    v.isFinishRequest = true;
                    v.isLoading = false;
                } 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;
                }
            }
        },
        showProductList() {
            var v = this;
            UJ.SaveStorage(StorageKey.oemOrderMain + v.modifyObj.id + "_", v.modifyObj);
            UJ.SaveStorage(StorageKey.oemOrderDetails + 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.oemOrderStocks + v.modifyObj.id + "_", stocks);
        },
        checkData() {
            var v = this;
            if (v.modifyObj.oemMarketId == "" || v.modifyObj.oemMarketId.length == 0 || v.modifyObj.oemMarketId == -1) {
                alert("請選擇通路");
                v.$refs.oemMarketId.focus();
                return false;
            }
            if (v.modifyObj.shippingDate == null || v.modifyObj.shippingDate == "") {
                alert("請輸入預計出貨日!");
                $("#shippingDate").focus();
                return false;
            }
            if (v.modifyObj.receiver == null || v.modifyObj.receiver == "") {
                alert("請填寫收件人姓名");
                v.$refs.receiver.focus();
                return false;
            }
            if (v.modifyObj.mobile == null || v.modifyObj.mobile == "") {
                alert("請填寫收件人電話");
                v.$refs.mobile.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.address.focus();
                return false;
            }
            if (v.modifyObj.details == null || v.modifyObj.details.length == 0) {
                alert("請加入輔具!");
                return false;
            }
            return true;
        },
        async createItem() {
            var v = this;
            if (v.checkData()) {
                if (v.modifyObj.freightage == 0) {
                    swal({
                        title: "確定要建立出貨單？",
                        html: "出貨單只有免運品項，確定要建立出貨單嗎？。",
                        type: "question",
                        showCancelButton: true,
                        confirmButtonText: "確定",
                        cancelButtonText: "取消"
                    }).then(result => {
                        if (result.value) {
                            v.create();
                        }
                    });
                } else {
                    v.create();
                }
            }
        },
        async create() {
            var v = this;
            v.isFinishRequest = false;
            v.isLoading = true;

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

            let res = await OemOrderDataService.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()) {
                if (v.modifyObj.freightage == 0) {
                    swal({
                        title: "確定要儲存出貨單？",
                        html: "出貨單只有免運品項，確定要儲存出貨單嗎？。",
                        type: "question",
                        showCancelButton: true,
                        confirmButtonText: "確定",
                        cancelButtonText: "取消"
                    }).then(result => {
                        if (result.value) {
                            v.update();
                        }
                    });
                } else {
                    v.update();
                }
            }
        },
        async update() {
            var v = this;
            v.isFinishRequest = false;
            v.isLoading = true;

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

            let res = await OemOrderDataService.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(result => {
                if (result.value) {
                    v.delete();
                }
            });
        },
        async delete() {
            var v = this;
            v.isFinishRequest = false;
            v.isLoading = true;

            let res = await OemOrderDataService.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;
            }
        },
        changeCity() {
            var v = this;
            setTimeout(function () {
                let zipRes = twzipcode.get();
                var refreshFreightage = false;
                if (v.modifyObj.delivery.zipCode != zipRes.zipcode) {
                    refreshFreightage = true;
                }
                v.modifyObj.delivery.zipCode = zipRes.zipcode;
                if (refreshFreightage) {
                    v.calculateFreightage();
                }
            }, 300);
        },
        removeStock(detailId, 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.oemOrderDetails + v.modifyObj.id + "_", v.modifyObj.details);
            UJ.SaveStorage(StorageKey.oemOrderStocks + v.modifyObj.id + "_", stocks);

            //強制更新vue物件
            v.$forceUpdate();

            v.calculateFreightage();
        },
        isNotify() {
            var v = this;
            var notify = false;
            if (v.modifyObj.id > 0) {
                if (v.originalObj.receiver != v.modifyObj.receiver) { return true; }
                if (v.originalObj.shippingDate != v.modifyObj.shippingDate) { return true; }
                if (v.originalObj.mobile != v.modifyObj.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; }

                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) {
                                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 OemOrderDataService.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 OemOrderDataService.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 source = UJ.getParameterByName("s");
            var page = UJ.getParameterByName("p");
            if (page == null) page = 1;
            if (source == 100) {
                location.href = '/order/shiplist?tf=' + UJ.TF() + "&p=" + page;
            } else {
                location.href = 'shiplist?tf=' + UJ.TF() + "&p=" + page;
            }
        },
        openAddressList() {
            UJ.SaveStorage(StorageKey.oemOrderMain + this.modifyObj.id + "_", this.modifyObj);
        },
        initAutocomplete() {
            var v = this;
            //setting autocomplete
            $('#query-market').autocomplete({
                minLength: 0,
                delay: 50, //延遲
                source: (request, response) => {
                    var markets = v.ltOemMarketList.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.modifyObj.oemMarketId = ui.item.id;
                    v.modifyObj.oemMarketName = ui.item.label;
                },
                change: function (event, ui) {
                    //清空輸入框
                    if (ui.item == null) {
                        v.modifyObj.oemMarketId = -1;
                        v.modifyObj.oemMarketName = "";
                    }
                }
            }).focus(function () {
                //點輸入框就秀出下拉選單
                $(this).trigger("keydown");
            }).change(function () {
                if ($(this).val().trim() == '' || $(this).val() == '') {
                    v.modifyObj.oemMarketId = -1;
                    v.modifyObj.oemMarketName = "";
                }
            }).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");
            });
        }
    }
});

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