<template>
    <div :queryUrl="queryUrl" :id="dropCtlId" class="go-common-drop-ctl" style="position: relative;"
         ref="common_drop_div">
        <go-input ref="inputElObj" :labelAlign="labelAlign" :suffixTip="false" :labelWidth="labelWidth" @radioBoxClick="radioBoxClick" :radioBox="inputItem.radioBox"
                       v-model="showValue" :readOnly="true" :radioVal="radioVal" :clearValue="false"
                       :suffix="dropSuffixIcon" :disabled="disabledInput"
                       @inputClick="inputClick" @suffixClick="suffixClick" :width="width" :item="inputItem">
            <span slot="rightIcon" style="position: absolute;right: 12%;rigth:0;top:0;font-size: 18px;cursor: pointer;"
                  @click.stop="rightIconClick" :style="rightIconStyle">
                <slot name="rightIcon"></slot>
            </span>
        </go-input>

        <go-drop-items
            ref="dropItems"
            :showValue="showValue"
            :showRightValue="showRightValue"
            @selValue="selValue"
            :selByText="inputItem['selByText']"
            @selDrop="selDrop"
            @searchFun="searchFun"
            :dataOptions="dataOptions"
            :search="search"
            :textField="textField"
            :valueField="valueField"
        ></go-drop-items>
    </div>
</template>

