<template>
    <el-select
        v-model="index"
        filterable
        clearable
        remote
        reserve-keyword
        placeholder="请输入商品关键词"
        :remote-method="remoteMethod"
        :loading="loading">
        <el-option
        v-for="(item, index) in list"
        :key="item.id"
        :label="item.titleZh"
        :value="index">
        </el-option>
    </el-select>
</template>
<script>
import {getProduct, getProductPage} from '@/api/ecw/product'

export default {
    props:{
        productType: [String, Number],
        value: [String, Number]
    },
    data(){
        return {
            index: {},
            list:[],
            loading: false
        }
    },
    watch:{
        index(val){
            this.$emit('input', val !== null ? this.list[val].id : null)
            this.$emit('change', val !== null ? this.list[val] : null)
        },
        value(val){
            console.log('初始化内容', val)
            /* let index = this.list.findIndex(item => item.id == val)
            if(index < 0){
                getProduct(val).then(res => {
                    this.list.unshift(res.data)
                    this.index = 0
                })
            } */
            this.init()
            
        }
    },
    created(){
        console.log('created', this.value)
        this.init()
    },
    methods:{
        init(){
            if(!this.value) return null
            let index = this.list.findIndex(item => item.id == this.value)
            if(index < 0){
                getProduct(this.value).then(res => {
                    this.list.unshift(res.data)
                    this.index = 0
                })
            }
        },
        remoteMethod(keyword){
            let params = {}
            if(this.productType){
                params.productType = this.productType
            }
            params.titleZh = keyword
            this.loading = true
            getProductPage(params)
                .then(res => this.list = res.data.list)
                .finally(() => this.loading = false)
        }
    }
}
</script>