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

let twzipcode;
var vMain = new Vue({
    el: "#dvMain",
    data: function () {
        return {
            pageTitle: "收款記錄",
            authDesc: "訂單_訂單管理",
            isSystemManager: false,
            isLoading: false,
            isFinishRequest: false,
            isBindFancybox: true,
            showCloseBTN: true,
            orderObj: {
                id: -1
            },
            modifyObj: {
                id: -1,
                orderId: -1,
                paymentAmount: 0,
                paymentDate: null,
                invoiceAmount: 0,
                invoiceDate: null,
                invoiceNum: "",
                imgSrc: ""
            }
        };
    },
    components: {
        'date-picker': DatePicker
    },
    created: async function () {
        var v = this;
        v.isSystemManager = await AuthDataService.IsSystemManager();
        v.orderObj.id = UJ.getParameterByName("oid");
        v.modifyObj.id = UJ.getParameterByName("id");

        var res = await OrderDataService.GetMain(v.orderObj.id);
        if (res.status == RESPONSE_STATUS.OK) {
            v.orderObj = res.data;

            v.loadData();

        } else {
            var data = res.data;
            showErrMsg(data.message, "", "", function () {
                if (data.enMessage == enMessage.NotFound) {
                    v.closeAndReloadParent();
                }
            });
        }
    },
    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;
        }
    },
    methods: {
        async loadData() {
            var v = this;
            if (v.modifyObj.id != null && v.modifyObj.id > 0) {
                v.isFinishRequest = false;

                var res = await OrderDataService.GetPaymentRecord(v.modifyObj.id);
                if (res.status == RESPONSE_STATUS.OK) {
                    v.modifyObj = res.data;
                    v.modifyObj.createDate = Decorator.ChangeServerDateTimeToISODateTime(v.modifyObj.createDatetime);
                    v.modifyObj.modifyDate = Decorator.ChangeServerDateTimeToISODateTime(v.modifyObj.modifyDatetime);
                    v.modifyObj.paymentDate = Decorator.ChangeServerDateTimeToISODateTime(v.modifyObj.paymentDate);

                    v.isBindFancybox = false;//重新綁定fancybox
                    v.isFinishRequest = true;
                } else {
                    var data = res.data;
                    showErrMsg(data.message, "", "", function () {
                        if (data.enMessage == enMessage.NotFound) {
                            v.closeAndReloadParent();
                        }
                    });
                }
            } else {
                v.isFinishRequest = true;
                v.modifyObj.orderId = v.orderObj.id;
            }
        },
        checkData() {
            var v = this;
            if (v.modifyObj.paymentAmount == null || v.modifyObj.paymentAmount.length == 0 || v.modifyObj.paymentAmount <= 0) {
                alert("請填寫收款金額!");
                v.$refs.paymentAmount.focus();
                return false;
            }
            if (v.modifyObj.paymentDate == null || v.modifyObj.paymentDate == "") {
                alert("請輸入收款日期!");
                $("#paymentDate").focus();
                return false;
            }
            return true;
        },
        async createItem() {
            var v = this;
            if (v.checkData()) {
                v.isFinishRequest = false;
                v.isLoading = true;

                let oObj = JSON.parse(JSON.stringify(v.modifyObj));
                oObj.paymentDate = Decorator.ChangeISODateTimeToServerDateTime(oObj.paymentDate);

                let res = await OrderDataService.CreatePaymentRecord(oObj);
                if (res.status == RESPONSE_STATUS.OK) {
                    showMsg('新增成功!', null, null, null, null, function () {
                        v.closeAndReloadParent();
                    });
                } 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 updateItem() {
            var v = this;
            if (v.checkData()) {
                v.isFinishRequest = false;
                v.isLoading = true;

                let oObj = JSON.parse(JSON.stringify(v.modifyObj)); 
                oObj.paymentDate = Decorator.ChangeISODateTimeToServerDateTime(oObj.paymentDate);

                let res = await OrderDataService.UpdatePaymentRecord(oObj);
                if (res.status == RESPONSE_STATUS.OK) {
                    showMsg('更新成功!', null, null, null, null, function () {
                        v.closeAndReloadParent();
                    });
                } 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;
                }
            }
        },
        deleteItem() {
            var v = this;
            swal({
                title: "確定要刪除？",
                type: "question",
                showCancelButton: true,
                confirmButtonText: "確定",
                cancelButtonText: "取消"
            }).then(result => {
                if (result.value) {
                    v.delete();
                }
            });
        },
        async delete() {
            var v = this;
            v.isFinishRequest = false;
            v.isLoading = true;

            let res = await OrderDataService.DeletePaymentRecord(v.modifyObj.id);
            if (res.status == RESPONSE_STATUS.OK) {
                showMsg('刪除成功!', null, null, null, null, function () {
                    v.closeAndReloadParent();
                });
            } else {
                var data = res.data;
                showErrMsg(data.message, "", "", function () {
                    if (data.enMessage == enMessage.NotFound) {
                        v.closeAndReloadParent();
                    }
                });
                v.isFinishRequest = true;
                v.isLoading = false;
            }
        },
        triggerUpload(obj) {
            $(obj).trigger("click");
        },
        onFileChange(e) {
            var files = e.target.files || e.dataTransfer.files;
            if (!files.length) return;
            this.uploadImg(files[0], e);
        },
        async uploadImg(f, e) {
            //自動上傳
            var v = this;
            v.isFinishRequest = false;
            v.isLoading = true;
            var fData = new FormData();
            fData.append("files", f);
            fData.append("type", "paymentrecord");
            fData.append("orderId", v.orderObj.id);

            let res = await OrderDataService.UploadImage(fData);
            if (res.status != RESPONSE_STATUS.OK) {
                alert('圖片上傳失敗');
                v.resetFile();
                return;
            }
            else {
                v.modifyObj.imgSrc = res.data;
                v.resetFile();
                v.isFinishRequest = true;
            }
        },
        resetFile() {
            const inputImg = this.$refs.fuImg;
            inputImg.type = 'text';
            inputImg.type = 'file';
        },
        closeAndReloadParent() {
            CloseAndReloadParent();
        }
    }
});
