<template>
    <div class="mix-select-container">
        <van-field
            readonly
            clickable
            :required="required"
            :name="name"
            :label="label"
            :placeholder="placeholder"
            @click="onShowPicker"
            ref="pureSelect"
            v-model="selectedText"
            :rules="validatePropRules"
            is-link />
        <van-popup v-model="showPicker" position="bottom">
            <van-picker
                show-toolbar
                :columns="dataList"
                value-key="label"
                :default-index="selectedIndex"
                @confirm="onConfirm"
                @cancel="showPicker = false" />
        </van-popup>
    </div>
</template>

<script>

    import { isEmpty, isNotEmpty, removeUrlParam, getUrlAllParam, convertSelect } from "@bingoit/utils";
    import { showMsg } from "../../utils/common.ui";
    import { getAutoConvert } from "@bingoit/ajax";
    import {commonSelectMixin} from "../../mixins/form.component";

    export default {
        name: "BgoPureSelect",
        mixins: [commonSelectMixin],
        props: {
            name: {
                type: String,
                default: 'purePickerSelect'
            }
        },
        created() {
            this.handleFormRule();
        },
        mounted() {
            this.getDataItem();
            if(this.vanForm) {
                this.vanForm.addField(this.$refs.pureSelect);
            }
        },
        data() {
            return {
                requestUrl: '',
                dataList: [],
                selectedIndex: 0,
                show: false,
                selectedText: '',
                showPicker: false
            }
        },
        methods: {
            onShowPicker() {
                if(this.disabled || this.readonly) {
                    return;
                }
                this.showPicker = true;
            },
            onConfirm(item) {
                this.selectedText = item.label;
                this.currentValue = item.id;
                this.showPicker = false;
            },
            /**
             * 获取数据项
             */
            getDataItem() {
                let requestUrl = '';
                if (this.dataSource === 'custom') {
                    if(this.isDataConvert) {
                        this.dataList = convertSelect(this.item);
                    } else {
                        this.dataList = this.item;
                    }
                    this.initData();
                    return;
                } else if (this.dataSource === 'dict') {
                    if (isEmpty(this.item)) {
                        showMsg('获取数据字典项失败');
                        return;
                    }
                    requestUrl = '/api/dict/items/';
                    requestUrl = requestUrl + this.item;
                } else if (this.dataSource === 'url') {
                    requestUrl = this.item;
                }
                let args = {};
                if(isNotEmpty(this.value)) {
                    args.inputValue = this.value;
                    args.value = this.value;
                }
                this.requestData(requestUrl, args);
            },
            /**
             * 请求数据
             * @param url
             * @param args
             */
            requestData(url, args) {
                let handleArgs = getUrlAllParam(url);
                if(handleArgs) {
                    for(let key in handleArgs) {
                        let value = handleArgs[key];
                        if(typeof(value) === 'string' && value.startsWith('${') && value.endsWith('}')) {
                            value = '';
                        }
                        if(key.startsWith('s_')) {
                            let newKey = key.substring(2);
                            handleArgs[newKey] = value;
                            delete handleArgs[key];
                        }
                    }
                }
                url = removeUrlParam(url);
                this.requestUrl = url;
                if(!args) {
                    args = {};
                }
                if(handleArgs) {
                    args = Object.assign({} , handleArgs , args);
                }
                this.getRemoteData(url, args);
            },

            /**
             * 获取远程数据
             * @param requestUrl
             * @param args
             */
            getRemoteData(requestUrl, args, callback) {
                //this.isSelected = false;
                this.dataList = [];
                this.loading = true;
                getAutoConvert(requestUrl, args).then(result => {
                    this.loading = false;
                    if (result.code === 1) {
                        if(this.isDataConvert) {
                            this.dataList = convertSelect(result.datas);
                        } else {
                            this.dataList = result.datas;
                        }
                        if(isNotEmpty(this.value) && (isEmpty(this.currentValue) || this.currentValue.length === 0)) {
                            this.currentValue = this.value;
                        }
                        this.initData();
                    }
                    if(callback) {
                        callback();
                    }
                }).catch(err => {
                    console.error(err);
                    if(callback) {
                        callback();
                    }
                })
            },
            /**
             * 初始化数据
             */
            initData() {
                //数据记载结束;初始化表单数据
                //this.isRequestLoading = false;
                if(this.currentValue && this.dataList && this.dataList.length > 0) {
                    let data = this.dataList[0];
                    let propName = 'id';
                    if(Object.prototype.hasOwnProperty.call(data, 'value') && isNotEmpty(data['value'])) {
                        propName = 'value';
                    }
                    let selectedData = this.findItem(this.dataList, this.currentValue, propName);
                    if(selectedData) {
                        this.selectedText = selectedData.item.label;
                        this.selectedIndex = selectedData.index;
                    }
                }
            },
            /**
             * 查找数据
             * @param items
             * @param value
             * @param propName
             */
            findItem(items, value, propName) {
                let index = 0;
                for(let item of items) {
                    if(item[propName] === value) {
                        return {index: index, item: item};
                    }
                    index++;
                }
            },
            getSourceElement() {
                return this.$refs.pureSelect
            }
        }
    }
</script>

<style lang="scss">

    .mix-select-container {
        .van-cell__title {
            max-width: 90px;
        }
    }

</style>
