import { AuthDataService } from '/js/ApiDataServer/Auth.js?tf=202411121501';
import { UniversalDataService } from '/js/ApiDataServer/Universal.js?tf=202411131831';
import { ReportDataService } from '/js/ApiDataServer/Report.js?tf=202601310005';
import { RESPONSE_STATUS } from '/js/constants.js';
import { Decorator } from '/js/util/dacorator.js?tf=202507260259';

var vMain = new Vue({
    el: "#dvMain",
    data: function () {
        return {
            pageTitle: "門市對帳報表",
            authDesc: "報表_門市對帳報表",
            isSystemManager: false,
            isLoading: false,
            isFinishRequest: true,
            tabs: [
                {
                    name: "租賃", show: true, isInvoice: false,
                    list: [],
                    totalPrice: 0,
                    total: 0,
                    trColumns: [
                        { css: "sortable text-center", col: "idx", title: "" },
                        { css: "text-center", col: "", title: "checkbox" },
                        { css: "text-center", col: "", title: "對帳月份" },
                        { css: "", col: "", title: "" },
                        { css: "sortable", col: "productCode", title: "項目" },
                        { css: "sortable", col: "seatWidthAttrName", title: "座寬" },
                        { css: "", col: "", title: "" },
                        { css: "sortable", col: "buyTypeString", title: "類型" },
                        { css: "sortable", col: "tenantName", title: "承租人" },
                        { css: "sortable", col: "deliveryReceiver", title: "使用人" },
                        { css: "sortable", col: "ownerStoreName", title: "門市" },
                        { css: "sortable text-center", col: "firstDate", title: "起租日期" },
                        { css: "sortable text-center", col: "startDate", title: "計租(起)" },
                        { css: "sortable text-center", col: "endDate", title: "計租(尾)" },
                        { css: "sortable", col: "statusString", title: "租賃狀態" },
                        { css: "text-right", col: "", title: "數量" },
                        { css: "text-right", col: "", title: "租借期數" },
                        { css: "text-right", col: "", title: "租金" },
                        { css: "text-right", col: "", title: "對帳金額" },
                        { css: "sortable", col: "orderNum", title: "訂單編號" },
                        { css: "width150", col: "", title: "備註" }
                    ]
                },
                {
                    name: "運費", show: false, isInvoice: false,
                    list: [],
                    total: 0,
                    trColumns: [
                        { css: "sortable text-center", col: "idx", title: "" },
                        { css: "text-center", col: "", title: "checkbox" },
                        { css: "text-center", col: "", title: "對帳月份" },
                        { css: "", col: "", title: "" },
                        { css: "sortable", col: "productCode", title: "項目" },
                        { css: "sortable", col: "seatWidthAttrName", title: "座寬" },
                        { css: "sortable", col: "tenantName", title: "承租人" },
                        { css: "sortable", col: "deliveryReceiver", title: "使用人" },
                        { css: "sortable", col: "ownerStoreName", title: "門市" },
                        { css: "sortable", col: "freightageAreaName", title: "運費區別" },
                        { css: "sortable text-center", col: "date", title: "起始日/建立日" },
                        { css: "text-right", col: "", title: "數量" },
                        { css: "text-right", col: "", title: "金額" },
                        { css: "text-right", col: "", title: "小計金額" },
                        { css: "sortable", col: "orderNum", title: "訂單編號" }
                    ]
                },
                {
                    name: "維修費", show: false, isInvoice: false,
                    list: [],
                    total: 0,
                    trColumns: [
                        { css: "sortable text-center", col: "idx", title: "" },
                        { css: "text-center", col: "", title: "checkbox" },
                        { css: "text-center", col: "", title: "對帳月份" },
                        { css: "", col: "", title: "" },
                        { css: "sortable", col: "tenantName", title: "承租人" },
                        { css: "sortable", col: "deliveryReceiver", title: "使用人" },
                        { css: "sortable", col: "paymentStatusString", title: "狀態" },
                        { css: "sortable", col: "repaireDate", title: "維修日期" },
                        { css: "text-right", col: "", title: "費用" },
                        { css: "", col: "", title: "說明" },
                        { css: "", col: "", title: "付款日期" },
                        { css: "sortable", col: "orderNum", title: "訂單編號" }
                    ]
                },
                {
                    name: "耗材費", show: false, isInvoice: false,
                    list: [],
                    total: 0,
                    trColumns: [
                        { css: "sortable text-center", col: "idx", title: "" },
                        { css: "text-center", col: "", title: "checkbox" },
                        { css: "text-center", col: "", title: "對帳月份" },
                        { css: "", col: "", title: "" },
                        { css: "sortable", col: "productCode", title: "項目" },
                        { css: "sortable", col: "seatWidthAttrName", title: "座寬" },
                        { css: "sortable", col: "tenantName", title: "承租人" },
                        { css: "sortable", col: "deliveryReceiver", title: "使用人" },
                        { css: "sortable", col: "ownerStoreName", title: "門市" },
                        { css: "sortable text-center", col: "date", title: "起始日/建立日" },
                        { css: "text-right", col: "", title: "數量" },
                        { css: "text-right", col: "", title: "金額" },
                        { css: "text-right", col: "", title: "小計金額" },
                        { css: "sortable", col: "orderNum", title: "訂單編號" }
                        //{ css: "sortable", col: "paymentStatusString", title: "狀態" },
                        //{ css: "text-right", col: "", title: "費用" },
                        //{ css: "", col: "", title: "說明" },
                        //{ css: "", col: "", title: "付款日期" },
                        //{ css: "sortable", col: "orderNum", title: "訂單編號" }
                    ]
                },
                {
                    name: "租賃發票", show: false, isInvoice: true,
                    obj: {
                        applyDate: "",
                        buyer: {},
                        list: [],
                        subtotal: 0,
                        totalTax: 0,
                        totalAmt: 0
                    }
                },
                {
                    name: "加購發票", show: false, isInvoice: true,
                    obj: {
                        applyDate: "",
                        buyer: {},
                        list: [],
                        subtotal: 0,
                        totalTax: 0,
                        totalAmt: 0
                    }
                },
                {
                    name: "運費發票", show: false, isInvoice: true,
                    obj: {
                        applyDate: "",
                        buyer: {},
                        list: [],
                        subtotal: 0,
                        totalTax: 0,
                        totalAmt: 0
                    }
                },
                {
                    name: "維修費發票", show: false, isInvoice: true,
                    obj: {
                        applyDate: "",
                        buyer: {},
                        list: [],
                        subtotal: 0,
                        totalTax: 0,
                        totalAmt: 0
                    }
                },
                {
                    name: "耗材費發票", show: false, isInvoice: true,
                    obj: {
                        applyDate: "",
                        buyer: {},
                        list: [],
                        subtotal: 0,
                        totalTax: 0,
                        totalAmt: 0
                    }
                },
                {
                    name: "轉介", show: false, isInvoice: false,
                    list: [],
                    totalPrice: 0,
                    total: 0,
                    trColumns: [
                        { css: "sortable text-center", col: "idx", title: "" },
                        { css: "text-center", col: "", title: "checkbox" },
                        { css: "text-center", col: "", title: "對帳月份" },
                        { css: "", col: "", title: "" },
                        { css: "sortable", col: "productCode", title: "項目" },
                        { css: "sortable", col: "seatWidthAttrName", title: "座寬" },
                        { css: "sortable", col: "buyTypeString", title: "類型" },
                        { css: "sortable", col: "tenantName", title: "承租人" },
                        { css: "sortable", col: "deliveryReceiver", title: "使用人" },
                        { css: "sortable", col: "ownerStoreName", title: "門市" },
                        { css: "sortable text-center", col: "firstDate", title: "起租日期" },
                        { css: "sortable text-center", col: "startDate", title: "計租(起)" },
                        { css: "sortable text-center", col: "endDate", title: "計租(尾)" },
                        { css: "sortable", col: "statusString", title: "租賃狀態" },
                        { css: "text-right", col: "", title: "數量" },
                        { css: "text-right", col: "", title: "租借期數" },
                        { css: "text-right", col: "", title: "營業額" },
                        { css: "text-right", col: "", title: "對帳金額" },
                        { css: "sortable", col: "orderNum", title: "訂單編號" },
                        { css: "width150", col: "", title: "備註" }
                    ]
                }
            ],
            ltMarket: [],
            ltStore: [],
            ltVerified: [],
            query: {
                marketId: -1,
                marketName: "",
                storeId: -1,
                storeName: "",
                startDateFrom: null,
                startDateTo: null,
                endDateFrom: null,
                endDateTo: null,
                verifiedMon: null,
                verified: -1
            },
            showResult: false,
            checkAll: false,
            verifiedMonth: null,
            ltChecked: [],
            ltInvoiceTypes: [],
            ltBillTypes: [],
            sortKey: "",       // Key for sorting
            sortOrder: 1      // 1: Ascending, -1: Descending
        };
    },
    created: async function () {
        var v = this;
        v.isSystemManager = await AuthDataService.IsSystemManager();
        v.ltMarket = await ReportDataService.GetMarket();
        v.ltStore = await UniversalDataService.GetStore();
        v.ltVerified = await UniversalDataService.GetVerified();
        v.ltInvoiceTypes = await UniversalDataService.GetMarketInvoiceType();
        v.ltBillTypes = await UniversalDataService.GetMarketBillType();
        v.initAutocomplete();

        v.clearCriteria();
    },
    updated: function () {
        var v = this;
        initAdminutil();
        if (v.isFinishRequest) {
            setTimeout(function () {
                v.isLoading = false;
            }, 100);
        } else {
            v.isLoading = true;
        }
    },
    components: {
        'date-picker': DatePicker
    },
    computed: {
        sortRentalTable() {
            var v = this;
            var ltSort = v.tabs[0].list;
            if (v.sortKey !== "") {
                ltSort.sort((a, b) => {
                    if (typeof a[v.sortKey] === 'string') {
                        return v.sortOrder * a[v.sortKey].localeCompare(b[v.sortKey]);
                    }
                    return v.sortOrder * (a[v.sortKey] - b[v.sortKey]);
                });
            }
            return ltSort;
        },
        sortFreightageTable() {
            var v = this;
            var ltSort = v.tabs[1].list;
            if (v.sortKey !== "") {
                ltSort.sort((a, b) => {
                    if (typeof a[v.sortKey] === 'string') {
                        return v.sortOrder * a[v.sortKey].localeCompare(b[v.sortKey]);
                    }
                    return v.sortOrder * (a[v.sortKey] - b[v.sortKey]);
                });
            }
            return ltSort;
        },
        sortRepairingTable() {
            var v = this;
            var ltSort = v.tabs[2].list;
            if (v.sortKey !== "") {
                ltSort.sort((a, b) => {
                    if (typeof a[v.sortKey] === 'string') {
                        return v.sortOrder * a[v.sortKey].localeCompare(b[v.sortKey]);
                    }
                    return v.sortOrder * (a[v.sortKey] - b[v.sortKey]);
                });
            }
            return ltSort;
        },
        sortConsumableFeeTable() {
            var v = this;
            var ltSort = v.tabs[3].list;
            if (v.sortKey !== "") {
                ltSort.sort((a, b) => {
                    if (typeof a[v.sortKey] === 'string') {
                        return v.sortOrder * a[v.sortKey].localeCompare(b[v.sortKey]);
                    }
                    return v.sortOrder * (a[v.sortKey] - b[v.sortKey]);
                });
            }
            return ltSort;
        },
        sortTransferTable() {
            var v = this;
            var ltSort = v.tabs[9].list;
            if (v.sortKey !== "") {
                ltSort.sort((a, b) => {
                    if (typeof a[v.sortKey] === 'string') {
                        return v.sortOrder * a[v.sortKey].localeCompare(b[v.sortKey]);
                    }
                    return v.sortOrder * (a[v.sortKey] - b[v.sortKey]);
                });
            }
            return ltSort;
        }
    },
    methods: {
        showDIV(idx) {
            var v = this;
            v.tabs.forEach(function (obj, index) {
                if (idx == index) {
                    obj.show = true;
                } else {
                    obj.show = false;
                }
            });

            v.getList();
        },
        clearCriteria() {
            var v = this;
            v.query.marketId = -1;
            v.query.marketName = "";
            $('#query-market').val('');

            v.query.storeId = -1;
            v.query.storeName = "";
            $('#query-store').val('');

            v.query.startDateFrom = null;
            v.query.startDateTo = null;
            v.query.endDateFrom = null;
            v.query.endDateTo = null;

            v.query.verifiedMon = null;
            v.query.verified = -1;

            v.showResult = false;
        },
        changeDate(type) {
            var v = this;
            if (type == "start") {
                if (v.query.startDateFrom != null && v.query.startDateFrom != "") {
                    var sd = new Date(v.query.startDateFrom);
                    var ed = new Date(sd.getFullYear(), sd.getMonth(), 1);
                    v.query.startDateTo = ed.addMonths(1).addDays(-1).format("yyyy-MM-dd");
                    v.query.endDateFrom = null;
                    v.query.endDateTo = null;
                    v.verifiedMonth = ed.format("yyyy-MM-dd");
                }
            }
            if (type == "end") {
                if (v.query.endDateFrom != null && v.query.endDateFrom != "") {
                    var sd = new Date(v.query.endDateFrom);
                    var ed = new Date(sd.getFullYear(), sd.getMonth(), 1);
                    v.query.endDateTo = ed.addMonths(1).addDays(-1).format("yyyy-MM-dd");
                    v.query.startDateFrom = null;
                    v.query.startDateTo = null;
                    v.verifiedMonth = ed.format("yyyy-MM-dd");
                }
            }
        },
        getList() {
            var v = this;
            if (v.query.marketId > 0 || v.query.storeId > 0) {
                v.showResult = true;
                v.tabs.forEach(function (obj, index) {
                    if (obj.show) {
                        //發票
                        if (obj.isInvoice) {
                            v.getBillInvoice(index, obj.name);
                        } else {
                            v.getBill(index, obj.name);
                        }
                        v.ltChecked = [];
                        v.checkAll = false;
                    }
                });
            } else {
                v.showResult = false;
            }
        },
        //租賃, 運費, 維修費, 轉介明細
        async getBill(tabIdx, tabName) {
            var v = this;
            if ((v.query.startDateFrom != null && v.query.startDateFrom.length > 0)
                || (v.query.endDateFrom != null && v.query.endDateFrom.length > 0)
                || (v.query.startDateTo != null && v.query.startDateTo.length > 0)
                || (v.query.endDateTo != null && v.query.endDateTo.length > 0)
                || (v.query.verifiedMon != null && v.query.verifiedMon.length > 0)) {
           
                v.isLoading = true;
                v.isFinishRequest = false;
                v.sortKey = "idx";
                v.sortOrder = 1;

                let res;
                //租賃
                if (tabName == "租賃") { res = await ReportDataService.GetStoreRental(v.query); }
                //運費
                if (tabName == "運費") { res = await ReportDataService.GetStoreFreightage(v.query); }
                //維修費
                if (tabName == "維修費") { res = await ReportDataService.GetStoreRepairing(v.query); }
                //耗材費
                if (tabName == "耗材費") { res = await ReportDataService.GetStoreConsumableFee(v.query); }
                //轉介
                if (tabName == "轉介") { res = await ReportDataService.GetStoreTransfer(v.query); }

                if (res.status == RESPONSE_STATUS.OK) {
                    var data = res.data;
                    v.tabs[tabIdx].list = data;
                    if (tabName == "租賃" || tabName == "轉介") {
                        v.tabs[tabIdx].totalPrice = 0;
                    }
                    v.tabs[tabIdx].total = 0;
                    v.tabs[tabIdx].list.forEach(function (item, idx) {
                        item.idx = idx + 1;
                        item.verifiedMonth = Decorator.ChangeISODateTimeToDateYYMM(item.verifiedMonth);
                        item.firstDate = Decorator.ChangeISODateTimeToDate(item.firstDate);
                        item.startDate = Decorator.ChangeISODateTimeToDate(item.startDate);
                        item.endDate = Decorator.ChangeISODateTimeToDate(item.endDate);
                        if (item.seatWidthAttrName == null) {
                            item.seatWidthAttrName = "";
                        }
                        if (tabName == "租賃" || tabName == "轉介") {
                            v.tabs[tabIdx].totalPrice += parseInt(item.totalPrice);
                            v.tabs[tabIdx].total += parseInt(item.totalCost);
                        } else if (tabName == "運費") {
                            item.date = Decorator.ChangeISODateTimeToDate(item.date);
                            v.tabs[tabIdx].total += parseFloat(item.freightage);
                        } else if (tabName == "維修費") {
                            item.repaireDate = Decorator.ChangeISODateTimeToDate(item.repaireDate);
                            item.paymentDatetime = Decorator.ChangeISODateTimeToDate(item.paymentDatetime);
                            v.tabs[tabIdx].total += parseFloat(item.fee);
                        } else if (tabName == "耗材費") {
                            item.date = Decorator.ChangeISODateTimeToDate(item.date);
                            v.tabs[tabIdx].total += parseFloat(item.subtotal);
                        }
                    });

                    v.isLoading = false;
                    v.isFinishRequest = true;
                    v.showResult = true;
                } 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;
                    }
                }
            } else {
                v.showResult = false;
            }
        },
        SelectAll(ckd, tabIdx, tabName) {
            var v = this;
            v.ltChecked = [];
            v.checkAll = ckd;
            v.tabs[tabIdx].list.forEach(async function (item) {
                if (ckd && item.enVerified == 0) {
                    if (tabName == "租賃" || tabName == "轉介") {
                        item.orderDetailIds.forEach(function (orderDetailId) {
                            v.ltChecked.push(orderDetailId);
                        });
                    } else if (tabName == "運費" || tabName == "耗材費") {
                        //訂單運費
                        if (item.detailId > 0) {
                            v.ltChecked.push(item.detailId);
                        } else if (item.otherId > 0) {
                            //額外運費
                            v.ltChecked.push(-item.otherId);
                        }
                    } else if (tabName == "維修費") {
                        v.ltChecked.push(item.otherId);
                    }
                }
            });
        },
        isExistsCheckList(item, tabName) {
            var v = this;

            var isExists = false;
            v.ltChecked.forEach(function (checkId) {
                if (tabName == "租賃" || tabName == "轉介") {
                    item.orderDetailIds.forEach(function (orderDetailId) {
                        if (checkId == orderDetailId) {
                            isExists = true;
                        }
                    });
                } else if (tabName == "運費" || tabName == "耗材費") {
                    if (checkId == item.detailId || checkId == -item.otherId) {
                        isExists = true;
                    }
                } else if (tabName == "維修費") {
                    //維修費
                    if (checkId == item.otherId) {
                        isExists = true;
                    }
                }
            });

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

            var isExists = false;
            v.ltChecked.forEach(function (checkId, idx) {
                if (tabName == "租賃" || tabName == "轉介") {
                    item.orderDetailIds.forEach(function (detailId) {
                        if (checkId == detailId) {
                            isExists = true;
                            if (!ckd) {
                                v.ltChecked.splice(idx, 1);
                            }
                        }
                    });
                } else if (tabName == "運費" || tabName == "耗材費") {
                    if (checkId == item.detailId || checkId == -item.otherId) {
                        isExists = true;
                        if (!ckd) {
                            v.ltChecked.splice(idx, 1);
                        }
                    }
                } else if (tabName == "維修費") {
                    if (checkId == item.otherId) {
                        isExists = true;
                        if (!ckd) {
                            v.ltChecked.splice(idx, 1);
                        }
                    }
                }
            });

            if (ckd && !isExists) {
                if (tabName == "租賃" || tabName == "轉介") {
                    item.orderDetailIds.forEach(function (orderDetailId) {
                        v.ltChecked.push(orderDetailId);
                    });
                } else if (tabName == "運費" || tabName == "耗材費") {
                    //訂單運費
                    if (item.detailId > 0) {
                        v.ltChecked.push(item.detailId);
                    } else if (item.otherId > 0) {
                        //額外運費
                        v.ltChecked.push(-item.otherId);
                    }
                } else if (tabName == "維修費") {
                    //維修費
                    v.ltChecked.push(item.otherId);
                }
            }
            if (!ckd) {
                v.checkAll = false;
            }
        },
        //對帳狀態
        async saveVerified(tabName) {
            var v = this;
            if (v.verifiedMonth == null) {
                showErrMsg("請選擇對帳月份", "", "warning", function () {
                    return false;
                });
                return false;
            }

            if (v.ltChecked != null && v.ltChecked.length > 0) {
                v.isFinishRequest = false;
                v.isLoading = true;

                var verifiedType = -1;
                if (tabName == "租賃" || tabName == "轉介") {
                    verifiedType = 100;
                } else if (tabName == "運費") {
                    verifiedType = 400;
                } else if (tabName == "維修費") {
                    verifiedType = 200;
                } else if (tabName == "耗材費") {
                    verifiedType = 500;
                }

                let res = await ReportDataService.UpdateVerified({
                    verifiedType: verifiedType,
                    list: v.ltChecked,
                    verifiedMonth: v.verifiedMonth
                });
                if (res.status == RESPONSE_STATUS.OK) {
                    showMsg('儲存成功!', null, null, null, null, function () {
                        v.getList();
                        v.checkAll = false;
                        v.ltChecked = [];
                    });
                } 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;
                }
            } else {
                showErrMsg("請勾選要標記的項目", "", "warning", function () {
                    return false;
                });
            }
        },
        async restoreVerified(item, tabName) {
            var v = this;
            swal({
                title: "確定要恢復為未對帳？",
                type: "question",
                showCancelButton: true,
                confirmButtonText: "確定",
                cancelButtonText: "取消"
            }).then(async function (result) {
                if (result.value) {
                    v.isFinishRequest = false;
                    v.isLoading = true;

                    var verifiedType = -1;
                    var list = [];
                    if (tabName == "租賃" || tabName == "轉介") {
                        verifiedType = 100;
                        list = item.orderDetailIds;
                    } else if (tabName == "運費") {
                        verifiedType = 400;
                        if (item.detailId > 0) {
                            list.push(item.detailId);
                        } else if (item.otherId > 0) {
                            list.push(-item.otherId);
                        }
                    } else if (tabName == "維修費") {
                        verifiedType = 200;
                        list.push(item.otherId);
                    } else if (tabName == "耗材費") {
                        verifiedType = 500;
                        if (item.detailId > 0) {
                            list.push(item.detailId);
                        } else if (item.otherId > 0) {
                            list.push(-item.otherId);
                        }
                    }

                    let res = await ReportDataService.RestoreVerified({
                        verifiedType: verifiedType,
                        list: list
                    });
                    if (res.status == RESPONSE_STATUS.OK) {
                        showMsg('恢復成功!', null, null, null, null, function () {
                            v.getList();
                        });
                    } 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 getBillInvoice(tabIdx, tabName) {
            var v = this;
            v.isLoading = true;
            v.isFinishRequest = false;
            v.sortKey = "";
            v.sortOrder = 1;

            let res;
            //租賃
            if (tabName == "租賃發票") { res = await ReportDataService.GetStoreRentalInvoice(v.query); }
            //加購
            if (tabName == "加購發票") { res = await ReportDataService.GetStoreAdditionInvoice(v.query); }
            //運費
            if (tabName == "運費發票") { res = await ReportDataService.GetStoreFreightageInvoice(v.query); }
            //維修費
            if (tabName == "維修費發票") { res = await ReportDataService.GetStoreRepairingInvoice(v.query); }
            //耗材
            if (tabName == "耗材費發票") { res = await ReportDataService.GetStoreConsumableFeeInvoice(v.query); }
            
            if (res.status == RESPONSE_STATUS.OK) {
                var data = res.data;
                v.tabs[tabIdx].obj = data;
                v.isLoading = false;
                v.isFinishRequest = true;
                v.showResult = true;
            } 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;
                }
            }
        },
        sortColumn(tabIdx, colIdx) {
            var v = this;
            var key = v.tabs[tabIdx].trColumns[colIdx].col;
            if (key.length > 0) {
                if (v.sortKey === key) {
                    v.sortOrder = -v.sortOrder; // Reverse the order if the same column is clicked
                } else {
                    v.sortKey = key;
                    v.sortOrder = 1; // Set ascending order for the new column
                }
            }
        },
        sortIcon(tabIdx, colIdx) {
            var v = this;
            var key = v.tabs[tabIdx].trColumns[colIdx].col;
            var css = v.tabs[tabIdx].trColumns[colIdx].css;
            if (v.sortKey === key) {
                if (v.sortOrder === 1) {
                    return css + " asc";
                } else {
                    return css + " desc";
                }
            }
            return css;
        },
        //匯出報表
        async exportData() {
            var v = this;
            v.isLoading = true;
            v.isFinishRequest = false;
            let res = await ReportDataService.ExportStoreBill(v.query);
            if (res.status != RESPONSE_STATUS.OK) {
                alert('匯出失敗');
                v.isFinishRequest = true;
                v.isLoading = false;
                return;
            } else {
                v.isFinishRequest = true;
                v.isLoading = false;
            }
        },
        initAutocomplete() {
            var v = this;
            //setting autocomplete
            $('#query-market').autocomplete({
                minLength: 0,
                delay: 50, //延遲
                source: (request, response) => {
                    var markets = v.ltMarket.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.marketId = ui.item.id;
                    v.query.marketName = ui.item.label;

                    if (v.query.storeName.trim().length > 0) {
                        var stores = v.ltStore.filter(function (item) {
                            if (v.query.marketId < 0 || (v.query.marketId > 0 && item.marketId == v.query.marketId)) {
                                return (v.query.storeName.toLowerCase().indexOf(item.name.toLowerCase()) > -1) ||
                                    (item.shortName != null && item.shortName != '' && v.query.storeName.toLowerCase().indexOf(item.shortName.toLowerCase()) > -1);
                            }
                        });

                        if (stores.length == 0) {
                            v.query.storeId = -1;
                            v.query.storeName = "";
                            $('#query-store').val('');
                        }
                    }
                    v.getList();
                },
                change: function (event, ui) {
                    //清空輸入框
                    if (ui.item == null) {
                        v.query.marketId = -1;
                        v.query.marketName = "";
                        v.getList();
                    }
                }
            }).focus(function () {
                //點輸入框就秀出下拉選單
                $(this).trigger("keydown");
            }).change(function () {
                if ($(this).val().trim() == '' || $(this).val() == '') {
                    v.query.marketId = -1;
                    v.query.marketName = "";
                    v.getList();
                }
            }).data("ui-autocomplete")._renderItem = function (ul, item) {
                return $("<li>")
                    .addClass("multiline-label")
                    .append("<div>" + item.label + "</div>")
                    .appendTo(ul);
            };

            //setting autocomplete
            $('#query-store').autocomplete({
                minLength: 0,
                delay: 50, //延遲
                source: (request, response) => {
                    var stores = v.ltStore.filter(function (item) {
                        if (v.query.marketId < 0 || (v.query.marketId > 0 && item.marketId == v.query.marketId)) {
                            return (item.name.toLowerCase().indexOf(request.term.toLowerCase()) > -1) ||
                                (item.shortName != null && item.shortName != '' && item.shortName.toLowerCase().indexOf(request.term.toLowerCase()) > -1);
                        }
                    });

                    if (request.term.trim().length > 0 && stores.length == 0) {
                        v.query.storeId = -1;
                        v.query.storeName = "";
                        $('#query-store').val('');
                    }

                    response($.map(stores, function (item) {
                        var name = item.name;
                        if (item.shortName != null && item.shortName != '') { name += "(" + item.shortName + ")"; }
                        return {
                            // label和value是基本參數
                            label: `${name}`,  //列表所顯示的文字
                            value: name,  	//列表選項的值
                            id: item.id
                        };
                    }));
                },
                select: function (event, ui) {
                    //選取
                    v.query.storeId = ui.item.id;
                    v.query.storeName = ui.item.label;
                    v.getList();
                },
                change: function (event, ui) {
                    //清空輸入框
                    if (ui.item == null) {
                        v.query.storeId = -1;
                        v.query.storeName = "";
                        v.getList();
                    }
                }
            }).focus(function () {
                //點輸入框就秀出下拉選單
                $(this).trigger("keydown");
            }).change(function () {
                if ($(this).val().trim() == '' || $(this).val() == '') {
                    v.query.storeId = -1;
                    v.query.storeName = "";
                    v.getList();
                }
            }).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");
            });
        }
    }
});
