import { AuthDataService } from '/js/ApiDataServer/Auth.js?tf=202411121501';
import { UniversalDataService } from '/js/ApiDataServer/Universal.js?tf=202411131831';
import { PackingDataService } from '/js/ApiDataServer/Packing.js?tf=202411201826';
import { OemDataService } from '/js/ApiDataServer/Oem.js?tf=202411191029';
import { PackingSaleOrderDataService } from '/js/ApiDataServer/PackingSaleOrder.js';
import { StoreDataService } from '/js/ApiDataServer/Store.js';
import { RESPONSE_STATUS } from '/js/constants.js';
import { Decorator } from '/js/util/dacorator.js';
import { StorageKey } from '/js/constants.js?tf=202412272022';
import { enMessage } from '/js/constants.js';
import { UJ } from '/js/util/uj.js';

var vMain = new Vue({
    el: "#dvMain",
    data: function () {
        return {
            pageTitle: "出貨單列表",
            authDesc: "訂單_出貨管理",
            isSystemManager: false,
            isLoading: false,
            isFinishRequest: false,
            isBindFancybox: true,
            memberObj: {},
            ltOemMarketList: [],
            ltPackingType: [],
            ltPackingStatus: [],
            ltSource: [],
            ltRentedFor: [],
            ltShippingMethod: [],
            ltStore: [],
            query: {
                packingId: null,
                startDate: null,
                endDate: null,
                packingNum: "",
                orderNum: "",
                propertyNo: "",
                keyword: "",
                shippingStartDate: null,
                shippingEndDate: null,
                packingStatuss: -1,
                sources: [],
                rentedFors: [],
                shippingMethods: [],
                packingTypes: [],
                oemMarketId: -1,
                oemMarketName: "",
                currentPage: 1,
                pageSize: 20
            },
            list: [],
            pager: {},
            checkAll: false,
            ltChecked: [],
            packingItem: {},
            lastActionId: []
        };
    },
    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 = '/';
            }
        }

        v.ltOemMarketList = await OemDataService.GetOemMarketList();
        v.initAutocomplete();

        v.ltPackingType = await UniversalDataService.GetPackingType();
        v.ltPackingStatus = await UniversalDataService.GetPackingStatus();
        v.ltSource = await UniversalDataService.GetOrderSource();
        v.ltRentedFor = await UniversalDataService.GetRentedFor();
        v.ltShippingMethod = await UniversalDataService.GetShippingMethod();
        v.ltStore = await StoreDataService.GetMarketStoreList(-1);

        v.query.orderNum = UJ.getParameterByName("o");
        if (UJ.getParameterByName("p") != null) {
            v.getList(UJ.getParameterByName("p"));
        } else {
            v.getList(1);
        }

        var editId = UJ.GetStorage(StorageKey.oemPackingEditId);
        if (editId != null) {
            v.lastActionId = [];
            v.lastActionId.push(editId);
            UJ.ResetStorage(StorageKey.oemPackingEditId);
        }
    },
    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: {
        clearCriteria() {
            location.href = 'shiplist?tf=' + UJ.TF();
        },
        async getList(pageNum) {
            var v = this;
            //rebind tooltip 前先清空 list
            v.list = [];
            v.isLoading = true;
            v.isFinishRequest = false;
            if (pageNum > 0) {
                v.query.currentPage = pageNum;
            }
            let res = await PackingDataService.GetShipList(v.query);
            if (res.status == RESPONSE_STATUS.OK) {
                var data = res.data;

                v.list = data.list;
                v.list.forEach(function (item) {
                    item.cancelApplyDatetime = Decorator.ChangeServerDateTimeToISODateTime(item.cancelApplyDatetime);
                    item.cancelConfirmDatetime = Decorator.ChangeServerDateTimeToISODateTime(item.cancelConfirmDatetime);
                    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.oemMarketName = "--";

                    v.ltOemMarketList.forEach(function (market) {
                        if (item.oemMarketId == market.id) {
                            item.oemMarketName = market.name;
                        }
                    });
                    if (item.orderDetails != null) {
                        item.orderDetails.forEach(function (obj) {
                            //for QC
                            obj.startDate = Decorator.ChangeISODateTimeToDate(obj.startDate);
                            obj.endDate = Decorator.ChangeISODateTimeToDate(obj.endDate);

                            obj.startDateShort = Decorator.ChangeISODateTimeToMMdd(obj.startDate);
                            obj.endDateShort = Decorator.ChangeISODateTimeToMMdd(obj.endDate);
                        });
                    }
                    item.ownerStoreName = "";
                    v.ltStore.forEach(function (obj) {
                        if (obj.id == item.ownerStoreId) {
                            item.ownerStoreName = obj.shortName;
                        }
                    });
                    item.deliveryStoreName = "";
                    v.ltStore.forEach(function (obj) {
                        if (obj.id == item.deliveryStoreId) {
                            item.deliveryStoreName = obj.shortName;
                            item.county = obj.county;
                            item.city = obj.city;
                            if (obj.address != null) {
                                item.address = obj.address;
                            }
                        }
                    });
                });

                v.pager = data.pager;
                v.isFinishRequest = true;
                v.isLoading = false;
                v.isBindFancybox = false;//重新綁定fancybox
            } else {
                var data = res.data;
                if (res.httpStatus === 401) {
                    showErrMsg(data.message, "", "", function () {
                        location.href = "/";
                    });
                } else {
                    showErrMsg(data.message, "", "", null);
                    v.isLoading = false;
                    v.isFinishRequest = true;
                }
            }
        },
        goPage(pageNum) {
            this.getList(pageNum);
        },
        keychange(event) {
            if (event.keyCode == 13) {
                this.getList(1);
            }
        },
        changeStatus(type, val, ckd) {
            var v = this;
            var isExists = false;
            var lt = [];
            switch (type) {
                case "packingTypes":
                    lt = v.query.packingTypes;
                    break;
                case "source":
                    lt = v.query.sources;
                    break;
                case "rentedFor":
                    lt = v.query.rentedFors;
                    break;
                case "shippingMethod":
                    lt = v.query.shippingMethods;
                    break;
            }
            lt.forEach(function (value, idx) {
                if (value == val) {
                    isExists = true;
                    if (!ckd) {
                        lt.splice(idx, 1);
                    }
                }
            });

            if (ckd && !isExists) {
                lt.push(val);
            }

            v.getList(1);
        },
        checkedList(type, val) {
            var v = this;
            var lt = [];
            switch (type) {
                case "packingTypes":
                    lt = v.query.packingTypes;
                    break;
                case "source":
                    lt = v.query.sources;
                    break;
                case "rentedFor":
                    lt = v.query.rentedFors;
                    break;
                case "shippingMethod":
                    lt = v.query.shippingMethods;
                    break;
            }

            var res = false;
            lt.forEach(function (value) {
                if (value == val) {
                    res = true;
                }
            });
            return res;
        },
        changeDate(type) {
            var v = this;
            if (type == "start") {
                v.query.endDate = v.query.startDate;
            } else if (type == "shippingStart") {
                v.query.shippingEndDate = v.query.shippingStartDate;
            }
        },
        showQC(item) {
            UJ.SaveStorage(StorageKey.shipqc + item.packingNum + "_", item);
        },
        SelectAll(ckd) {
            var v = this;
            v.ltChecked = [];
            v.checkAll = ckd;
            v.list.forEach(async function (item) {
                if (ckd) {
                    v.ltChecked.push(item);
                }
            });
        },
        isExistsCheckList(packingId) {
            var v = this;
            var isExists = false;
            v.ltChecked.forEach(function (obj) {
                if (obj.id == packingId) {
                    isExists = true;
                }
            });

            return isExists;
        },
        changeCKD(item, ckd) {
            var v = this;

            var isExists = false;
            v.ltChecked.forEach(function (obj, idx) {
                if (obj.id == item.id) {
                    isExists = true;
                    if (!ckd) {
                        v.ltChecked.splice(idx, 1);
                    }
                }
            });

            if (ckd && !isExists) {
                v.ltChecked.push(item);
            }
            if (!ckd) {
                v.checkAll = false;
            }
        },
        async exportData() {
            var v = this;
            if (v.ltChecked != null && v.ltChecked.length > 0) {
                let res = await PackingDataService.ExportList(v.ltChecked);
                if (res.status != RESPONSE_STATUS.OK) {
                    alert('匯出失敗');
                    v.isFinishRequest = true;
                    return;
                } else {
                    v.isFinishRequest = true;
                }
            } else {
                showErrMsg("請勾選要匯出的項目", "", "warning", function () {
                    return false;
                });
            }
        },
        transToOrder(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;
                    v.lastActionId = [];
                    v.lastActionId.push(item.id);

                    let res = await PackingDataService.TransToOrder(item.orderMainId);
                    if (res.status == RESPONSE_STATUS.OK) {
                        showMsg('已取消出貨(轉回訂單)!', null, null, null, null, function () {
                            location.href = "/order/orderedit?id=" + item.orderMainId + '&s=sl';
                        });
                    } 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;
                    }
                }
            });
        },
        transToShip(item) {
            var v = this;
            var title = "確定轉 [已出貨]？";
            var html = "轉為已出貨";

            if (item.enPackingType == 200) {
                if (item.oemDetails.length > 0 && item.freightage == 0) {
                    title = "確定轉 [已出貨]？"
                    html = "<div style='color: #ff0000; font-weight: bold;'>出貨單無運費</div>";
                }
            }
            swal({
                title: title,
                html: html,
                type: "question",
                showCancelButton: true,
                confirmButtonText: "確定",
                cancelButtonText: "取消"
            }).then(async function (result) {
                if (result.value) {
                    v.isFinishRequest = false;
                    v.isLoading = true;
                    v.lastActionId = [];
                    v.lastActionId.push(item.id);

                    let res = await PackingDataService.TransToShip(item.id);
                    if (res.status == RESPONSE_STATUS.OK) {
                        showMsg('已轉為已出貨!', null, null, null, null, function () {
                            v.getOne();
                        });
                    } 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;
                    }
                }
            });
        },
        transToPreparing(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;
                    v.lastActionId = [];
                    v.lastActionId.push(item.id);

                    let res = await PackingDataService.TransToPreparing(item.id);
                    if (res.status == RESPONSE_STATUS.OK) {
                        showMsg('已恢復為出貨準備中!', null, null, null, null, function () {
                            v.getOne();
                        });
                    } 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;
                    }
                }
            });
        },
        transToDelivered(item) {
            var v = this;
            var html = "轉為已簽收（訂單品項轉為使用中）";
            if (item.enPackingType == 300) {
                var html = "轉為已簽收。";
            }
            swal({
                title: "確定轉 [已簽收]？",
                html: html,
                type: "question",
                showCancelButton: true,
                confirmButtonText: "確定",
                cancelButtonText: "取消"
            }).then(async function (result) {
                if (result.value) {
                    v.isFinishRequest = false;
                    v.isLoading = true;
                    v.lastActionId = [];
                    v.lastActionId.push(item.id);

                    let res = await PackingDataService.TransToDelivered(item.id);
                    if (res.status == RESPONSE_STATUS.OK) {
                        showMsg('已轉為已簽收!', null, null, null, null, function () {
                            v.getOne();
                        });
                    } 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;
                    }
                }
            });
        },
        transToCancelApply(item) {
            var v = this;
            swal({
                title: "確定要申請取消出貨？",
                html: "訂單中止，取消出貨委託。<div style='color: red'>申請送出後無法恢復，確定要送出申請嗎？</div>",
                type: "question",
                showCancelButton: true,
                confirmButtonText: "確定",
                cancelButtonText: "取消"
            }).then(async function (result) {
                if (result.value) {
                    v.isFinishRequest = false;
                    v.isLoading = true;
                    v.lastActionId = [];
                    v.lastActionId.push(item.id);

                    let res = await PackingDataService.TransToCancelApply(item.id);
                    if (res.status == RESPONSE_STATUS.OK) {
                        showMsg('已送出取消出貨申請!', null, null, null, null, function () {
                            v.getOne();
                        });
                    } 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;
                    }
                }
            });
        },
        transToCancelConfirm(item) {
            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;
                    v.lastActionId = [];
                    v.lastActionId.push(item.id);

                    let res = await PackingDataService.TransToCancelConfirm(item.id);
                    if (res.status == RESPONSE_STATUS.OK) {
                        showMsg('已確認取消出貨!', null, null, null, null, function () {
                            v.getOne();
                        });
                    } 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(item) {
            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;
                    v.lastActionId = [];
                    v.lastActionId.push(item.id);

                    let res = await PackingSaleOrderDataService.Delete(item.orderMainId);
                    if (res.status == RESPONSE_STATUS.OK) {
                        showMsg('刪除成功!', null, null, null, null, function () {
                            v.getList(v.query.currentPage);
                        });
                    } 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;
                    }
                }
            });
        },
        trCss(item) {
            var v = this;
            var css = "";
            if (item.receivedDate == null) {
                if (item.enStatus == 500) {
                    css = "gray";
                } else {
                    css = "bg-pink";
                }
            }
            if (item.receivedDate != null) {
                css = "bg-closed";
            }

            v.lastActionId.forEach(function (actionId) {
                if (item.id == actionId) { css = "nofity"; }
            });
            return css;
        },
        triggerUpload(obj, item) {
            this.packingItem = item;
            $(obj).trigger("click");
        },
        onFileChange(e) {
            var v = this;
            v.isFinishRequest = false;
            v.isLoading = true;

            var files = e.target.files || e.dataTransfer.files;
            if (!files.length) return;
            this.uploadImg(files[0]);
        },
        async uploadImg(f) {
            //自動上傳
            var v = this;
            v.isFinishRequest = false;
            v.isLoading = true;
            var fData = new FormData();
            fData.append("files", f);
            fData.append("type", "receipts");
            fData.append("packingId", v.packingItem.id);
            v.lastActionId = [];
            v.lastActionId.push(v.packingItem.id);

            let res = await PackingDataService.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();
                return;
            }
            else {
                alert('上傳完成.');
                v.resetFile();
                v.getOne();
            }
        },
        resetFile() {
            const inputImg = this.$refs.fuImg;
            inputImg.type = 'text';
            inputImg.type = 'file';
            this.recycleItem = {};
            this.isLoading = false;
            this.isFinishRequest = true;
            this.isBindFancybox = false;
        },
        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.query.oemMarketId = ui.item.id;
                    v.query.oemMarketName = ui.item.label;

                    v.getList(1);
                },
                change: function (event, ui) {
                    //清空輸入框
                    if (ui.item == null) {
                        v.query.oemMarketId = -1;
                        v.query.oemMarketName = "";
                        v.getList(1);
                    }
                }
            }).focus(function () {
                //點輸入框就秀出下拉選單
                $(this).trigger("keydown");
            }).change(function () {
                if ($(this).val().trim() == '' || $(this).val() == '') {
                    v.query.oemMarketId = -1;
                    v.query.oemMarketName = "";
                    v.getList(1);
                }
            }).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");
            });
        },
        async getOne() {
            var v = this;
            v.isLoading = true;
            v.isFinishRequest = false;
            if (v.lastActionId.length > 0) {
                v.query.packingId = v.lastActionId[0];
            }

            let res = await PackingDataService.GetShipList(v.query);
            if (res.status == RESPONSE_STATUS.OK) {
                var data = res.data;
                v.query.packingId = -1;

                var resObj = data.list[0];
                resObj.cancelApplyDatetime = Decorator.ChangeServerDateTimeToISODateTime(resObj.cancelApplyDatetime);
                resObj.cancelConfirmDatetime = Decorator.ChangeServerDateTimeToISODateTime(resObj.cancelConfirmDatetime);
                resObj.scheduleDate = Decorator.ChangeISODateTimeToDate(resObj.scheduleDate);
                resObj.qcDate = Decorator.ChangeISODateTimeToDate(resObj.qcDate);
                resObj.shippingDate = Decorator.ChangeISODateTimeToDate(resObj.shippingDate);
                resObj.receivedDate = Decorator.ChangeISODateTimeToDate(resObj.receivedDate);
                resObj.oemMarketName = "--";

                v.ltOemMarketList.forEach(function (market) {
                    if (resObj.oemMarketId == market.id) {
                        resObj.oemMarketName = market.name;
                    }
                });
                if (resObj.orderDetails != null) {
                    resObj.orderDetails.forEach(function (obj) {
                        //for QC
                        obj.startDate = Decorator.ChangeISODateTimeToDate(obj.startDate);
                        obj.endDate = Decorator.ChangeISODateTimeToDate(obj.endDate);

                        obj.startDateShort = Decorator.ChangeISODateTimeToMMdd(obj.startDate);
                        obj.endDateShort = Decorator.ChangeISODateTimeToMMdd(obj.endDate);
                    });
                }
                resObj.ownerStoreName = "";
                v.ltStore.forEach(function (obj) {
                    if (obj.id == resObj.ownerStoreId) {
                        resObj.ownerStoreName = obj.shortName;
                    }
                });
                resObj.deliveryStoreName = "";
                v.ltStore.forEach(function (obj) {
                    if (obj.id == resObj.deliveryStoreId) {
                        resObj.deliveryStoreName = obj.shortName;
                        resObj.county = obj.county;
                        resObj.city = obj.city;
                        if (obj.address != null) {
                            resObj.address = obj.address;
                        }
                    }
                });

                v.list.forEach(function (item, idx) {
                    if (item.id == resObj.id) {
                        v.list[idx] = resObj;
                    }
                });

                v.isFinishRequest = true;
                v.isLoading = false;
                v.isBindFancybox = false;//重新綁定fancybox
            } else {
                var data = res.data;
                if (res.httpStatus === 401) {
                    showErrMsg(data.message, "", "", function () {
                        location.href = "/";
                    });
                } else {
                    showErrMsg(data.message, "", "", null);
                    v.isLoading = false;
                    v.isFinishRequest = true;
                }
            }
        },
        gotoEditUrl(item) {
            var v = this;
            if (item.enPackingType == 100) {
                location.href = "/order/orderedit?id=" + item.orderMainId + "&s=sl";
            }
            if (item.enPackingType == 200) {
                UJ.SaveStorage(StorageKey.oemPackingEditId, item.id);
                location.href = "/oem/order/orderEdit?id=" + item.orderMainId + "&s=100&p=" + v.query.currentPage;
            }
            if (item.enPackingType == 300) {
                UJ.SaveStorage(StorageKey.oemPackingEditId, item.id);
                location.href = "/packing/orderEdit?id=" + item.orderMainId + "&s=100&p=" + v.query.currentPage;
            }
        }
    }
});
