import { UniversalDataService } from '/js/ApiDataServer/Universal.js?tf=202411131831';
import { OrderDataService } from '/js/ApiDataServer/Order.js';
import { AuthDataService } from '/js/ApiDataServer/Auth.js?tf=202411121501';
import { RESPONSE_STATUS } from '/js/constants.js';
import { Decorator } from '/js/util/dacorator.js';
import { StorageKey } from '/js/constants.js?tf=202505071852';
import { enMessage } from '/js/constants.js';
import { UJ } from '/js/util/uj.js';

var vMain = new Vue({
    el: "#dvMain",
    data: function () {
        return {
            pageTitle: "訂單列表",
            authDesc: "訂單_訂單管理",
            isSystemManager: false,
            isLoading: false,
            isFinishRequest: true,
            isBindFancybox: true,
            StorageKey: "assistiverent_admin_orderlist",
            memberObj: {},
            ltMarket: [],
            ltStore: [],
            ltType: [],
            ltSource: [],
            ltRentedFor: [],
            ltStatus: [],
            ltPaymentStatus: [],
            ltPayMethod: [],
            query: {
                createDateS: null,
                createDateE: null,
                marketId: -1,
                marketName: "",
                storeId: -1,
                storeName: "",
                keyword: "",
                propertyNo: "",
                types: [],
                sources: [],
                rentedFors: [],
                statuss: [],
                payments: [],
                paymethods: [],
                currentPage: 1,
                pageSize: 20
            },
            list: [],
            pager: {},
            orderItem: {},
            uploadImgType: "",
            lastActionId: []
        }
    },
    created: async function () {
        var v = this;
        var res = await AuthDataService.Me();
        if (res.status == RESPONSE_STATUS.OK) {
            v.memberObj = res.data;
            v.isSystemManager = v.memberObj.isSystemManager;

            if (v.memberObj.marketId > 0) {
                $('#query-market').prop("readonly", "readonly");
            }
        } else {
            var data = res.data;
            if (data.enMessage == enMessage.NotLogin) {
                await AuthDataService.Logout();
                location.href = '/';
            }
        }

        v.ltMarket = await UniversalDataService.GetMarket();
        v.ltStore = await UniversalDataService.GetStore();
        v.ltType = await UniversalDataService.GetOrderMainType();
        v.ltSource = await UniversalDataService.GetOrderSource();
        v.ltRentedFor = await UniversalDataService.GetRentedFor();
        v.ltStatus = await UniversalDataService.GetOrderMainStatus();
        v.ltPaymentStatus = await OrderDataService.GetPaymentStatus();
        v.ltPayMethod = await UniversalDataService.GetOrderMainPayMethod();
        v.initAutocomplete();

        var onum = UJ.getParameterByName("onum");
        if (onum != null && onum != "") {
            v.query.keyword = onum;
            v.getList(1);

            // 移除 URL 中的 onum 參數
            var currentUrl = new URL(location.href);
            currentUrl.searchParams.delete("onum");
            history.pushState(null, null, currentUrl.toString());

        } else {
            var s = $("body").getPostDataFromStorage(v.StorageKey);
            if (s.propCount == 0) {
                v.clearCriteria();
            } else {
                v.query.createDateS = (s.createDateS == null || s.createDateS.length == 0) ? null : s.createDateS;
                v.query.createDateE = (s.createDateE == null || s.createDateE.length == 0) ? null : s.createDateE;

                if (v.memberObj.marketId > 0) {
                    v.query.marketId = v.memberObj.marketId;
                    v.query.marketName = v.memberObj.marketName;
                    $('#query-market').val(v.memberObj.marketName);
                } else {
                    v.query.marketId = s.marketId;
                    v.query.marketName = s.marketName;
                    $('#query-market').val(s.marketName);
                }

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

                v.query.keyword = s.keyword;
                v.query.propertyNo = s.propertyno;

                v.query.types = [];
                if (s.type != null) {
                    s.type.split(',').forEach(function (value) {
                        if (value != "null") {
                            v.query.types.push(value);
                        }
                    });
                }

                v.query.sources = [];
                if (s.source != null) {
                    s.source.split(',').forEach(function (value) {
                        if (value != "null") {
                            v.query.sources.push(value);
                        }
                    });
                }

                v.query.rentedFors = [];
                if (s.rentedFor != null) {
                    s.rentedFor.split(',').forEach(function (value) {
                        if (value != "null") {
                            v.query.rentedFors.push(value);
                        }
                    });
                }

                v.query.statuss = [];
                if (s.status != null) {
                    s.status.split(',').forEach(function (value) {
                        if (value != "null") {
                            v.query.statuss.push(value);
                        }
                    });
                }

                v.query.paymethods = [];
                if (s.paymethod != null) {
                    s.paymethod.split(',').forEach(function (value) {
                        if (value != "null") {
                            v.query.paymethods.push(value);
                        }
                    });
                }

                v.query.payments = [];
                if (s.payment != null) {
                    s.payment.split(',').forEach(function (value) {
                        if (value != "null") {
                            v.query.payments.push(value);
                        }
                    });
                }

                if (UJ.getParameterByName("p") != null) {
                    v.getList(UJ.getParameterByName("p"));
                } else {
                    v.getList(s.currentPage);
                }
            }
        }

        var editId = UJ.GetStorage(StorageKey.orderEditId);
        if (editId != null) {
            v.lastActionId = [];
            v.lastActionId.push(editId);
            UJ.ResetStorage(StorageKey.orderEditId);
        }
    },
    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;
        }
    },
    components: {
        'date-picker': DatePicker
    },
    methods: {
        clearCriteria() {
            var v = this;
            v.query.createDateS = null;
            v.query.createDateE = null;

            if (v.memberObj.marketId > 0) {
                v.query.marketId = v.memberObj.marketId;
                v.query.marketName = v.memberObj.marketName;
                $('#query-market').val(v.memberObj.marketName);
            } else {
                v.query.marketId = -1;
                v.query.marketName = "";
                $('#query-market').val('');
            }

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

            v.query.keyword = "";
            v.query.propertyNo = "";
            v.query.types = [];
            v.query.sources = [];
            v.query.rentedFors = [];
            v.query.statuss = [];
            v.query.paymethods = [];
            v.query.payments = [];

            v.getList(1);
        },
        changeDate(type) {
            var v = this;
            if (type == "createDateS") {
                v.query.createDateE = v.query.createDateS;
            }
        },
        async getList(pageNum) {
            var v = this;
            v.isLoading = true;
            v.isFinishRequest = false;
            if (pageNum > 0) {
                v.query.currentPage = pageNum;
            }

            let res = await OrderDataService.GetList(v.query);
            v.list = res.list;
            if (v.list.length == 0 && v.query.currentPage > 1) {
                v.getList(1);
            }
            if (v.list != null && v.list.length > 0) {
                v.list.forEach(function (item) {
                    item.createDate = Decorator.ChangeISODateTimeToDate(item.createDatetime);
                });
            }
            v.pager = res.pager;
            v.isLoading = false;
            v.isFinishRequest = true;
            v.isBindFancybox = false;//重新綁定fancybox
        },
        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 "status":
                    lt = v.query.statuss;
                    break;
                case "payment":
                    lt = v.query.payments;
                    break;
                case "paymethod":
                    lt = v.query.paymethods;
                    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 "status":
                    lt = v.query.statuss;
                    break;
                case "payment":
                    lt = v.query.payments;
                    break;
                case "paymethod":
                    lt = v.query.paymethods;
                    break;
            }

            var res = false;
            lt.forEach(function (value, idx) {
                if (value == val) {
                    res = true;
                }
            });
            return res;
        },
        goPage(pageNum) {
            this.getList(pageNum);
        },
        gotoEditUrl(item) {
            var v = this;
            UJ.SaveStorage(StorageKey.orderEditId, item.id);
            location.href = "orderedit?id=" + item.id + "&p=" + v.query.currentPage;
        },
        openEditUrl(item) {
            var v = this;
            UJ.SaveStorage(StorageKey.orderEditId, item.id);
            window.open("orderedit?id=" + item.id + "&p=" + v.query.currentPage);
        },
        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");
            });
        },
        trCss(order) {
            var v = this;
            var css = "";
            if (order.enPaymentStatus == 200) css = "bg-pink";
            if (order.enStatus == 9999) css = "bg-closed";

            v.lastActionId.forEach(function (actionId) {
                if (order.id == actionId) { css = "nofity"; }
            });
            return css;
        }, 
        orderCss(order) {
            if (order.enStatus == 500) return "order-pause";
            if (order.enStatus <= 600) return "order-pending";
            return "";
        },
        triggerUpload(obj, item, type) {
            this.orderItem = item;
            this.uploadImgType = type
            $(obj).trigger("click");
        },
        onFileChange(e) {
            var v = this;
            v.isFinishRequest = false;
            v.isLoading = true;

            var files = e.target.files || e.dataTransfer.files;
            if (!files.length) return;
            this.uploadImg(files[0]);
        },
        async uploadImg(f) {
            //自動上傳
            var v = this;
            v.isFinishRequest = false;
            v.isLoading = true;
            var fData = new FormData();
            fData.append("files", f);
            fData.append("type", v.uploadImgType);
            fData.append("orderId", v.orderItem.id);
            v.lastActionId = [];
            v.lastActionId.push(v.orderItem.id);

            let res = await OrderDataService.UploadImage(fData);
            if (res.status != RESPONSE_STATUS.OK) {
                var data = res.data;
                if (res.httpStatus === 401) {
                    showErrMsg(data.message, "", "", null);
                } else {
                    showErrMsg('上傳失敗!!', "", "", null);
                }
                v.resetFile();
                return;
            }
            else {
                alert('上傳完成.');
                if (v.uploadImgType == "contract") {
                    var contracts = await OrderDataService.GetContractList(v.orderItem.id);
                    v.orderItem.contracts = [];
                    contracts.forEach(function (item) {
                        v.orderItem.contracts.push(item.imgSrc);
                    });
                } else if (v.uploadImgType == "receipt") {
                    var receipts = await OrderDataService.GetReceiptList(v.orderItem.id);
                    v.orderItem.receipts = [];
                    receipts.forEach(function (item) {
                        v.orderItem.receipts.push(item.imgSrc);
                    });
                }
                v.resetFile();
            }
        },
        resetFile() {
            const inputImg = this.$refs.fuImg;
            inputImg.type = 'text';
            inputImg.type = 'file';
            this.isLoading = false;
            this.isFinishRequest = true;
            this.isBindFancybox = false;
        }
    }
});
