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 { OemOrderDataService } from '/js/ApiDataServer/OemOrder.js';
import { RESPONSE_STATUS } from '/js/constants.js';
import { StorageKey } from '/js/constants.js';
import { enMessage } from '/js/constants.js';
import { Decorator } from '/js/util/dacorator.js?tf=202507291309';
import { UJ } from '/js/util/uj.js';

var vMain = new Vue({
    el: "#dvMain",
    data: function () {
        return {
            pageTitle: "[代工清消收送] 出貨單-加入輔具-庫存清單",
            authDesc: "代工_出貨管理",
            isSystemManager: false,
            isLoading: false,
            isBindFancybox: true,
            showCloseBTN: false,
            orderId: -1,
            productObj: {
                id: -1
            },
            attrObj: {
                id: -1
            },
            list: [],
            ltChecked: []
        };
    },
    created: async function () {
        var v = this;
        v.isSystemManager = await AuthDataService.IsSystemManager();
        v.orderId = UJ.getParameterByName("oid");
        v.productObj.id = UJ.getParameterByName("id");

        v.attrObj.id = UJ.getParameterByName("aid");
        if (v.attrObj.id != null && v.attrObj.id > 0) {
            var ltSeatWidthAttrs = await UniversalDataService.GetOemltSeatWidthAttrs();
            ltSeatWidthAttrs.forEach(function (item) {
                if (item.id == v.attrObj.id) {
                    v.attrObj = item;
                }
            });
        }

        v.loadData();
    },
    updated: function () {
        var v = this;
        if (!v.isBindFancybox) {
            bindFancybox();
            v.isBindFancybox = true;
        }

        initAdminutil();
        setTimeout(function () {
            v.isLoading = false;
        }, 100);
    },
    methods: {
        async loadData() {
            var v = this;
            v.ltChecked = UJ.GetStorage(StorageKey.oemOrderStocks + v.orderId + "_");
            var res = await OemDataService.GetProduct(v.productObj.id);
            if (res.status == RESPONSE_STATUS.OK) {
                v.productObj = res.data;
                v.getList();

            } else {
                var data = res.data;
                showErrMsg(data.message, "", "", function () {
                    if (data.enMessage == enMessage.NotFound) {
                        v.closeAndReloadParent();
                    }
                });
            }
        },
        async getList() {
            var v = this;
            v.isLoading = true;

            let res = await OemOrderDataService.GetAvailableStockList(v.productObj.id, v.attrObj.id);
            if (res.status == RESPONSE_STATUS.OK) {
                v.list = res.data;
                v.list.forEach(function (item) {
                    item.modifyDate = Decorator.ChangeISODateTimeToDate(item.modifyDatetime);
                });

                // 排序：依 modifyDatetime 升冪（舊到新）
                v.list.sort(function (a, b) {
                    return new Date(a.modifyDatetime) - new Date(b.modifyDatetime);
                });

                v.isLoading = false;
                v.isFinishRequest = true;

            } else {
                var data = res.data;
                if (res.httpStatus === 401) {
                    showErrMsg(data.message, "", "", function () {
                        location.href = "/";
                    });
                } else {
                    showErrMsg(data.message, "", "", null);
                    v.isFinishRequest = true;
                }
            }
        },
        selected(item) {
            var v = this;
            var ckd = !v.isChecked(item);
            var stocks = UJ.GetStorage(StorageKey.oemOrderStocks + v.orderId + "_");
            if (stocks != null) {
                var isExists = false;
                stocks.forEach(function (stock, idx) {
                    if (stock.stockId == item.stockId) {
                        isExists = true;
                        if (!ckd) {
                            stocks.splice(idx, 1);
                        }
                    }
                });
                if (ckd && !isExists) {
                    stocks.push(item);
                }
            } else {
                stocks = [];
                if (ckd) {
                    stocks.push(item);
                }
            }
            UJ.SaveStorage(StorageKey.oemOrderStocks + v.orderId + "_", stocks);
            v.closeAndReloadParent();
        },
        isChecked(stock) {
            var v = this;
            var isExists = false;
            if (v.ltChecked != null && v.ltChecked.length > 0) {
                v.ltChecked.forEach(function (obj) {
                    if (obj.stockId == stock.stockId) {
                        isExists = true;
                    }
                });
            }
            return isExists;
        },
        closeAndReloadParent() {
            CloseAndReloadParent();
        }
    }
});
