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=202501171249';
import { RESPONSE_STATUS } from '/js/constants.js';
import { Decorator } from '/js/util/dacorator.js';

var vMain = new Vue({
    el: "#dvMain",
    data: function () {
        return {
            pageTitle: "營業報表",
            authDesc: "報表_營業報表",
            isSystemManager: false,
            isLoading: false,
            isFinishRequest: true,
            ltMarket: [],
            ltStore: [],
            ltSource: [],
            ltPayMethod: [],
            ltPaymentStatus: [],
            query: {
                marketId: -1,
                marketName: "",
                storeId: -1,
                storeName: "",
                startMonth: "",
                endMonth: "",
                sources: [],
                payMethods: [],
                paymentStatuss: []
            },
            summary: [],
            list: [],
            totalPrice: 0,
            totalRent: 0,
            totalFreightage: 0,
            totalPurchase: 0,
            showResult: false,
            tabs: [
                { name: "明細", show: true },
                { name: "月統計", show: false },
            ],
            trColumns: [
                { css: "sortable text-center", col: "idx", title: "" },
                { css: "sortable", col: "revenueMonth", title: "對帳月份" },
                { css: "sortable", col: "enSource", title: "來源" },
                { css: "sortable", col: "ownerStoreShortName", title: "來源門市" },
                { css: "sortable", col: "tenantName", title: "承租人" },
                { css: "sortable", col: "deliveryReceiver", title: "使用人" },
                { css: "sortable", col: "productCode", title: "項目" },
                { css: "sortable", col: "seatWidthAttrName", title: "座寬" },
                { css: "sortable", col: "buyTypeString", title: "類型" },
                { css: "sortable text-center", col: "startDate", title: "起租日" },
                { css: "sortable text-center", col: "endDate", title: "退租日" },
                { css: "sortable text-center", col: "statusString", title: "租賃狀態" },
                { css: "sortable text-righ", col: "qty", title: "數量" },
                { css: "sortable text-righ", col: "periodQty", title: "租借期數" },
                { css: "sortable text-righ", col: "totalPrice", title: "租金" },
                { css: "sortable text-righ", col: "totalRent", title: "營收" },
                { css: "sortable text-righ", col: "totalFreightage", title: "運費" },
                { css: "sortable text-righ", col: "totalPurchase", title: "加購" },
                { css: "sortable", col: "shippingMethodString", title: "出貨方式" },
                { css: "sortable", col: "payMethodString", title: "付款方式" },
                { css: "sortable", col: "paymentStatusString", title: "付款狀態" },
                { css: "sortable", col: "paymentDatetime", title: "付款日期" },
                { css: "sortable", col: "orderNum", title: "訂單編號" },
                { css: "sortable", col: "enSource", title: "來源" },
            ],
            sortKey: "",       // Key for sorting
            sortOrder: 1      // 1: Ascending, -1: Descending
        };
    },
    created: async function () {
        var v = this;
        v.isSystemManager = await AuthDataService.IsSystemManager();
        v.ltMarket = await UniversalDataService.GetMarket();
        v.ltStore = await UniversalDataService.GetStore();
        v.ltSource = await UniversalDataService.GetOrderSource();
        v.ltPayMethod = await UniversalDataService.GetOrderMainPayMethod();
        v.ltPaymentStatus = await UniversalDataService.GetPaymentStatus();
        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: {
        sortTable() {
            var v = this;
            var ltSort = v.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;
                }
            });
        },
        clearCriteria() {
            var v = this;
            
            v.query.marketId = -1;
            v.query.marketName = "";
            $('#query-market').val('');

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

            var sd = (new Date()).addMonths(-1);
            v.query.startMonth = sd.format("yyyy-MM-01");
            v.changeDate('start');

            v.query.sources = [];
            v.query.payMethods = [];
            v.query.paymentStatuss = [];
            v.sortKey = "";
            v.sortOrder = 1;

            v.getList();
        },
        changeDate(type) {
            var v = this;
            if (type == "start") {
                v.query.endMonth = v.query.startMonth;
            }
        },
        async getList() {
            var v = this;
            var isValid = true;
            if (v.query.startMonth == null || v.query.startMonth.length == 0) {
                v.showResult = false;
                isValid = false;
            }
            if (v.query.endMonth == null || v.query.endMonth.length == 0) {
                v.showResult = false;
                isValid = false;
            }

            if (isValid) {
                v.isLoading = true;
                v.isFinishRequest = false;
                v.sortKey = "";
                v.sortOrder = 1;

                let res = await ReportDataService.GetOperatingRental(v.query);
                if (res.status == RESPONSE_STATUS.OK) {
                    var data = res.data;
                    v.list = data.list;
                    v.summary = data.summary;

                    v.totalPrice = 0;
                    v.totalRent = 0;
                    v.totalFreightage = 0;
                    v.totalPurchase = 0;

                    var trcss = "tr0";
                    v.list.forEach(function (item, idx) {
                        item.idx = idx + 1;
                        item.startDate = Decorator.ChangeISODateTimeToDate(item.startDate);
                        item.endDate = Decorator.ChangeISODateTimeToDate(item.endDate);
                        item.paymentDatetime = Decorator.ChangeISODateTimeToDate(item.paymentDatetime);
                        if (idx > 0) {
                            if (item.orderNum.indexOf(v.list[idx - 1].orderNum) < 0) {
                                if (trcss == "tr0") {
                                    trcss = "tr1";
                                } else {
                                    trcss = "tr0";
                                }
                            }
                        }
                        item.trcss = trcss;
                        v.totalPrice += parseInt(item.totalPrice);
                        v.totalRent += parseInt(item.totalRent);
                        v.totalFreightage += parseInt(item.totalFreightage);
                        v.totalPurchase += parseInt(item.totalPurchase);
                    });
                  
                    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(idx) {
            var v = this;
            var key = v.trColumns[idx].col;
            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(idx) {
            var v = this;
            var key = v.trColumns[idx].col;
            var css = v.trColumns[idx].css;
            if (v.sortKey === key) {
                if (v.sortOrder === 1) {
                    return css + " asc";
                } else {
                    return css + " desc";
                }
            }
            return css;
        },
        changeStatus(type, val, ckd) {
            var v = this;

            var isExists = false;
            var lt = [];
            switch (type) {
                case "source":
                    lt = v.query.sources;
                    break;
                case "payMethod":
                    lt = v.query.payMethods;
                    break;
                case "paymentStatus":
                    lt = v.query.paymentStatuss;
                    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 "source":
                    lt = v.query.sources;
                    break;
                case "payMethod":
                    lt = v.query.payMethods;
                    break;
                case "paymentStatus":
                    lt = v.query.paymentStatuss;
                    break;
            }

            var res = false;
            lt.forEach(function (value, idx) {
                if (value == val) {
                    res = true;
                }
            });
            return res;
        },
        //匯出報表
        async exportData() {
            var v = this;
            v.isLoading = true;
            v.isFinishRequest = false;
            let res = await ReportDataService.ExportOperatingRental(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");
            });
        }
    }
});
