<template>
    <div class="bgo-auto-complete">
        <bgo-form-item
            :label="label"
            :required="required"
            :readonly="readonly"
            :disabled="disabled"
            role="select"
        >
            <van-field
                v-show="!(readonly || disabled)"
                v-model="valueText"
                ref="autocomplete"
                :name="name"
                :placeholder="placeholder"
                :required="required"
                :clearable="clearable"
                :readonly="true"
                :disabled="disabled"
                @click="onClick"
            />
            <div v-show="readonly || disabled">
                {{ valueText }}
            </div>

            <template
                #right-icon
                v-if="this.valueText && !(disabled || readonly)"
            >
                <bgo-font-icon
                    type="vant"
                    icon="clear"
                    color="#BFC1C2"
                    @click.stop="onClear"
                />
            </template>
        </bgo-form-item>

        <van-popup
            v-model="showPopup"
            class="mix-input-popup mix-input-popup--with-search"
            position="bottom"
            round
        >
            <div class="mix-input-popup__title-bar">
                <button @click="showPicker = false">取消</button>
            </div>

            <bgo-search
                v-model="valueText"
                ref="autocomplete"
                @input="onChange"
                placeholder="请输入搜索关键词"
                autofocus
                class="mix-input-search"
            />

            <div class="mix-input-popup-body">
                <bgo-panel-loading v-if="loading"></bgo-panel-loading>
                <van-empty v-if="isNotData" description="没有搜索到数据" />
                <van-radio-group v-model="selectedValue">
                    <van-cell-group>
                        <van-cell
                            v-for="item in items"
                            :title="item.label"
                            clickable
                            :key="item.id"
                            @click="onClickItem(item)"
                        >
                            <span slot="icon" class="input-cell-left">
                                <van-radio :name="item.id">
                                    <template #icon="props">
                                        <img
                                            :src="
                                                getCustomRadioIcon(
                                                    props.checked
                                                )
                                            "
                                            style="width: 20px; height: 20px;"
                                        />
                                    </template>
                                </van-radio>
                            </span>
                        </van-cell>
                    </van-cell-group>
                </van-radio-group>
            </div>
        </van-popup>
    </div>
</template>

<script>
import { commonSelectMixin } from "../../mixins/form.component";
import _ from "lodash/function";
import { getAutoConvert } from "@bingoit/ajax";
import {
    handleUrl,
    isEmpty,
    isNotEmpty,
    DICT_ITEM_URL_PREFIX,
    convertSelect
} from "@bingoit/utils";

