import { AuthDataService } from '/js/ApiDataServer/Auth.js?tf=202411121501';
import { OemDataService } from '/js/ApiDataServer/Oem.js?tf=202507031152';
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,
            memberObj: {},
            ltOemMarketList: [],
            query: {
                marketId: -1,
                marketName: "",
                currentPage: 1,
                pageSize: 20
            },
            list: [],
            pager: {}
        };
    },
    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 = '/';
            }
        }

        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.ltOemMarketList = await OemDataService.GetOemMarketList();
        v.initAutocomplete();

        v.getList();
    },
    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 getList() {
            var v = this;
            v.isLoading = true;
            v.isFinishRequest = false;

            let res = await OemDataService.GetPendingStock(v.query);
            if (res.status == RESPONSE_STATUS.OK) {
                var data = res.data;
                v.list = data.list;
                v.list.forEach(function (item) {
                    item.lastEventDatetime = Decorator.ChangeServerDateTimeToISODateTime(item.lastEventDatetime);
                    item.marketName = "";
                    v.ltOemMarketList.forEach(function (market) {
                        if (market.id == item.marketId) {
                            item.marketName = market.name;
                        }
                    });
                });

                v.pager = data.pager;
                v.isFinishRequest = true;
                v.isLoading = false;
                v.isBindFancybox = false;//重新綁定fancybox
            } else {
                var data = res.data;
                if (res.httpStatus === 401) {
                    showErrMsg(data.message, "", "", function () {
                        location.href = "/";
                    });
                } else {
                    showErrMsg(data.message, "", "", null);
                    v.isFinishRequest = true;
                }
            }
        },
        async confirm(item) {
            var v = this;
            v.isFinishRequest = false;
            v.isLoading = true;

            let res = await OemDataService.ConfirmStock(item.stockId);
            if (res.status == RESPONSE_STATUS.OK) {
                showMsg(item.propertyNo + '已確認!', null, null, null, 500, function () {
                    v.getList();
                });
            } else {
                var data = res.data;
                showErrMsg(data.message, "", "", null);
                v.isFinishRequest = true;
                v.isLoading = false;
            }
        },
        async release(item) {
            var v = this;
            v.isFinishRequest = false;
            v.isLoading = true;

            let res = await OemDataService.ReleaseStock(item.stockId);
            if (res.status == RESPONSE_STATUS.OK) {
                showMsg(item.propertyNo + '已轉可租用!', null, null, null, 500, function () {
                    v.getList();
                });
            } else {
                var data = res.data;
                showErrMsg(data.message, "", "", null);
                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.ltOemMarketList.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;

                    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);
            };

            //點輸入框或右側箭頭就秀出下拉選單
            $(".autocomplete").click(function (item) {
                var obj = $(this).children('input').eq(0);
                $(obj).trigger("keydown");
            });
        }
    }
});
