/*!
 * Built by ShiftSoftware
 * Copyright (c)
 */
import { Host, h } from "@stencil/core";
import distributerSchema from "../../locales/partLookup/distributor/type";
import { getLocaleLanguage, getSharedLocal, sharedLocalesSchema } from "../../features/multi-lingual/index";
import { FormHook } from "../../features/form-hook/index";
import { number, object, string } from "yup";
import getLanguageFromUrl from "../../global/lib/get-language-from-url";
import cn from "../../global/lib/cn";
import { fetchFrom } from "../../global/lib/fetch-from";
const manufacturerOrderTypesFetcher = async ({}) => {
    return [
        {
            value: '0',
            label: 'V',
        },
        {
            value: '1',
            label: 'A ',
        },
    ];
};
const manufacturerPartLookupValidation = object({
    orderType: string()
        .meta({ label: 'Order Type', placeholder: 'Order Type' })
        .required('This field is required.'),
    quantity: number()
        .meta({ label: 'quantity', placeholder: 'quantity' })
        .required('This field is required.')
        .typeError('This field is required.')
        .min(1, 'This field is required.'),
    partNumber: string()
        .meta({ label: 'Part Number', placeholder: 'Part Number' })
        .required('This field is required.'),
});
export class ManufacturerPartLookup {
    constructor() {
        this.locale = Object.assign({ sharedLocales: sharedLocalesSchema.getDefault() }, distributerSchema.getDefault());
        // #endregion
        // #region Form Hook logic
        this.isLoading = false;
        this.formSubmit = async (payload) => {
            try {
                if (this.isDev) {
                    await new Promise(r => setTimeout(r, 2000));
                    if (0.5 < Math.random()) {
                        if (0.5 < Math.random())
                            this.manufacturerResponse = { message: '', quantity: 2, id: '2', orderType: 'Airplane', partNumber: 'T110715002102', status: 'Pending', manufacturerResult: [] };
                        else
                            this.manufacturerResponse = { message: '', quantity: 2, id: '2', orderType: 'Airplane', partNumber: 'T110715002102', status: 'UnResolved', manufacturerResult: [] };
                    }
                    else {
                        this.manufacturerResponse = {
                            id: '2',
                            message: '',
                            quantity: 2,
                            orderType: 'Airplane',
                            partNumber: 'T110715002102',
                            status: 'Pending',
                            manufacturerResult: [
                                { key: 'item 1', value: `${Math.floor(Math.random() * 100)}` },
                                { key: 'item 2', value: 'Available' },
                                { key: 'item 3', value: `${Math.floor(Math.random() * 100)}` },
                                { key: 'item 4', value: 'Not Available' },
                            ],
                        };
                    }
                    this.form.reset();
                    return;
                }
                const requestPayload = {
                    logId: this.logId,
                    quantity: +payload.quantity,
                    partNumber: payload.partNumber,
                    // @ts-ignore
                    orderType: +payload.orderType,
                };
                const response = await fetchFrom(this.manufacturerPartLookupEndpoint, { language: this.language, body: requestPayload, method: 'POST' });
                if (!response.ok) {
                    throw new Error(`Request failed with status ${response.status}`);
                }
                const responseType = (await response.json());
                this.form.reset();
                this.manufacturerResponse = responseType;
            }
            catch (error) {
                console.error('❌ Manufacturer Lookup request failed:', error);
                // @ts-ignore
                this.manufacturerResponse = { message: this.locale.RequestFailed };
            }
        };
        this.logId = '';
        this.standAlone = true;
        this.manufacturerPartLookupTitle = 'Manufacture lookup';
        this.form = new FormHook(this, manufacturerPartLookupValidation);
    }
    async componentWillLoad() {
        if (!this.language)
            this.language = getLanguageFromUrl();
        await Promise.all([this.changeLanguage(this.language)]);
    }
    async changeLanguage(newLanguage) {
        const [sharedLocales, locale] = await Promise.all([getSharedLocal(newLanguage), getLocaleLanguage(newLanguage, 'partLookup.distributor', distributerSchema)]);
        this.locale = Object.assign({ sharedLocales }, locale);
    }
    // #endregion
    render() {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        const { formController } = this.form;
        const isComponentOpened = (!!((_a = this === null || this === void 0 ? void 0 : this.partLookup) === null || _a === void 0 ? void 0 : _a.showManufacturerPartLookup) && !this.closeManufacturerPartLookup) || this.standAlone;
        return (h(Host, { key: '0f036603dff5899811b48162e0344d6946c8475e', translate: "no" }, h("flexible-container", { key: '2a46003f17893430fb3575e00a5683c60032e4ea', isOpened: isComponentOpened }, h("div", { key: '2ee897f73a17435c7ecb4f59c030b44a1f5799f4', class: "w-full max-w-[96vw] mx-auto pt-[32px]" }, h("div", { key: '46c7b44060cfdacac51e5c5f0dff1dfd3c37c5d6', class: "bg-[#f6f6f6] rounded-md p-[16px]" }, h("div", { key: '388fff58b142eb48c3d12d51fe36ca600dcbc0b5', class: "flex items-center mb-[12px] justify-center px-[16px] font-bold text-[18px]" }, this.manufacturerPartLookupTitle), h("form", Object.assign({ key: '010bbd1acbf35b62577ac97708f3659a3d96ef70', class: "relative manufacturer-form flex flex-col items-center gap-[32px] pt-[8px] pb-[16px]", dir: this.locale.sharedLocales.direction }, formController), h("div", { key: 'b33d8a79c10aa573f608d8b901f94aab9511ecb2', class: "flex gap-2" }, h("form-input", { form: this.form, name: "partNumber", isLoading: this.isLoading, key: this.locale.sharedLocales.lang, staticValue: ((_b = this.partLookup) === null || _b === void 0 ? void 0 : _b.partNumber) || undefined }), h("form-input", { inputProps: { type: 'number', min: 1 }, name: "quantity", isLoading: this.isLoading, key: this.locale.sharedLocales.lang, form: this.form }), h("form-select", { clearable: true, form: this.form, name: "orderType", isLoading: this.isLoading, fetcher: manufacturerOrderTypesFetcher, key: this.locale.sharedLocales.lang, language: this.locale.sharedLocales.language })), h("form-submit", { key: this.locale.sharedLocales.lang, isLoading: this.isLoading, form: this.form })), h("flexible-container", { key: 'b4c245b2e3d5953ff9420c5852f586e585c54b76', isOpened: !!this.manufacturerResponse && !this.isLoading }, h("div", { key: '2c83cc980df47ef6a6f42f6b87c35a0ba338cb22', class: "flex flex-col items-center pt-[12px]" }, h("div", { key: 'b686301eb396fec496141635635a9abc89c06f98', class: cn('text-center text-[20px] font-semibold py-[12px]') }, !((_d = (_c = this.manufacturerResponse) === null || _c === void 0 ? void 0 : _c.manufacturerResult) === null || _d === void 0 ? void 0 : _d.length) && (((_e = this.manufacturerResponse) === null || _e === void 0 ? void 0 : _e.message) || this.locale.RequestFailed), !!((_g = (_f = this.manufacturerResponse) === null || _f === void 0 ? void 0 : _f.manufacturerResult) === null || _g === void 0 ? void 0 : _g.length) && (h("div", { key: '09124847eddd26cb2b478fbe1bd86a3d78799e1c', class: "bg-white rounded-lg border w-[500px]" }, (_h = this.manufacturerResponse) === null || _h === void 0 ? void 0 : _h.manufacturerResult.map(({ key, value }) => (h("div", { key: `${key}-${value}`, class: "flex even:bg-slate-100 hover:bg-sky-100/50 border-b w-full text-xl text-center" }, h("div", { class: "text-center flex items-center flex-1 max-w-[250px] shrink-0 justify-center py-[10px] px-[16px] border-r" }, key), h("div", { class: "text-center flex items-center flex-1 shrink-0 justify-center py-[10px] px-[16px] border-l" }, value))))))))))))));
    }
    static get is() { return "manufacturer-part-lookup"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["manufacturer-part-lookup.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["manufacturer-part-lookup.css"]
        };
    }
    static get properties() {
        return {
            "language": {
                "type": "string",
                "attribute": "language",
                "mutable": true,
                "complexType": {
                    "original": "LanguageKeys",
                    "resolved": "\"ar\" | \"en\" | \"ku\" | \"ru\"",
                    "references": {
                        "LanguageKeys": {
                            "location": "import",
                            "path": "~features/multi-lingual",
                            "id": "src/features/multi-lingual/index.ts::LanguageKeys"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "isDev": {
                "type": "boolean",
                "attribute": "is-dev",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "logId": {
                "type": "string",
                "attribute": "log-id",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "''"
            },
            "partLookup": {
                "type": "unknown",
                "attribute": "part-lookup",
                "mutable": false,
                "complexType": {
                    "original": "PartLookupDTO",
                    "resolved": "{ partNumber: string; partDescription: string; localDescription: string; productGroup: string; pnc: string; binType: string; showManufacturerPartLookup: boolean; distributorPurchasePrice?: number; length?: number; width?: number; height?: number; netWeight?: number; grossWeight?: number; cubicMeasure?: number; hsCode: string; origin: string; supersededTo: string[]; supersededFrom: string[]; stockParts: StockPartDTO[]; prices: PartPriceDTO[]; hsCodes: HSCodeDTO[]; deadStock: DeadStockDTO[]; logId?: string; }",
                    "references": {
                        "PartLookupDTO": {
                            "location": "import",
                            "path": "~types/generated/part/part-lookup-dto",
                            "id": "src/global/types/generated/part/part-lookup-dto.ts::PartLookupDTO"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "standAlone": {
                "type": "boolean",
                "attribute": "stand-alone",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "true"
            },
            "manufacturerPartLookupTitle": {
                "type": "string",
                "attribute": "manufacturer-part-lookup-title",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'Manufacture lookup'"
            },
            "closeManufacturerPartLookup": {
                "type": "boolean",
                "attribute": "close-manufacturer-part-lookup",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "manufacturerPartLookupEndpoint": {
                "type": "string",
                "attribute": "manufacturer-part-lookup-endpoint",
                "mutable": false,
                "complexType": {
                    "original": "Endpoint",
                    "resolved": "string | { url: string; body?: object; headers?: object; method?: string; query?: QueryString; }",
                    "references": {
                        "Endpoint": {
                            "location": "import",
                            "path": "~lib/fetch-from",
                            "id": "src/global/lib/fetch-from.ts::Endpoint"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            }
        };
    }
    static get states() {
        return {
            "locale": {},
            "isLoading": {},
            "manufacturerResponse": {}
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "language",
                "methodName": "changeLanguage"
            }];
    }
}
