import { AuthDataService } from '/js/ApiDataServer/Auth.js?tf=202411121501';
import { OemDataService } from '/js/ApiDataServer/Oem.js?tf=202411191029';
import { UniversalDataService } from '/js/ApiDataServer/Universal.js?tf=202411131831';
import { PackingDataService } from '/js/ApiDataServer/Packing.js?tf=202411201826';
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: [],
            ltPackingStatus: [],
            query: {
                packingId: null,
                startDate: null,
                endDate: null,
                packingNum: "",
                orderNum: "",
                propertyNo: "",
                keyword: "",
                shippingStartDate: null,
                shippingEndDate: null,
                packingStatuss: -1,
                sources: [],
                rentedFors: [],
                shippingMethods: [],
                packingTypes: [200],
                oemMarketId: -1,
                oemMarketName: "",
                currentPage: 1,
                pageSize: 20
            },
            list: [],
            pager: {},
            lastActionId: -1
        };
    },
    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 (v.memberObj.marketId > 0) {
            v.query.marketId = v.memberObj.marketId;
            v.query.marketName = v.memberObj.marketName;
            $('#query-market').val(v.memberObj.marketName);
        } else {
            v.query.marketId = -1;
            v.query.marketName = "";
            $('#query-market').val('');
        }

        if (! await OemDataService.IsAuthModifyOrder()) {
            showErrMsg("權限不足", "", null, function () {
                location.href = "/";
            });
        } else {
            v.ltOemMarketList = await OemDataService.GetOemMarketList();
            v.initAutocomplete();

            v.ltPackingStatus = await UniversalDataService.GetPackingStatus();

            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 = 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;
            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;
                        }
                    });
                });

                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);
            }
        },
        changeDate(type) {
            var v = this;
            if (type == "start") {
                v.query.endDate = v.query.startDate;
            } else if (type == "shippingStart") {
                v.query.shippingEndDate = v.query.shippingStartDate;
            }
        },
        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 = 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 = 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;
                    }
                }
            });
        },
        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";
            }

            if (item.id == v.lastActionId) {
                css = "nofity";
            }
            return css;
        },
        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;
            v.query.packingId = v.lastActionId;

            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;
                    }
                });

                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;
            UJ.SaveStorage(StorageKey.oemPackingEditId, item.id);
            location.href = "/oem/order/orderEdit?id=" + item.orderMainId + "&p=" + v.query.currentPage;
        }
    }
});