export default {
    name: "BgoAutoComplete",
    props: {
        clearable: {
            type: Boolean,
            default: false
        },
        name: {
            type: String,
            default: "autocomplete"
        }
    },
    mixins: [commonSelectMixin],
    created() {
        this.handleFormRule();
        console.info("dataSource:", this.dataSource);
        console.info("item:", this.item);
        this.initItem();
    },
    data() {
        return {
            valueText: "",
            showPopup: false,
            loading: false,
            items: [],
            sourceItems: [],
            selectedValue: "",
            isNotData: false
        };
    },
    methods: {
        onClick() {
            if (this.readonly || this.disabled) {
                return;
            }
            this.showPopup = true;
        },
        onChange: _.debounce(function(val) {
            this.isNotData = false;
            this.items = [];
            if (isEmpty(val)) {
                return;
            }
            this.loading = true;
            this.currentValue = val;
            if (this.isRemoteSearch()) {
                this.getRemoteData(this.item, { name: val });
            } else {
                for (let item of this.sourceItems) {
                    if (item.label.indexOf(val) > -1) {
                        this.items.push(item);
                    }
                }
                this.loading = false;
                if (isEmpty(this.items)) {
                    this.isNotData = true;
                }
            }
        }, 500),

        isRemoteSearch() {
            if (this.isCustom() || this.isDict()) {
                return false;
            }
            return true;
        },
        initItem() {
            if (this.isDict()) {
                let requestUrl = DICT_ITEM_URL_PREFIX + this.item;
                this.sourceItems = [];
                getAutoConvert(requestUrl).then(result => {
                    if (result.code === 1) {
                        if (this.isDataConvert) {
                            this.sourceItems.push(
                                ...convertSelect(result.datas)
                            );
                        } else {
                            this.sourceItems.push(...result.datas);
                        }
                        this.initDefaultValue(this.sourceItems);
                    }
                });
            } else if (this.isCustom()) {
                this.sourceItems = convertSelect(this.item);
                this.initDefaultValue(this.sourceItems);
            } else if (this.isUrl() && isNotEmpty(this.currentValue)) {
                let url = handleUrl(this.item);
                url += "value=" + this.currentValue;
                getAutoConvert(url).then(result => {
                    if (result.code === 1) {
                        let list = [];
                        if (this.isDataConvert) {
                            list.push(...convertSelect(result.datas));
                        } else {
                            list.push(...result.datas);
                        }
                        this.initDefaultValue(list);
                    }
                });
            }
        },

        /**
         * 获取远程数据
         * @param requestUrl
         * @param args
         */
        getRemoteData(requestUrl, args) {
            this.items = [];
            getAutoConvert(requestUrl, args)
                .then(result => {
                    if (result.code === 1) {
                        if (this.isDataConvert) {
                            this.items.push(...convertSelect(result.datas));
                        } else {
                            this.items.push(...result.datas);
                        }
                    }
                    this.loading = false;
                    if (isEmpty(this.items)) {
                        this.isNotData = true;
                    }
                })
                .catch(err => {
                    this.isNotData = true;
                    console.error(err);
                });
        },
        onClickItem(item) {
            this.selectedValue = item.id;
            this.currentValue = this.selectedValue;
            this.valueText = item.label;
            this.showPopup = false;
        },
        onConfirm() {
            this.showPopup = false;
            if (isEmpty(this.currentValue) && isNotEmpty(this.valueText)) {
                this.currentValue = this.valueText;
            }
        },
        initDefaultValue(items) {
            if (isNotEmpty(this.currentValue) && isNotEmpty(items)) {
                let isFind = false;
                for (let item of items) {
                    if (item.id === this.currentValue) {
                        this.valueText = item.label;
                        isFind = true;
                        break;
                    }
                }
                if (!isFind) {
                    this.valueText = this.currentValue;
                }
            }
        },
        getSourceElement() {
            return this.$refs.autocomplete;
        },

        /**
         * 获取自定义单选图标
         */
        getCustomRadioIcon(checked) {
            let icon;
            if (checked) {
                icon = require("../../assets/icons/radio-checked.png");
                if (this.disabled || this.readonly) {
                    icon = require("../../assets/icons/radio-check-disabled.png");
                }
            } else {
                icon = require("../../assets/icons/uncheck.png");
                if (this.disabled || this.readonly) {
                    icon = require("../../assets/icons/disabled.png");
                }
            }

            return icon;
        }
    }
};
</script>

<style lang="scss">
@import "../../style/var.scss";

/* .search-panel .auto-complete .van-cell {
        background-color: #fff;
        padding: 10px 15px;
    } */

$title-bar-height: 48px;
$search-height: 66px;
$breadcrumb-height: 40px;

.bgo-auto-complete {
    .van-cell::after {
        content: " ";
        position: absolute;
        pointer-events: none;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        left: $padding-md;
        right: $padding-md;
        bottom: 0;
        -webkit-transform: scaleY(0.5);
        transform: scaleY(0.5);
        // border-bottom: 1px solid $border-color;
        border-bottom: none;
    }
    .van-hairline--top-bottom::after,
    .van-hairline-unset--top-bottom::after {
        border-width: 0;
    }
}

.mix-input-popup {
    height: 60vh;
    // make fixed position relative to ancester
    // instead of viewport
    transform: scale(1);

    .mix-input-popup__title-bar {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: $title-bar-height;
        padding: 0 $padding-md;
        background-color: $gray-1;

        button {
            padding: 0;
            font-size: $font-size-lg;
            background-color: transparent;
            border: none;
            outline: none;
        }

        &__button--primary {
            color: $primary-color;
        }
    }
    .mix-input-search {
        position: fixed;
        top: $title-bar-height;
        z-index: 99999;
        height: $search-height;
        width: 100%;
        border-radius: 16px 16px 0 0;

        .van-search__content {
            border-radius: 6px;
        }
    }
    .mix-input-popup-body {
        height: calc(100% - #{$title-bar-height});
        margin-top: $title-bar-height;
        overflow: auto;

        .van-cell {
            padding: $padding-md;
        }
    }
    .input-cell-left {
        padding-right: $padding-xs;
    }

    .van-search {
        padding: $padding-md;
    }

    &--with-search {
        .mix-input-popup-body {
            height: calc(100% - #{$title-bar-height} - #{$search-height});
            margin-top: $title-bar-height + $search-height;
        }
    }
}
</style>
