<template>
    <div class="row go-input-acl-input go-form-row  go-common-drop-ctl">
        <go-label :labelWidth="labelWidth" :labelAlign="labelAlign" :item="inputItem"></go-label>
        <div  :class="'go-content ' + getInputWid()" :style="getInputWidStyle()">
            <div class="go-content-body" :class="'input-group ' + getInputWid()" :style="inputGroupStyle"
                 @click="showAclWin">
                <input :itemId="inputItem.id" ctlType="aclWin" class="hidden" type="hidden"/>

                <div ref="selItemContainer"
                     :class="extendClass"
                     :style="inputGroupStyle">
                    <span v-if="showItems.length === 0" style="padding: 0 0 0 5px;" class="placeholder">请选择{{ inputItem.label }}</span>

                    <ul class="user-ul-acl clearfix" v-else>
                        <li
                            :key="index"
                            class="choice-item-com"
                            :name="userItem.name"
                            :id="userItem.id"
                            :dataForm="_getDataForm(index)"
                            v-for="(userItem, index) of showItems"
                            :dataFromLabel="_getDataFromLabel(userItem.name)"
                        >
                            <span>{{ getUserLabel(userItem.name) }}</span>
                            <i
                                class="choice-close ivu-icon ivu-icon-md-close"
                                @click.stop="removeRecord(userItem)"
                                type="md-close"
                            ></i>
                        </li>
                    </ul>
                </div>

                <div class="go-input-acl-icon" v-show="!inputItem.disabled" style=" position: absolute;right:26px;top:-2px;" @click.stop="clickClearBtn">
                    <Icon style="font-size: 16px;color: #4A8AE9"  type="ios-close-circle"></Icon>
                </div>


                <go-drop-icon></go-drop-icon>
                <!--校验提醒图标-->
                <go-error-icon v-model="value" :rightSlot="rightSlot" :right="clearIconRight||inputItem.clearIconRight"
                               :validMsg="validMsg||inputItem.validMsg"
                               :errorFlag="errorFlag||inputItem.hasError"></go-error-icon>

            </div>
        </div>
    </div>
</template>

