<template>
    <div>
        <label for="" class="item-title mb5">{{ titleName }}</label>
        <div style="position: relative">
            <input type="text" v-model="inputValue" @input="handleInputChange" placeholder="거래처를 입력하세요"
                class="full-input" />
            <Icon :path="mdiMagnify" size="1.2" class="search-icon" />
            <ul class="auto-list" v-if="accountResults.length > 0">
                <li v-for="(account, index) in accountResults" :key="index" @click="handleItemClick(account)"
                    class="flex align-center no-gutters">
                    <div class="col-1 mr5">
                        <p class="option-icon">
                            <Icon :path="mdiMagnify" size="1" />
                        </p>
                    </div>
                    <div class="col-10 abbreviation">
                        <p>{{ account.JSNAME }}</p>
                    </div>
                </li>
            </ul>
        </div>
    </div>
</template>

<script>
import axios from 'axios';


export default {
    props: ['initialJSName', 'SABNHO', 'titleName', 'onModal', 'setCUSTCD'],
    components: {
        Icon,
    },
    data() {
        return {
            inputValue: this.initialJSName || '',
            accountResults: [],
            accounts: [],
            mdiMagnify,
        };
    },
    methods: {
        selectClientName(name) {
            this.$axios({
                method: 'post',
                url: 'https://api.ajinpaper.app/ajin_API/client.do',
                headers: {
                    'Content-Type': 'application/json',
                },
                data: {
                    jsname: name,
                    sabnho: this.SABNHO,
                },
            })
                .then((response) => {
                    if (response.data && response.data.resultCode === 200) {
                        this.accounts = response.data.resultData;
                    }
                })
                .catch((error) => {
                    this.onModal('오류 발생. 관리자에 문의해주세요');
                });
        },
        handleInputChange() {
            const value = this.inputValue;
            const filtered = this.accounts.filter((account) =>
                account.JSNAME.toLowerCase().includes(value.toLowerCase())
            );
            this.accountResults = filtered;
        },
        handleItemClick(account) {
            this.inputValue = account.JSNAME;
            this.setCUSTCD(account.CUSTCD);
            this.accountResults = [];
        },
    },
    watch: {},
    computed: {},
    components: {},
    mounted() {
        this.selectClientName('');
    },
};
</script>
