import { UniversalDataService } from '/js/ApiDataServer/Universal.js?tf=202411131831';
import { ReportDataService } from '/js/ApiDataServer/Report.js';
import { AuthDataService } from '/js/ApiDataServer/Auth.js?tf=202411121501';
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: false,
            isBindFancybox: true,
            ltType: [],
            ltSource: [],
            ltRentedFor: [],
            ltMarket: [],
            ltStore: [],
            ltShippingMethod: [],
            ltCategory: [],
            ltBuyType: [],
            ltDetailStatus: [],
            ltPayMethod: [],
            ltPaymentStatus: [],
            query: {
                types: [],
                sources: [],
                rentedFors: [],
                marketId: -1,
                marketName: "",
                storeId: -1,
                storeName: "",
                createDateS: null,
                createDateE: null,
                shippingMethods: [],
                keyword: "",
                parentCateId: -1,
                categoryId: -1,
                buyTypes: [],
                detailStatuss: [],
                rentalStartDateS: null,
                rentalStartDateE: null,
                rentalEndDateS: null,
                rentalEndDateE: null,
                payMethods: [],
                paymentStatuss: [],
                currentPage: 1,
                pageSize: 50
            },
            list: [],
            pager: {},
            trColumns: [
                { css: "sortable", col: "typeString", title: "訂單" },
                { css: "sortable", col: "sourceString", title: "來源" },
                { css: "sortable", col: "rentedForString", title: "租借目的" },
                { css: "sortable", col: "ownerStoreName", title: "來源門市" },
                { css: "sortable text-center", col: "createDatetime", title: "建立日" },
                { css: "sortable", col: "orderNum", title: "訂單編號" },
                { css: "sortable", col: "tenantName", title: "承租姓名" },
                { css: "sortable", col: "email", title: "Email" },
                { css: "sortable", col: "tenantMobile", title: "承租電話" },
                { css: "sortable", col: "shippingMethodString", title: "運送方式" },
                { css: "sortable", col: "deliveryReceiver", title: "使用人姓名" },
                { css: "sortable", col: "deliveryMobile", title: "使用人電話" },
                { css: "sortable", col: "deliveryAddress", title: "運送地址" },
                { css: "sortable", col: "takebackAddress", title: "回收地址" },
                { css: "sortable", col: "parentCategoryName", title: "產品大分類" },
                { css: "sortable", col: "categoryName", title: "產品小分類" },
                { css: "sortable", col: "buyTypeString", title: "類型" },
                { css: "sortable", col: "productCode", title: "型號" },
                { css: "sortable", col: "seatWidthAttrName", title: "座寬" },
                { css: "sortable", col: "propertyNoList", title: "產編" },
                { css: "sortable", col: "statusString", title: "狀態" },
                { css: "sortable text-center", col: "startDate", title: "起租/起展日" },
                { css: "sortable text-center", col: "endDate", title: "退租/退展日" },
                { css: "text-right", col: "", title: "數量" },
                { css: "text-right", col: "", title: "租金/售價" },
                { css: "text-center", col: "", title: "期數" },
                { css: "text-right", col: "", title: "耗材" },
                { css: "text-right", col: "", title: "押金" },
                { css: "text-right", col: "", title: "運費" },
                { css: "sortable text-center", col: "shipPlaceString", title: "出貨點" },
                { css: "sortable text-center", col: "payMethodString", title: "付款方式" },
                { css: "sortable text-center", col: "paymentStatusString", title: "付款狀態" },
                { css: "sortable text-center", col: "invoiceTypeString", title: "發票格式" },
                { css: "", col: "", title: "統編" },
                { css: "", col: "", title: "公司名稱" },
                { css: "sortable text-center", col: "billTypeString", title: "索取方式" },
                { css: "", col: "", title: "手機條碼載具" },
                { css: "", col: "", title: "發票收件人姓名" },
                { css: "", col: "", title: "發票收件人電話" },
                { css: "", col: "", title: "發票寄送地址" },
                { css: "", col: "", title: "其它費用" },
                { css: "", col: "", title: "備註" }
            ],
            sortKey: "",       // Key for sorting
            sortOrder: 1      // 1: Ascending, -1: Descending
        };
    },
    created: async function () {
        var v = this;
        v.isSystemManager = await AuthDataService.IsSystemManager();
        v.ltType = await UniversalDataService.GetOrderMainType();
        v.ltSource = await UniversalDataService.GetOrderSource();
        v.ltRentedFor = await UniversalDataService.GetRentedFor();
        v.ltMarket = await UniversalDataService.GetMarket();
        v.ltStore = await UniversalDataService.GetStore();
        v.ltShippingMethod = await UniversalDataService.GetShippingMethod();
        v.ltCategory = await UniversalDataService.GetProductCategory();
        v.ltBuyType = await UniversalDataService.GetBuyType();
        v.ltDetailStatus = await UniversalDataService.GetOrderDetailStatus();
        v.ltPayMethod = await UniversalDataService.GetOrderMainPayMethod();
        v.ltPaymentStatus = await UniversalDataService.GetPaymentStatus();
        v.initAutocomplete();

        v.clearCriteria();
    },
    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
    },
    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: {
        clearCriteria() {
            var v = this;
            v.query.types = [];
            v.query.sources = [];
            v.query.rentedFors = [];

            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(-2);
            v.query.createDateS = sd.format("yyyy-MM-01");
            v.query.createDateE = null;
            v.query.shippingMethods = [];
            v.query.keyword = "";
            v.query.parentCateId = -1;
            v.query.categoryId = -1;
            v.query.buyTypes = [];
            v.query.detailStatuss = [];

            v.query.rentalStartDateS = null;
            v.query.rentalStartDateE = null;
            v.query.rentalEndDateS = null;
            v.query.rentalEndDateE = null;

            v.query.payMethods = [];
            v.query.paymentStatuss = [];

            v.getList(1);
        },
        changeDate(type) {
            var v = this;
            if (type == "createDateS") {
                v.query.createDateE = v.query.createDateS;

            } else if (type == "rentalStartDateS") {
                if (v.query.rentalStartDateS == null) {
                    v.query.rentalStartDateE = null;
                } else {
                    var sd = new Date(v.query.rentalStartDateS);
                    var ed = new Date(sd.getFullYear(), sd.getMonth(), 1);
                    v.query.rentalStartDateE = ed.addMonths(2).addDays(-1).format("yyyy-MM-dd");
                }

            } else if (type == "rentalEndDateS") {
                if (v.query.rentalEndDateS == null) {
                    v.query.rentalEndDateE = null;
                } else {
                    var sd = new Date(v.query.rentalEndDateS);
                    var ed = new Date(sd.getFullYear(), sd.getMonth(), 1);
                    v.query.rentalEndDateE = ed.addMonths(2).addDays(-1).format("yyyy-MM-dd");
                }
            }
        },
        async getList(pageNum) {
            var v = this;
            v.isLoading = true;
            if (pageNum > 0) {
                v.query.currentPage = pageNum;
            }
            let res = await ReportDataService.GetRentalList(v.query);
            if (res.status == RESPONSE_STATUS.OK) {
                var data = res.data;

                v.list = data.list;
                v.list.forEach(function (item) {
                    item.createDatetime = Decorator.ChangeISODateTimeToDate(item.createDatetime);
                    if (item.startDate == null) {
                        item.startDate = "";
                    } else {
                        item.startDate = Decorator.ChangeISODateTimeToDate(item.startDate);
                    }
                    if (item.endDate == null) {
                        item.endDate = "";
                    } else {
                        item.endDate = Decorator.ChangeISODateTimeToDate(item.endDate);
                    }
                    item.propertyNoList = "";
                    if (item.ltStocks != null && item.ltStocks.length > 0) {
                        item.ltStocks.forEach(function (obj) {
                            item.propertyNoList += obj.propertyNo;
                        });
                    }
                });

                v.pager = data.pager;
                v.isBindFancybox = false;//重新綁定fancybox
                v.isFinishRequest = true;
                v.isLoading = false;
            } else {
                var data = res.data;
                if (res.httpStatus === 401) {
                    showErrMsg(data.message, "", "", function () {
                        location.href = "/";
                    });
                } else {
                    showErrMsg(data.message, "", "", null);
                    v.isFinishRequest = true;
                }
                v.isLoading = false;
            }
        },
        goPage(pageNum) {
            this.getList(pageNum);
        },
        keychange(event) {
            if (event.keyCode == 13) {
                this.getList(1);
            }
        },
        changeStatus(type, val, ckd) {
            var v = this;

            var isExists = false;
            var lt = [];
            switch (type) {
                case "type":
                    lt = v.query.types;
                    break;
                case "source":
                    lt = v.query.sources;
                    break;
                case "rentedFor":
                    lt = v.query.rentedFors;
                    break;
                case "shippingMethod":
                    lt = v.query.shippingMethods;
                    break;
                case "buyType":
                    lt = v.query.buyTypes;
                    break;
                case "detailStatus":
                    lt = v.query.detailStatuss;
                    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 "type":
                    lt = v.query.types;
                    break;
                case "source":
                    lt = v.query.sources;
                    break;
                case "rentedFor":
                    lt = v.query.rentedFors;
                    break;
                case "shippingMethod":
                    lt = v.query.shippingMethods;
                    break;
                case "buyType":
                    lt = v.query.buyTypes;
                    break;
                case "detailStatus":
                    lt = v.query.detailStatuss;
                    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;
        },
        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;
        },
        async exportData() {
            var v = this;
            let res = await ReportDataService.ExportRentalList(v.query);
            if (res.status != RESPONSE_STATUS.OK) {
                var data = res.data;
                if (res.httpStatus === 401) {
                    showErrMsg(data.message, "", "", null);

                } else {
                    showErrMsg("匯出失敗", "", "", null);
                }
                v.isFinishRequest = true;
            } else {
                v.isFinishRequest = true;
            }
        },
        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.goPage(1);
                },
                change: function (event, ui) {
                    //清空輸入框
                    if (ui.item == null) {
                        v.query.marketId = -1;
                        v.query.marketName = "";
                        v.goPage(1);
                    }
                }
            }).focus(function () {
                //點輸入框就秀出下拉選單
                $(this).trigger("keydown");
            }).change(function () {
                if ($(this).val().trim() == '' || $(this).val() == '') {
                    v.query.marketId = -1;
                    v.query.marketName = "";
                    v.goPage(1);
                }
            }).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.goPage(1);
                },
                change: function (event, ui) {
                    //清空輸入框
                    if (ui.item == null) {
                        v.query.storeId = -1;
                        v.query.storeName = "";
                        v.goPage(1);
                    }
                }
            }).focus(function () {
                //點輸入框就秀出下拉選單
                $(this).trigger("keydown");
            }).change(function () {
                if ($(this).val().trim() == '' || $(this).val() == '') {
                    v.query.storeId = -1;
                    v.query.storeName = "";
                    v.goPage(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");
            });
        }
    }
});