<script>
    import GoLabel from "./commponents/go-label";
    import GoErrorIcon from "./commponents/go-error-icon";
    import GoDropIcon from "./commponents/go-drop-icon";
    import formMixin from "../../mixins/formMixins";
    import goDialog from "../../jsCom/go-dialog";
    import {AssertUtils, GoingUtils} from "goingutils";
    import goAclWinUtils from "../../jsCom/goForm/components/go-aclWin-ctl-event";
    import WinUtils from "../../winUtils";

    export default {
        name: "go-input-acl",
        mixins: [formMixin],
        data: function () {
            return {
                diaWinObj: null,
                showLabelFlag: true,
                dataFroms: [],
                moreHeight: 65,
            };
        },
        props: {
            excludeIds: {
                type: Array,
                default: () => []
            },
            //返回的id是否需要带类型
            hasType: {
                type: Boolean,
                default: false
            },
            winTitle: {},
            tabs: {},
            //弹出的相关参数
            params: {},
            //校验选中的数据
            validateSelRecord: {},
            //弹框前 的前置事件
            showBefore: {},
            ids: {
                type: String,
                default: ""
            },
            moreSel: {
                type: Boolean,
                default: false
            },
            initSels: {
                type: String
            },
            //传入的设置的数据在列表中的索引
            dataIndex: {
                type: Number,
                default: 0,
            }
        },
        computed: {
            //扩展样式信息
            extendClass() {
                let inputItemObj = this.inputItem;
                //是否显示校验样式 和disabled的样式
                let classes = [this.inputItem.hasError ? 'error-input' : '', inputItemObj.disabled ? 'input-disabled' : ''];
                //判断是否用户传入了errorFlag
                if (this.errorFlag) {
                    classes.push("error-input");
                }
                return [...classes, 'sel-item-container', 'clearfix'];
            },
            inputGroupStyle() {
                if (this.moreSel && this.inputItem) {
                    return {cursor: "pointer", height: this.moreHeight + "px"};
                } else if (this.inputItem && !this.inputItem.disabled) {
                    return {cursor: "pointer"};
                }
                return {};
            },
            showItems() {
                let userObjs = [];
                if (this.value == null || this.value === "") {
                    return userObjs;
                }
                let selNames = (this.value + "").split(GoingUtils.relChart);
                let selIds = (this.ids + "").split(GoingUtils.relChart);
                selNames.forEach((name, index) => {
                    if (selIds.length > index) {
                        userObjs.push({id: selIds[index], name});
                    } else {
                        console.error && console.error(`选人组件名称【${name}】存在，而id不存在，请确认！`);
                    }
                });
                return userObjs;
            },
        },
        methods: {
            clickClearBtn(){
                this.$emit("input", "");
                this.$emit("clearRecords", {selIds:'',selNames:''});
            },
            //获取输入框的样式信息
            getInputWidStyle() {
                let styleJson = this._getInputWidStyle(this.width);
                //是否可以多选
                if (this.moreSel) {
                    styleJson["height"] = this.moreHeight + 2 + "px";
                }
                return styleJson;
            },
            //获取用户的数据来源信息
            _getDataFromLabel(userLabel) {
                return userLabel.split("_")[1];
            },
            _getDataForm(index) {
                return this.dataFroms[index] || '';
            },
            //获取用户的label信息
            getUserLabel(userLabel) {
                if (this.hasType) {
                    return userLabel;
                } else {
                    return userLabel.split("_")[0];
                }
            },
            //获取用户的id
            getUserIds(index, userItem) {
                let selIds = (this.ids + "").split(GoingUtils.relChart);
                if (selIds[index] != null) {
                    return selIds[index];
                } else {
                    return userItem;
                }
            },
            //移除相应的值
            removeRecord(userItem) {
                if (this.inputItem.disabled || this.inputItem.readonly) {
                    return void (0);
                }
                let selNames = (this.value + "").split(GoingUtils.relChart);
                let selIds = (this.ids + "").split(GoingUtils.relChart);
                if (selIds == null || selIds === "") {
                    GoingUtils.showWinErrorMessage("您可能没有设置授权组件的id接收，请确认");
                    return void (0);
                }
                selIds.forEach(function (idStr, index) {
                    if (idStr === userItem.id) {
                        selIds.splice(index, 1);
                        selNames.splice(index, 1);
                    }
                });
                //回写相应的值
                this.setInputValue(selIds, selNames, "");
            },
            //点击确定按钮
            executeConfirm(vueObj, aclCtl) {
                this.diaWinObj = null;
                //获取返回的ids
                let {selIds, selNames, accountId, backFlag, dataFroms} = aclCtl.getBackInfos(vueObj.inputItem.config["count"], this.hasType);
                this.dataFroms = dataFroms;
                //如果返回false 则表示出现了提示信息
                if (backFlag === false) {
                    return backFlag;
                }
                //对选择的数据进行校验
                if (AssertUtils.isNotNull(this.validateSelRecord) && AssertUtils.isFunction(this.validateSelRecord)) {
                    let flat = this.validateSelRecord({selIds: selIds.join(""), selNames});
                    if (!flat) {
                        return flat;
                    }
                }
                //需要返回数组的情况 才进行操作
                if (AssertUtils.isNotNull(selNames) && AssertUtils.isArray(selNames)) {
                    this.setInputValue(selIds, selNames, accountId);
                }
                this.$emit("confirmAfter", {});
            },
            //回写输入框的值
            setInputValue(selIds, selNames, accountId) {
                //提交数据
                this.$emit("input", selNames.join(GoingUtils.relChart));
                //执行回调方法
                this.$emit("selRecords", {
                    selIds: selIds.join(GoingUtils.relChart),
                    selNames: selNames.join(GoingUtils.relChart),
                    accountId: accountId,
                    index: this.dataIndex
                });
                this.clearErrorState();
                setTimeout(() => {
                    this.validateFun();
                }, 100);
            },
            _initBtnEvent() {
                //定义确定按钮事件
                this.inputItem.config["confirmBtn"] = (aclCtl) => {
                    var flag = this.executeConfirm(this, aclCtl);
                    //如果返回了false 则表示有提示信息出现
                    if (flag !== false) {
                        //关闭窗口
                        WinUtils.closeParentCurWin();
                        //销毁授权对象的内存信息
                        goDialog.destructionAcl();
                    }
                };
            },
            _initAlreadySelValue(tabs) {
                let vueObj = this;
                //设置控件的初始化值
                if (AssertUtils.isNotEmpty(this.value)) {
                    let {ids, names, dataForms} = goAclWinUtils.getAclWinIdsAndNames(
                        $(vueObj.$refs.selItemContainer)
                    );
                    this.inputItem.config["initFun"] = function () {
                        return {
                            ids: ids.join(GoingUtils.relChart),
                            names: names.join(GoingUtils.relChart),
                            dataForms,
                            hasType: vueObj.hasType,
                            tabs: tabs,
                        };
                    };
                }else{
                    this.inputItem.config["initFun"] = function () {
                        return {
                            ids: "",
                            names: "",
                            dataForms:"",
                            hasType: vueObj.hasType,
                            tabs: tabs,
                        };
                    };
                }
            },
            //显示授权窗口
            showAclWin() {
                //防止重复弹框
                if (this.diaWinObj != null) {
                    return void (0);
                }
                if (this.inputItem.disabled || this.inputItem.readonly) {
                    return void (0);
                }
                //如果没有传入config对象 则需要自己构建
                if (this.inputItem.config == null) {
                    this.inputItem.config = {};
                }
                //需要设置相应的配置信息才行
                if (this.inputItem.config != null) {
                    //定义确定按钮事件
                    this._initBtnEvent();
                    //如果传入了 tabs 则使用传入的tabs为主
                    if (AssertUtils.isNotNull(this.tabs) && AssertUtils.isArray(this.tabs)) {
                        this.inputItem.config["tabs"] = this.tabs;
                    }
                    //初始化以前选择的记录
                    this._initAlreadySelValue(this.inputItem.config["tabs"]);
                    //弹框前对数据进行校验
                    if (AssertUtils.isNotNull(this.showBefore) && AssertUtils.isFunction(this.showBefore)) {
                        let flat = this.showBefore();
                        if (!flat) {
                            return void (0);
                        }
                    }
                    //是否定义了参数函数
                    if (AssertUtils.isNotNull(this.params)) {
                        //将参数传递到组件中
                        this.inputItem.config["params"] = this.params;
                    }
                    if (AssertUtils.isNotNull(this.excludeIds)) {
                        //将参数传递到组件中
                        this.inputItem.config["excludeIds"] = this.excludeIds;
                    }
                    //如果传入了 winTitle 则使用传入的winTitle
                    if (AssertUtils.isNotEmpty(this.winTitle)) {
                        this.inputItem.config["title"] = this.winTitle;
                    }

                    //如果设置单选，而又没有定义选择的数量 则设置为单选
                    if (!this.moreSel && this.inputItem.config["count"] == null) {
                        this.inputItem.config["count"] = 1;
                    }

                    this.inputItem.config["closeWin"] = () => {
                        this.diaWinObj = null;
                    };
                    //设置授权窗口信息
                    this.diaWinObj = goDialog.attachAclWin(this.inputItem.config, this);
                }
            }
        },
        watch: {
            //如果disabled状态发生变化
            disabled(newVal) {
                this.inputItem["disabled"] = newVal;
            }
        },
        components: {
            GoErrorIcon,
            GoLabel,
            GoDropIcon: GoDropIcon
        }
    };
</script>

