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 { StorageKey } from '/js/constants.js?tf=202503201821';
import { UJ } from '/js/util/uj.js';

var vMain = new Vue({
    el: "#dvMain",
    data: function () {
        return {
            pageTitle: "佳醫銷售出貨單-加入輔具",
            authDesc: "訂單_出貨管理",
            isSystemManager: false,
            isLoading: false,
            isFinishRequest: false,
            showCloseBTN: false,
            isBindFancybox: true,
            StorageKey: "AssistiveRent_Admin_Packing_ProductList",
            ltCategory: [],
            ltSeatWidthAttrs: [],
            orderId: -1,
            query: {
                productType: -1,
                parentId: -1,
                categoryId: -1,
                keyword: "",
                seatWidthAttrs: [],
                stocks: [],
                currentPage: 1,
                pageSize: 9999
            },
            list: [],
            pager: {}
        };
    },
    created: async function () {
        var v = this;
        v.isSystemManager = await AuthDataService.IsSystemManager();
        v.orderId = UJ.getParameterByName("oid");

        v.ltCategory = await UniversalDataService.GetProductCategory();
        v.ltSeatWidthAttrs = await UniversalDataService.GetltSeatWidthAttrs();

        var s = $("body").getPostDataFromStorage(v.StorageKey);
        if (s.propCount == 0) {
            v.clearCriteria();
        } else {
            if (s.parentId != null && s.parentId != "null") {
                v.query.parentId = s.parentId;
            }
            if (s.categoryId != null && s.categoryId != "null") {
                v.query.categoryId = s.categoryId;
            }
            v.query.keyword = s.keyword;
            v.query.seatWidthAttrs = [];
            if (s.seatwidth != null) {
                s.seatwidth.split(',').forEach(function (value) {
                    if (value != "null") {
                        v.query.seatWidthAttrs.push(value);
                    }
                });
            }
            v.getList(s.currentPage);
        }
    },
    updated: function () {
        var v = this;
        if (!v.isBindFancybox) {
            bindFancybox();
            v.isBindFancybox = true;
        }

        initAdminutil();
        if (v.isFinishRequest) {
            setTimeout(function () {
                $("body").setPostDataToStorage(v.StorageKey);
                v.isLoading = false;
            }, 100);
        } else {
            v.isLoading = true;
        }
    },
    methods: {
        clearCriteria() {
            var v = this;
            v.query.parentId = -1;
            v.query.categoryId = -1;
            v.query.keyword = "";
            v.query.seatWidthAttrs = [];
            v.getList(1);
        },
        async getList(pageNum) {
            var v = this;
            v.isFinishRequest = false;
            v.isLoading = true;
            if (pageNum > 0) {
                v.query.currentPage = pageNum;
            }

            v.query.stocks = UJ.GetStorage(StorageKey.packingCreateOrderStocks + v.orderId + "_");
            for (var i = v.query.stocks.length - 1; i >= 0; i--) {
                var obj = v.query.stocks[i];
                if (obj.orderDetailId > 0) {
                    v.query.stocks.splice(i, 1);
                }
            }

            let res = await PackingSaleOrderDataService.GetProductListWithStock(this.query);
            if (res.status == RESPONSE_STATUS.OK) {
                var data = res.data;
                v.list = data.list;
                if (v.query.stocks != null && v.query.stocks.length > 0) {
                    v.list.forEach(function (product) {
                        v.query.stocks.forEach(function (obj) {
                            if (obj.productId == product.id) {
                                var isExists = false;
                                product.stocks.forEach(function (stock) {
                                    if (stock.stockId == obj.stockId) {
                                        isExists = true;
                                    }
                                });
                                if (!isExists) {
                                    product.stocks.push(obj);
                                }
                            }
                        });
                    });
                }
                v.isBindFancybox = false;//重新綁定fancybox
                v.pager = data.pager;
                v.isFinishRequest = true;
            } else {
                var data = res.data;
                if (res.httpStatus === 401) {
                    showErrMsg(data.message, "", "", function () {
                        v.closeAndReloadParent();
                    });
                } else {
                    showErrMsg(data.message, "", "", null);
                    v.isFinishRequest = true;
                }
            }
        },
        keychange(event) {
            if (event.keyCode == 13) {
                this.getList(1);
            }
        },
        goPage(pageNum) {
            this.getList(pageNum);
        },
        changeCkd(type, val, ckd) {
            var v = this;

            var lt = [];
            switch (type) {
                case "seatwidth":
                    lt = v.query.seatWidthAttrs;
                    break;
            }

            var isExists = false;
            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 "seatwidth":
                    lt = v.query.seatWidthAttrs;
                    break;
            }

            var res = false;
            lt.forEach(function (value) {
                if (value == val) {
                    res = true;
                }
            });
            return res;
        },
        removeItem(stocks, idx, obj) {
            var v = this;
            v.list.forEach(function (item) {
                if (item.seatWidthAttrs != null && item.seatWidthAttrs.length > 0) {
                    item.seatWidthAttrs.forEach(function (attrObj, index) {
                        item.stocks.forEach(function (stock) {
                            if (attrObj.id == stock.seatWidthAttrId) {
                                if (stock.stockId == obj.stockId) {
                                    attrObj.stocks.splice(index, 1);
                                }
                            }
                        });
                    });
                }
            });
            v.query.stocks.forEach(function (stock, index) {
                if (stock.stockId == obj.stockId) {
                    v.query.stocks.splice(index, 1);
                }
            });
            UJ.SaveStorage(StorageKey.packingCreateOrderStocks + v.orderId + "_", v.query.stocks);

            stocks.splice(idx, 1);
        },
        addProduct() {
            var v = this;

            var ltDetails = [];
            v.list.forEach(function (item) {
                if (item.stocks != null && item.stocks.length > 0) {
                    ltDetails.push(item);
                }
            });

            if (ltDetails.length == 0) {
                alert("請輸入選擇要出貨的產編!");
                return false;
            }
            else {
                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.AddProduct({
                            orderId: v.orderId,
                            products: v.list
                        });
                        if (res.status == RESPONSE_STATUS.OK) {
                            showMsg('加入成功!', null, null, null, null, function () {
                                UJ.SaveStorage(StorageKey.packingCreateOrderDetails + v.orderId + "_", res.data);
                                v.closeAndReloadParent();
                            });

                        } 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;
                        }
                    }
                });
            }
        },
        closeAndReloadParent() {
            UJ.ResetStorage(StorageKey.packingCreateOrderStocks);
            $("body").resetStorage(this.StorageKey);
            CloseAndReloadParent();
        }
    }
});
