<template>
    <div>
        <el-autocomplete
            v-model="state"
            :fetch-suggestions="querySearchAsync"
            placeholder="请选择公司"
            @select="handleSelect"
        ></el-autocomplete>
    </div>
</template>

<script>
import { queryMaintenanceCompany } from '@/apps/mobile/api/recruitment/index';
export default {
    props: {
        companyName: {
            default: '',
        },
    },
    data() {
        return {
            state: `${this.companyName}`,
            timeout: null,
            companyList: [],
        };
    },
    created() {
        this.queryCompanyList();
    },
    mounted() {},
    methods: {
        querySearchAsync(queryString, cb) {
            let companyList = this.companyList;
            let results = queryString ? companyList.filter(this.createStateFilter(queryString)) : companyList;
            clearTimeout(this.timeout);
            this.timeout = setTimeout(() => {
                cb(results);
            }, 2000);
        },
        createStateFilter(queryString) {
            return state => {
                return state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
            };
        },
        // 查询所有维保公司
        queryCompanyList() {
            let obj = {
                pageNum: 0,
                pageSize: 1000, //数据量太大，有1万多条记录，卡顿
            };
            let companyArr = [];
            queryMaintenanceCompany(obj)
                .then(res => {
                    console.log('company', res);
                    companyArr = res.data.records;
                    if (res.data.records && res.data.records.length == 0) {
                        console.log('error');
                        this.$emit('companyEmpty');
                    }
                    if (companyArr && companyArr.length > 0) {
                        this.companyList = companyArr.map(item => {
                            return {
                                value: item.name,
                                id: item.id,
                            };
                        });
                    }
                })
                .catch(() => {});
        },
        handleSelect(item) {
            console.log(item);
            this.$emit('companyChange', item);
        },
        reset() {
            this.state = null;
        },
    },
    watch: {
        state(val) {
            if (val === '') {
                this.$emit('companyEmpty');
            }
        },
        companyName(val) {
            console.log(val);
            this.state = val;
        },
    },
};
</script>


<style lang="stylus" scoped></style>