import { UniversalDataService } from '/js/ApiDataServer/Universal.js?tf=202411131831';
import { FreightTypeDataService } from '/js/ApiDataServer/FreightType.js';
import { ProductMainDataService } from '/js/ApiDataServer/ProductMain.js';
import { ProductRelationDataService } from '/js/ApiDataServer/ProductRelation.js';
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';

var vMain = new Vue({
    el: "#dvMain",
    data: function () {
        return {
            pageTitle: "輔具編輯",
            authDesc: "輔具_輔具管理",
            isSystemManager: false,
            isLoading: false,
            isFinishRequest: false,
            ltProductType: [],
            ltFreightType: [],
            ltCategory: [],
            parentCategoryId: -1,
            modifyObj: {
                id: -1,
                categoryId: -1,
                sort: 5000,
                coverImage: "",
                pictures: [],
                deposit: null,
                freightTypeId: -1,
                consumableFee: null,
                status: 1,
                enProductType: -1,
                salePrice: -1,
                monthlyCharge: -1,
                weeklyCharge: -1,
                enRecovery: -1,
                enRequiredAddition: -1,
                enRenewCharged: -1,
                salePriceCost: -1,
                monthlyCost: -1,
                weeklyCost: -1
            },
            newPictures: [],
            relations: []
        };
    },
    created: async function () {
        this.isSystemManager = await AuthDataService.IsSystemManager();
        this.modifyObj.id = UJ.getParameterByName("id");
        this.ltProductType = await UniversalDataService.GetProductType();
        this.ltFreightType = await FreightTypeDataService.GetList();
        this.ltCategory = await UniversalDataService.GetProductCategory();
        this.resetItem();
        if (this.modifyObj.id > 0) {
            this.loadGift();
        }
    },
    updated: function () {
        var v = this;
        initAdminutil();

        if (v.isFinishRequest) {
            setTimeout(function () {
                v.isLoading = false;
            }, 100);
        } else {
            v.isLoading = true;
        }
    },
    components: {
        'date-picker': DatePicker,
        ckeditor: CKEditor.component,
    },
    methods: {
        async resetItem() {
            var v = this;
            if (v.modifyObj.id != null && v.modifyObj.id > 0) {
                v.isFinishRequest = false;

                var res = await ProductMainDataService.Get(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.parentCategoryId = -1;
                    v.ltCategory.forEach(function (item) {
                        if (item.id == v.modifyObj.categoryId) {
                            v.parentCategoryId = item.parentId;
                        }
                    });
                    v.newPictures = v.modifyObj.pictures.map(item => ({ url: item }));

                    v.isFinishRequest = true;
                } else {
                    var data = res.data;
                    showErrMsg(data.message, "", "", function () {
                        if (data.enMessage == enMessage.NotFound) {
                            UJ.BackToList();
                        }
                    });
                }
            } else {
                v.isFinishRequest = true;
            }
            setTimeout(function () {
                v.toggleBTN('parentCategoryId', v.parentCategoryId);
                v.toggleBTN('categoryId', v.modifyObj.categoryId);
                v.toggleBTN('freightTypeId', v.modifyObj.freightTypeId);
                v.toggleBTN('status', v.modifyObj.status);
                v.toggleBTN('productType', v.modifyObj.enProductType);
                v.toggleBTN('recovery', v.modifyObj.enRecovery);
                v.toggleBTN('requiredAddition', v.modifyObj.enRequiredAddition);
                v.toggleBTN('renewCharged', v.modifyObj.enRenewCharged);
            }, 100);
        },
        async loadGift() {
            var v = this;
            let res = await ProductRelationDataService.GetList(v.modifyObj.id, 100);
            if (res.status == RESPONSE_STATUS.OK) {
                v.relations = res.data;

            } else {
                var data = res.data;
                showErrMsg(data.message, "", "", function () {
                    if (res.httpStatus === 401) {
                        location.href = "/";

                    } else if (data.enMessage == enMessage.NotFound) {
                        UJ.BackToList();
                    }
                });
            }
        },
        checkData() {
            var v = this;
            if (v.modifyObj.enProductType == -1) {
                alert("請選擇類型!");
                return false;
            }
            if (v.modifyObj.categoryId == null || v.modifyObj.categoryId.length == 0 || v.modifyObj.categoryId == -1) {
                alert("請選擇分類!");
                return false;
            }
            if (v.modifyObj.sort == null || v.modifyObj.sort.length == 0) {
                alert("請輸入排序(限數字)!");
                v.$refs.sort.focus();
                return false;
            }
            if (v.modifyObj.name == null || v.modifyObj.name == "") {
                alert("請輸入品名!");
                v.$refs.name.focus();
                return false;
            }
            if (v.modifyObj.productCode == null || v.modifyObj.productCode == "") {
                alert("請輸入型號!");
                v.$refs.productCode.focus();
                return false;
            }
            if (v.modifyObj.modelNo == null || v.modifyObj.modelNo == "") {
                alert("請輸入JDE料號!");
                v.$refs.modelNo.focus();
                return false;
            }
            if (v.modifyObj.freightTypeId == null || v.modifyObj.freightTypeId.length == 0 || v.modifyObj.freightTypeId == -1) {
                alert("請選擇運費類型!");
                return false;
            }
            if (v.modifyObj.enRecovery == -1) {
                alert("請選擇是否需回收!");
                return false;
            } else {
                if (v.modifyObj.enRecovery == 1) {
                    if (v.modifyObj.deposit == null || v.modifyObj.deposit.length == 0) {
                        alert("請輸入押金!");
                        v.$refs.deposit.focus();
                        return false;
                    } else {
                        if (parseInt(v.modifyObj.deposit) < 0) {
                            alert("押金不可小於0!");
                            v.$refs.deposit.focus();
                            return false;
                        }
                    }
                    if (v.modifyObj.consumableFee == null || v.modifyObj.consumableFee.length == 0) {
                        alert("請輸入耗材費!");
                        v.$refs.consumableFee.focus();
                        return false;
                    } else {
                        if (parseInt(v.modifyObj.consumableFee) < 0) {
                            alert("耗材費不可小於0!");
                            v.$refs.consumableFee.focus();
                            return false;
                        }
                    }
                }
            }
            if (v.modifyObj.enRequiredAddition == -1) {
                alert("請選擇是否需加租(購)!");
                return false;
            }
            if (v.modifyObj.enRenewCharged == -1) {
                alert("請選擇續租是否收費!");
                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.startDatetime = Decorator.ChangeISODateTimeToServerDateTime(oObj.startDatetime);
                oObj.endDatetime = Decorator.ChangeISODateTimeToServerDateTime(oObj.endDatetime);

                let res = await ProductMainDataService.Create(oObj);
                if (res.status == RESPONSE_STATUS.OK) {
                    v.modifyObj.id = res.data.id;
                    showMsg('新增成功!', null, null, null, null, function () {
                        window.location.href = "edit?id=" + v.modifyObj.id;
                    });
                } 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;

                v.modifyObj.pictures = this.newPictures.map(item => (item.url));

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

                let res = await ProductMainDataService.Update(oObj);

                if (res.status == RESPONSE_STATUS.OK) {
                    showMsg('更新成功!', null, null, null, null, function () {
                        v.resetItem();
                    });
                } 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 ProductMainDataService.Delete(this.modifyObj.id);
            if (res.status == RESPONSE_STATUS.OK) {
                showMsg('刪除成功!', null, null, null, null, function () {
                    UJ.BackToList();
                });
            } else {
                var data = res.data;
                showErrMsg(data.message, "", "", function () {
                    if (data.enMessage == enMessage.NotFound) {
                        UJ.BackToList();
                    }
                });
                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);

            let res = await UniversalDataService.UploadImage(fData);
            if (res.status != RESPONSE_STATUS.OK) {
                alert('圖片上傳失敗');
                v.resetFile();
                v.isLoading = false;
                v.isFinishRequest = true;
                return;
            }
            else {
                if (e.target.id == "fuFile") {
                    v.modifyObj.content += "<img src=" + res.data + " />";
                } else if (e.target.id == "fuImg") {
                    v.modifyObj.coverImage = res.data;
                } else if (e.target.id == "fuPictures") {
                    if (v.modifyObj.pictures == null) {
                        v.modifyObj.pictures = [];
                    }
                    v.modifyObj.pictures.push(res.data);
                    v.newPictures = v.modifyObj.pictures.map(item => ({ url: item }));
                }

                v.resetFile();
                v.isFinishRequest = true;
            }
        },
        resetFile() {
            const inputImg = this.$refs.fuImg;
            inputImg.type = 'text';
            inputImg.type = 'file';

            const inputPic = this.$refs.fuPictures;
            inputPic.type = 'text';
            inputPic.type = 'file';

            const input = this.$refs.fuFile;
            input.type = 'text';
            input.type = 'file';
        },
        removePicture(index) {
            this.modifyObj.pictures.splice(index, 1);
            this.newPictures.splice(index, 1);
        },
        toggleBTN(type, val) {
            var v = this;
            switch (type) {
                case "status":
                    v.modifyObj.status = val;
                    break;
                case "parentCategoryId":
                    v.parentCategoryId = val;
                    var exists = false;
                    v.ltCategory.forEach(function (item) {
                        if (item.parentId == v.parentCategoryId && item.id == v.modifyObj.categoryId) {
                            exists = true;
                        }
                    });
                    if (!exists) {
                        v.modifyObj.categoryId = -1;
                        ResetBTN('categoryId');
                    }
                    break;
                case "categoryId":
                    v.modifyObj.categoryId = val;
                    break;
                case "freightTypeId":
                    v.modifyObj.freightTypeId = val;
                    break;
                case "productType":
                    v.modifyObj.enProductType = val;
                    break;
                case "recovery":
                    v.modifyObj.enRecovery = val;
                    if (v.modifyObj.enRecovery == 0) {
                        v.modifyObj.deposit = 0;
                        v.modifyObj.consumableFee = 0;
                    }
                    break;
                case "requiredAddition":
                    v.modifyObj.enRequiredAddition = val;
                    break;
                case "renewCharged":
                    v.modifyObj.enRenewCharged = val;
                    break;
            }

            ToggleBTN(type, val);
        },
        async updateRelationQty() {
            var v = this;
            let res = await ProductRelationDataService.UpdateQty({ productId: v.modifyObj.id, enRelationType: 100, list: v.relations });
            if (res.status != RESPONSE_STATUS.OK) {
                alert('數量更新失敗');
                v.isFinishRequest = true;
                return;
            } else {
                alert('數量已儲存');
                v.loadGift();
            }
        },
        async removeRelation(item) {
            var v = this;
            let res = await ProductRelationDataService.Delete(item.relationId);
            if (res.status != RESPONSE_STATUS.OK) {
                alert('刪除失敗');
                v.isFinishRequest = true;
                return;
            } else {
                v.loadGift();
            }
        }
    }
});

$(function () {
    setTimeout(function () {
        openLeftMenu('/product/list');
    }, 100);
});