<script>
    import {GoingUtils, AssertUtils} from "goingutils";
    import GoCommonInput from "./go-input";
    import GoDropItems from "./go-drop-items";
    import formMixin from "../../mixins/formMixins";
    import dropCodingFactory from "../../common/dropCodingFactory";

    function __initDropInfo(vueObj, opt) {
        vueObj.dataOptions.forEach(function (item) {
            vueObj.dropCodingMap[item[opt.valueField]] = item;
        });
        if (vueObj.dropCodingMap[vueObj.value] != null) {
            vueObj.showValue = vueObj.dropCodingMap[vueObj.value][opt.textField];
        } else {
            vueObj.showValue = vueObj.value || "";
        }
    }

    export default {
        name: "go-drop",
        mixins: [formMixin],
        data: function () {
            return {
                dropSuffixIcon: 'ivu-icon ivu-icon-ios-arrow-down',
                optionsTemp: null,
                initFlag: false,
                queryUrl: "",
                dataType: "",
                dropCodingMap: {},
                dropCtlId: GoingUtils.getUUid(12),
                searchId: GoingUtils.getUUid(12),
                dataOptions: [],
            };
        },
        props: {
            showRightValue: {
                type: Boolean,
                default: false
            },
            iconRight: {},
            position: {
                type: String,
                default: "bottom"
            },
            search: {
                type: Boolean,
                default: false
            },
            items: {},
            dropWidth: {
                type: String
            }
        },
        computed: {
            disabledInput(){
                return this.inputItem.disabled;
            },
            rightIconStyle() {
                if (this.iconRight != null) {
                    if ((this.iconRight).indexOf("%") > 0) {
                        return {right: this.iconRight};
                    } else {
                        return {right: this.iconRight + 'px'};
                    }
                }
                return {};
            },
            textField() {
                return this.inputItem.textField || "label";
            },
            valueField() {
                return this.inputItem.valueField || "id";
            }
        },
        created() {
            //通过中文选择默认是通过value进行选择  如果为空 则设置为false
            if (!AssertUtils.isNotNull(this.inputItem["selByText"])) {
                this.inputItem["selByText"] = false;
            }
            //加载数据
            this.getDataOptions();
        },
        mounted: function () {
            //如果选择了值 则需要触发change事件
            this.executeChange();
            //添加关闭下拉的事件
            this.addCloseEvent();
            this.$nextTick(()=>{
                //判断是否存在radio 选择
                if(this.radioBox){
                    this.setRadioValue(this.radioVal);
                }
            });
        },
        methods: {
            //下拉后缀点击事件
            suffixClick(value,inputEl){
                this.showPageDrop(this.inputItem, inputEl);
            },
            //设置drop的radio状态
            setRadioValue(radioState){
                radioState=GoingUtils.parseBoolean(radioState);
                this.inputItem.disabled = !radioState;
            },
            rightIconClick() {
                this.$emit("rightIconClick", {id: this.value});
            },
            //查询操作
            searchFun(val) {
                if (this.optionsTemp == null) {
                    this.optionsTemp = this.dataOptions;
                } else {
                    this.dataOptions = this.optionsTemp;
                }
                let newopt = this.dataOptions.filter(word => (word.label + "").includes(val));
                this.dataOptions = [...newopt];
            },
            //点击界面其他地方 关闭下拉
            addCloseEvent() {
                let vueObj = this;
                //如果点击不是该控件范围只内 则隐藏该控件下拉
                $(document).click(function (e) {
                    let target = $(e.target);
                    if (
                        !target.is("#" + vueObj.dropCtlId + " .go-content") &&
                        !target.is("#" + vueObj.dropCtlId + " .go-content *") &&
                        !target.is("#" + vueObj.dropCtlId + " .go-common-drop") &&
                        !target.is("#" + vueObj.dropCtlId + " .go-common-drop *")
                    ) {
                        vueObj.$refs.dropItems&&vueObj.$refs.dropItems.hideDropItems();
                        vueObj.toggleSuffixIcon();
                    }
                });
            },
            //点击输入框 弹出下拉选项
            inputClick(inputEl) {
                this.showPageDrop(this.inputItem, inputEl);
            },
            //加载下拉的数据信息
            getDataOptions() {
                let vueObj = this;
                //如果下拉选项是通过inputItem的items传入
                if (this.inputItem["items"] != null && AssertUtils.isArray(this.inputItem["items"])) {
                    this.dataOptions = this.inputItem["items"];
                    //初始化下拉信息
                    __initDropInfo(vueObj, {
                        valueField: vueObj.valueField,
                        textField: vueObj.textField
                    });
                } else if (AssertUtils.isNotEmpty(this.inputItem["type"]) && this.inputItem["type"] === "sysCoding_ro") {
                    //如果没有传入options而是传人了系统编码  则根据系统编码查询数据来填充下拉数据
                    this._initUrlState({type: "sysCodingUrl"});
                } else {
                    // 如果没有传入options而是传人了的url  则根据url查询数据来填充下拉数据
                    this._initUrlState({type: "commonUrl"});
                }
            },
            executeChange() {
                //如果存在值 则需要触发change事件
                if (!this.inputItem["selByText"]) {
                    this.$emit("selDrop", {id: this.value});
                } else {
                    this.$emit("selDrop", {label: this.value});
                }
            },
            selDrop(__item) {
                this.$emit("selDrop", __item);
            },
            //选择下拉的值
            selValue(value) {
                if (this.optionsTemp != null) {
                    this.dataOptions = this.optionsTemp;
                    this.optionsTemp = null;
                }
                this.inputItem["hasError"]=false;
                this.$emit("input", value);
                //切换图标的显示
                this.toggleSuffixIcon();
            },
            //获取选中的值
            _getSelValue(__item) {
                if (this.inputItem["selByText"]) {
                    return __item[this.textField];
                } else {
                    return __item[this.valueField];
                }
            },
            _initUrlState({type = "commonUrl"}) {
                this.dataType = type;
                this.queryUrl = this.inputItem["url"];
                this._initDataByUrl(this.queryUrl, null);
            },
            //根据用户的url初始化数据
            _initDataByUrl(queryUrl, $inputObj) {
                let vueObj = this;
                dropCodingFactory.getCodingAry(queryUrl, backAry => {
                    if ($inputObj != null) {
                        $inputObj.attr("initFlag", "true");
                    }
                    //重写item的label值
                    backAry.forEach(function (item) {
                        item["label"] = item["name"];
                        item["id"] = item["value"];
                    });
                    this.dataOptions = backAry;
                    __initDropInfo(vueObj, {
                        valueField: vueObj.valueField,
                        textField: vueObj.textField
                    });
                });
            },
            loadDataByUrl() {
                //如果查询url存在 而且初始化状态为false 则点击显示的时候 初始化下拉数据
                let queryUrl = this.queryUrl;
                //        获取下拉数据信息
                if (AssertUtils.isNotEmpty(queryUrl) && this.initFlag === false) {
                    this._initDataByUrl(queryUrl);
                }
            },
            //根据下拉显示的状态来切换图标显示方式
            toggleSuffixIcon() {
                if (this.$refs&&this.$refs.dropItems&&this.$refs.dropItems.showFlag) {
                    this.dropSuffixIcon = 'ivu-icon ivu-icon-ios-arrow-up';
                } else {
                    this.dropSuffixIcon = 'ivu-icon ivu-icon-ios-arrow-down';
                }
            },
            toggleDrapShow(inputEl) {
                //显示隐藏下拉
                this.$refs.dropItems.toggleShowFlag();
                //切换图标的显示
                this.toggleSuffixIcon();
                if (this.$refs&&this.$refs.dropItems&&this.$refs.dropItems.showFlag) {
                    //获取输入框的宽度
                    let parentWid = $(inputEl).closest(".go-content-body").width();
                    //如果传入的宽度存在 则使用用户定义的宽度，负责用input的宽度
                    parentWid = !isNaN(parseFloat(this.dropWidth)) ? parseFloat(this.dropWidth) : parseFloat(parentWid);
                    //设置下拉宽的样式信息
                    this.$refs.dropItems.setDropStyles(parentWid, this.getDropYPosition(inputEl), this.getDropXPosition(inputEl));
                }
            },
            //点击输入区域 显示下拉信息
            showPageDrop(item, inputEl) {
                if (item.disabled || this.disabled) {
                    return void 0;
                }
                //如果是查询url 第一次点击加载数据
                this.loadDataByUrl();
                //设置下拉框的位置
                this.toggleDrapShow(inputEl);
            },
            //radio选择事件
            radioBoxClick(data) {
                this.$emit("radioBoxClick", {item: this.inputItem, data});
            },
            //初始化显示值
            _initShowValue(newVal){
                //如果选择了值 则需要触发change事件
                if (this.dropCodingMap[newVal] != null) {
                    this.showValue = this.dropCodingMap[newVal][this.textField];
                } else {
                    this.showValue = newVal || "";
                }
            }
        },
        watch: {
            value: function (newVal) {
                this.executeChange();
                this._initShowValue(newVal);
            },
            //监听radio选项值的变化
            radioVal(newVal){
                if(this.radioBox){
                    this.setRadioValue(newVal);
                }
            }
        },
        components: {
            GoCommonInput,
            GoDropItems: GoDropItems
        }
    };
</script>
