<template>
    <div>
        <el-select v-model="dataValue"
                   :disabled="disabled"
                   :filterable="filterable"
                   clearable
                   :allowCreate="allowCreate"
                   :multiple="multiple"
                   :size="size" v-if="!showText && isDiy"
                   @change="onChange" :placeholder="disabled ? '' : placeholder" style="width: 100%;">
            <el-option
                    v-for="(item,index) in valueArr"
                    :label="item.label"
                    :value="item.value"
                    :key="index">
            </el-option>
        </el-select>
        <el-select v-model="dataValue"
                   :disabled="disabled"
                   :filterable="filterable"
                   clearable
                   :allowCreate="allowCreate"
                   :multiple="multiple"
                   :size="size" v-if="!showText && !isUsertree && !isDiy && !isPostree  && !isOrgtree&&isTreeData=='0' "
                   @change="onChange" :placeholder="disabled ? '' : placeholder" style="width: 100%;">
            <el-option
                    v-for="item in arrDatas"
                    :key="item.id"
                    v-if="!filterNotIds || filterNotIds.indexOf(item.id)==-1"
                    :label="item[dataName]"
                    :value="item[dataId]">
            </el-option>
        </el-select>
        <!--开启树下拉框-->
        <pl-select-tree v-if="(isOrgtree || isPostree)&&!showText&&showSelectTree" v-model="dataValue" :options="arrDatas" :props="isPostree?posSelectTreeProps:defaultSelectTreeProps" :change-data="changeData"
                        :multiple="multiple" :readonly="disabled" :filterable="filterable">
        </pl-select-tree>
        <pl-select-tree v-if="isTreeData=='1'&&treeDataType&&!showText&&showSelectTree" v-model="dataValue" :options="arrDatas" :props="treeDataTypeBak" :change-data="changeDataTree"
                        :multiple="multiple" :readonly="disabled" :backParentName="backParentName" :filterable="filterable">
        </pl-select-tree>
        <!--开启树下拉框 end-->
        <el-select v-model="dataValue"
                   :disabled="disabled"
                   :filterable="filterable"
                   :allowCreate="allowCreate"
                   :multiple="multiple"
                   :collapse-tags="collapseTags"
                   :filter-method="changeUser" clearable @clear="changeUser('')"
                   @blur="changeUserBlur"
                   ref="userTreeRef"
                   :size="size" v-if="!showText && isUsertree && !isDiy&&showSelect"
                   @change="onChange" :placeholder="disabled ? '' : placeholder" style="width: 100%;">
            <el-option
                    v-for="item in arrDatas"
                    :key="item.id"
                    v-if="!filterNotIds || filterNotIds.indexOf(item.id)==-1"
                    :label="item[dataName]"
                    :value="item[dataId]">
                <span>{{item[dataName] + (userOrgObj[item.userId] ? '-' : '') + (userOrgObj[item.userId] || '')}}</span>
            </el-option>
        </el-select>
        <div v-if="showText" style="height: 36px;">
            <span v-if="(isOrgtree|| isPostree ||isUsertree)">
                {{dataValueUser || formData[backfillField] || ""}}
            </span>
            <span v-if="multiple && !isOrgtree &&! isPostree && !isUsertree" v-for="(value,index) in dataValue" :key="index">
                {{arrDatasObj[value] === undefined ? "" : arrDatasObj[value] + ((index === (dataValue.length - 1)) ? "" : ",")}}
                <!--{{(arrDatasObj[value] || "") + ((index === (dataValue.length - 1)) ? "" : ",")}}-->
                <!--{{(arrDatasObj[value] || value) + ((index === (dataValue.length - 1)) ? "" : ",")}}-->
            </span>
            <span v-if="!multiple && !isOrgtree &&! isPostree && !isUsertree ">
                {{arrDatasObj[dataValue] || ""}}
                <!--{{arrDatasObj[dataValue] || dataValue || ""}}-->
            </span>
            <div v-if="measurementShow" style="display: inline-block">
                {{measurementShow || ""}}
            </div>
            <pl-eye-image v-if="showSee" :field="field" :onEyeChange="onSelectChange"></pl-eye-image>
            <!--<div v-if="showSee" class="saspiconfont pl-icon-Group-" style="display: inline-block;position: absolute;right: 15px;" @click="onEyeChange"></div>-->
        </div>
    </div>
</template>

<script>
    import {PlSelectTree} from 'sasp-base';
    import PinyinMatch from 'pinyin-match';

    export default {
        name: "pl-data-select",
        components: {
            PlSelectTree
        },
        props: {
            typeId: {required: false, default: ""},
            dataFormId: {required: false, default: ""},
            field: {required: false, default: ""},
            parentId: {required: false, default: "-1"},
            value: {required: false, default: ""},
            disabled: {required: false, default: false},
            size: {required: false},
            filterable: {required: false, default: false, type: Boolean},
            clearable: {required: false, default: false, type: Boolean},
            multiple: {required: false, default: false, type: Boolean},
            change: {required: false, type: Function},
            filterNotIds: {required: false},
            defultValue: {required: false},
            reqUrl:{default:""}, // 请求路径
            labelField:{default:"dataName"}, // 值域
            valueField:{default:"id"}, // 文本域
            displayColFieIds: {default:""},
            backfillSetting:{required: false,default: ""},
            placeholder:{default:"请选择"},
            showText:{required: false, default: false, type: Boolean}, // 自定义下拉框查看时显示文本
            showSee: {required: false, default: false, type: Boolean}, // 自定义下拉框查看时显示小眼睛
            allowCreate:{default:false},
            measurementShow:{default:false},// 自定义下拉框显示单位
            rememberSysDataObj:{type:Function},
            onSelectChange:{type:Function},
            isOrgtree:{required: false, default: false, type: Boolean},//组织下拉框
            isPostree:{required: false, default: false, type: Boolean},//岗位下拉框
            isUsertree:{required: false, default: false, type: Boolean},//用户下拉框
            orgDim:{required: false, default: ""},
            orgLevel:{required: false, default: ""},
            saveType:{required: false, default: ""},
            backfillField:{required: false, default: ""},
            formData:{type:Object},
            listOutParam:{type:Object},//外部传入参数
            isDiy:{required: false, default: false, type: Boolean},//自定义下拉框
            valueArr:{required: false, type: Array},
            openTree:{required: false, type: false},
            changeField:{type:Function},
            userData:{required:false,type:Array},//用户数据 外部传入内部就不再查询数据
            isTreeData:{type:String,default:"0"},//是否需要处理为树数据
            treeDataType:{type:String},//是否需要处理为树数据
            backParentName:{type:String,default:"0"},//是否回填上级名称
            collapseTags:{type:Boolean,default:false},
            showLockUser:{type:Boolean,default:false},//是否显示已锁定用户
        },
        data() {
            return {
                // 需要定义个内部变量接收传入的值，选择下拉框的时候改的也是这个值，如果不用内部变量接收的情况下，直接改传入的value的值会报警告
                dataValue: "",
                arrDatas: [],
                objDataVuleToData: {},
                dataName:"dataName",
                dataId:"id",
                selectedItem: {}, // 下拉框改变时选中的对象
                showDataName: "_show_name",
                currentParentId:"",
                arrDatasObj:{}, // 下拉数据的对象
                dataValueUser:"",
                usersNameArr:[],
                arrDatasCopy:[],
                defaultSelectTreeProps: {
                    parent: 'parentId',   // 父级唯一标识
                    value: 'id',          // 唯一标识
                    label: 'orgName',       // 标签显示
                    children: 'children', // 子级
                },
                posSelectTreeProps: {
                    parent: 'parentId',   // 父级唯一标识
                    value: 'id',          // 唯一标识
                    label: 'orgName',       // 标签显示
                    children: 'children', // 子级
                    disabledd:"posName",//不可点击的判断属性
                    disabled:"orgParentId",//不可点击的判断属性
                },
                showSelectTree:false,//树显示
                showSelect:false,
                treeDataTypeBak:{},
                userOrgObj:{},
                userIdObj:{},
            };
        },
        mounted(){
            // if(!this.isUsertree){
            //     if(this.multiple){
            //         // 多选情况下：
            //         // 添加表单初始化时如果没有值时设置为[]，修改表单初始化时为string需要转化
            //         if(this.isOrgtree || this.isPostree){//组织岗位默认值不需要转
            //             if(!this.dataValue){
            //                 this.dataValue = "";
            //                 //this.dataValue = this.value;
            //             }
            //         }else if(this.value && this.value.constructor == Array){
            //             this.dataValue = this.value;
            //         }else if(this.value){
            //             this.dataValue = this.value.split(",");
            //         }else{
            //             this.dataValue = [];
            //         }
            //     }else{
            //         if(this.value==undefined || this.value==''){
            //             this.dataValue =this.defultValue;
            //         }else{
            //             this.dataValue=this.value;
            //         }
            //     }
            // }
        },
        watch: {
            typeId() {
                this.initDataSelect();
            },
            parentId() {
                this.initDataSelect();
            },
            /*value() {
                if(this.value==undefined || this.value==''){
                    this.dataValue =this.defultValue;
                }else{
                    this.dataValue=this.value;
                }
            },*/
            reqUrl() {
                this.initDataSelect();
            },
            filterNotIds() {
                if (this.filterNotIds && this.filterNotIds.indexOf(this.value) > -1) {
                    this.dataValue = "";
                    this.onChange();
                }
            },
            value(){ //监听值变化重新赋值
                if(this.value==undefined || this.value==''){
                    this.dataValue = this.defultValue;
                }else{
                    this.dataValue= this.value;
                }
            }
        },
        created() {
            // if(this.value==undefined || this.value==''){
            //     this.dataValue = this.defultValue;
            // }else{
            //     this.dataValue = this.value;
            // }
            if(this.isOrgtree){
                this.initOrgTree();
            }else if(this.isPostree){
                this.initPosTree();
            }else if(this.isUsertree){
                // if( this.multiple && !Array.isArray(this.value)){
                //     try{
                //         if(this.value){
                //             this.dataValue =JSON.parse(this.value);
                //         }
                //     }catch (e) {
                //         this.dataValue =this.value.split(",");
                //     }
                // }
                // if(!this.dataValue && this.multiple){//多选为空需要手动赋值[]
                //     this.dataValue=[];
                // }
                // this.$emit('input',this.dataValue);
                this.initUserTree();
            }else{
                this.initDataSelect();
            }
            // let reg = /^[\u4E00-\u9FA5]+/g; //含繁体
            let reg = /^[\u0391-\uFFE5]+/g;
            if (reg.test(this.value) && this.value) {
                this.dataValue = this.value;
            }
        },
        methods: {
            initDataValue(){ // 初始化数据值，不能在下拉数据未加载时显示ID字串
                if(!this.value){
                    this.dataValue = this.defultValue;
                }else{
                    this.dataValue = this.value;
                }
                if(!this.isUsertree){
                    if(this.multiple){
                        // 多选情况下：
                        // 添加表单初始化时如果没有值时设置为[]，修改表单初始化时为string需要转化
                        if(this.isOrgtree || this.isPostree){//组织岗位默认值不需要转
                            if(!this.dataValue){
                                this.dataValue = "";
                                //this.dataValue = this.value;
                            }
                        }else if(this.value && this.value.constructor == Array){
                            this.dataValue = this.value;
                        }else if(this.value){
                            this.dataValue = this.value.split(",");
                        }else{
                            this.dataValue = [];
                        }
                    }else{
                        if(!this.value){
                            this.dataValue =this.defultValue;
                        }else{
                            this.dataValue=this.value;
                        }
                    }
                }else{
                    if(this.multiple && !Array.isArray(this.value)){
                        try{
                            if(this.value){
                                this.dataValue =JSON.parse(this.value);
                            }
                        }catch (e) {
                            this.dataValue =this.value.split(",");
                        }
                    }
                    if(!this.dataValue && this.multiple){//多选为空需要手动赋值[]
                        this.dataValue=[];
                    }
                    this.$emit('input',this.dataValue);
                }
            },
            /**
             * 加载数据字典下拉框
             */
            initDataSelect() {
                let vm = this;
                if (!vm.typeId && !vm.reqUrl && !vm.dataFormId) {
                    return;
                }
                vm.objDataVuleToData = {};
                vm.currentParentId = vm.parentId || "";
                vm.arrDatasObj = {};
                if(vm.reqUrl){
                    vm.dataName = vm.labelField + vm.showDataName;
                    vm.dataId = vm.valueField;
                    let url=vm.reqUrl;
                    let requestParam={};
                    if(url.includes("?")){//分割参数
                        let httpurl=url.split("?")[0];
                        let params=url.split("?")[1];
                        requestParam=this.getParamToObj(requestParam,params);
                        url=httpurl;
                    }

                    let serviceName = (window.SERVICE_NAME || {});
                    let adminServeName = serviceName.admin || "/admin/";
                    let formServeName = serviceName.form || "/form/";
                    let flowServeName = serviceName.flow || "/flow/";
                    let oaServeName = serviceName.oa || "/oaproject/";
                    // url = window.FORM_RENDER_URL + "/" + url;

                    // url = vm.platStringUtil.replaceAll(url,"/admin/",adminServeName);
                    // url = vm.platStringUtil.replaceAll(url,"/form/",formServeName);
                    // url = vm.platStringUtil.replaceAll(url,"/flow/",flowServeName);
                    // url = vm.platStringUtil.replaceAll(url,"/oaproject/",oaServeName);
                    // url = vm.platStringUtil.replaceAll(url,"/oaadmin/",adminServeName);
                    // url = vm.platStringUtil.replaceAll(url,"/oaform/",formServeName);
                    // url = vm.platStringUtil.replaceAll(url,"/oaflow/",flowServeName);

                    if(url.indexOf("http://") == -1 && url.indexOf("https://") == -1 ){
                        if(window.ADMIN_URL && (url.startsWith("admin/") || url.startsWith("oaadmin/"))){
                            url = vm.platStringUtil.replaceAll(url,"oaadmin/","/");
                            url = vm.platStringUtil.replaceAll(url,"admin/","/");
                            url = window.ADMIN_URL + url
                        }else if(window.FLOW_URL && (url.startsWith("flow/") || url.startsWith("oaflow/"))){
                            url = vm.platStringUtil.replaceAll(url,"oaflow/","/");
                            url = vm.platStringUtil.replaceAll(url,"flow/","/");
                            url = window.FLOW_URL + url
                        }else if(window.FORM_RENDER_URL && (url.startsWith("form/") || url.startsWith("oaform/"))){
                            url = vm.platStringUtil.replaceAll(url,"oaform/","/");
                            url = vm.platStringUtil.replaceAll(url,"form/","/");
                            url = window.FORM_RENDER_URL + url
                        }else if(window.OA_URL && (url.startsWith("project/") || url.startsWith("oaproject/"))){
                            url = vm.platStringUtil.replaceAll(url,"oaproject/","/");
                            url = vm.platStringUtil.replaceAll(url,"project/","/");
                            url = window.OA_URL + url
                        }else{
                            url = window.FORM_RENDER_URL + "/" + url;
                        }
                    }
                    let displayColFieIdsArr = vm.displayColFieIds ? vm.displayColFieIds.split(",") : [];
                    vm.axios.post(url,requestParam).then(res => {
                        this.initDataValue();
                        let arr = [];
                        arr = (res.data.operateObj ? res.data.operateObj : res.data) || [];
                        arr.forEach( item => {
                            let displayFieIdVal = "";
                            displayColFieIdsArr.forEach(dis => {
                                if (!displayFieIdVal) {
                                    displayFieIdVal += "(" + item[dis];
                                } else {
                                    displayFieIdVal += "-" +  item[dis];
                                }
                            });
                            if (displayFieIdVal) {
                                displayFieIdVal += ")";
                            }
                            vm.$set(item,vm.labelField + vm.showDataName,item[vm.labelField] + displayFieIdVal);
                            if(!item.id && item.ID){
                                vm.$set(item,"id",item.ID);
                            }
                        })
                        let arrBak=[];
                        if(Array.isArray(arr)){
                            arrBak=JSON.parse(JSON.stringify(arr));
                        }
                        vm.showSelectTree=false;
                        if(vm.isTreeData =='1' && vm.treeDataType){//处理为树数据
                            let obj=JSON.parse(vm.treeDataType);
                            let paramSetting = {"id":vm.valueField,"pId":obj.parent,"children":obj.children,"label":vm.labelField,"value":vm.valueField,"parentTree":obj.parentTree};
                            vm.treeDataTypeBak=paramSetting;
                            vm.arrDatas=this.COMMON_FUNC.buildElTree(arr, paramSetting);
                            this.$nextTick(() => {
                                vm.showSelectTree=true;
                            })
                        }else{
                            vm.arrDatas=arr;
                            this.$nextTick(() => {
                                vm.showSelectTree=true;
                            })
                        }
                        arrBak.forEach(item => {
                            vm.$set(vm.arrDatasObj,item[vm.valueField],item[vm.labelField]);
                        });
                        if(this.backParentName=='1'&&this.value.includes("-")){//开启回填上级名称需要额外处理数据
                            let arr = this.value.split("-");
                            let label="";
                            arr.forEach(item =>{
                                if(vm.arrDatasObj[item]){
                                    label +="-"+vm.arrDatasObj[item];
                                }else{
                                    label+="";
                                }
                            })
                            vm.$set(vm.arrDatasObj,this.value,label.substring(1));
                        }
                        vm.rememberSysDataObj && vm.rememberSysDataObj(vm.field,arrBak);
                    })
                }else if(vm.dataFormId){
                    let proimise = this.axios.post(this.api.plFormQuery.find,{formId:vm.dataFormId});
                    proimise.then(res => {
                        let datas = res.data || [];
                        this.initDataValue();
                        vm.dataName = vm.labelField;
                        vm.dataId = vm.valueField;
                        vm.arrDatas = datas || [];
                        vm.arrDatas.forEach((dataEach) => {
                            vm.objDataVuleToData[dataEach[vm.valueField]] = dataEach;
                            vm.$set(vm.arrDatasObj,dataEach[vm.valueField],dataEach[vm.labelField]);
                        });
                        vm.rememberSysDataObj && vm.rememberSysDataObj(vm.field,vm.arrDatasObj);
                    });
                }else{
                    let proimise = this.DATA_GLOBAL.getDatas(this.typeId,this.currentParentId);
                    if(this.showText){
                        proimise = this.DATA_GLOBAL.getDatasContainOutDate(this.typeId,this.currentParentId);
                    }
                    proimise.then(datas => {
                        this.initDataValue();
                        vm.arrDatas = datas || [];
                        vm.arrDatas.forEach((dataEach) => {
                            vm.objDataVuleToData[dataEach.id] = dataEach;
                            //存入key name
                            vm.DATA_GLOBAL.setKeyName(dataEach.id, dataEach.dataName);
                            vm.$set(vm.arrDatasObj,dataEach.id,dataEach.dataName);
                        });
                        vm.rememberSysDataObj && vm.rememberSysDataObj(vm.field,vm.arrDatasObj);
                    });
                }
            },

            /**
             * 处理get请求参数，返回对象
             */
            getParamToObj(result,params){
                if(params.includes("&")){
                    let arr=params.split("&");
                    arr.forEach(data =>{
                        let key=data.split("=")[0];
                        let value=data.substring(data.indexOf("=")+1);
                        if(value.includes("${listOutParam.")){
                            let str1=value.split("${listOutParam.")[0];
                            let str2=value.split("${listOutParam.")[1];
                            value=str1+"'"+this.listOutParam[str2.split("}")[0]]+"'"+str2.split("}")[1];
                        }
                        if(value.includes("${loginUser.")){
                            let str1=value.split("${loginUser.")[0];
                            let str2=value.split("${loginUser.")[1];
                            let loginUser =  this.CACHE_GLOBAL.getLoginUser();
                            if(!loginUser.id){
                                loginUser = this.FORM_USER_GLOBAL.getLoginUser();
                            }
                            if(str2.split("}")[0] == "id"){
                                value=str1+loginUser.id+str2.split("}")[1];
                            }
                            if(str2.split("}")[0] == "userName"){
                                value=str1+loginUser.userName+str2.split("}")[1];
                            }
                        }
                        this.$set(result,key,value);
                    })
                }else{
                    let key=params.split("=")[0];
                    let value=params.substring(params.indexOf("=")+1);
                    if(value.includes("${listOutParam.")){
                        let str1=value.split("${listOutParam.")[0];
                        let str2=value.split("${listOutParam.")[1];
                        value=str1+"'"+this.listOutParam[str2.split("}")[0]]+"'"+str2.split("}")[1];
                    }
                    if(value.includes("${loginUser.")){
                        let str1=value.split("${loginUser.")[0];
                        let str2=value.split("${loginUser.")[1];
                        let loginUser =  this.CACHE_GLOBAL.getLoginUser();
                        if(!loginUser.id){
                            loginUser = this.FORM_USER_GLOBAL.getLoginUser();
                        }
                        if(str2.split("}")[0] == "id"){
                            value=str1+loginUser.id+str2.split("}")[1];
                        }
                        if(str2.split("}")[0] == "userName"){
                            value=str1+loginUser.userName+str2.split("}")[1];
                        }
                    }
                    this.$set(result,key,value);
                }
                return result;
            },
            onChange() {
                let vm = this;
                let label = "";
                vm.arrDatas.forEach(item => {
                    if(item[this.valueField] === vm.dataValue ){
                        label = item[this.labelField];
                        vm.selectedItem = item;
                    }
                });

                if(this.isUsertree && this.saveType == "text"){
                    let text = this.userIdObj[this.dataValue];
                    // 把值通过返回给父组件的值
                    this.$emit('input', text);
                    this.change && this.change(text, label);
                    this.$emit('change', text);
                }else{
                    // 把值通过返回给父组件的值
                    this.$emit('input', this.dataValue);
                    this.change && this.change(this.dataValue, label);
                    this.$emit('change', this.dataValue);
                }
                //调用回调方法，回调赋值
                this.initBackField();
            },
            // 回调赋值
            async initBackField() {
                if (this.backfillSetting && this.formData) {
                    // 处理数据回填，根据backfillSetting中的对应关系来回填数据，value中的值是字段的ID,lable是查询接口中的对应字段名
                    this.backfillSetting.forEach(backfill =>{
                        this.$set(this.formData, backfill["value"],this.selectedItem[backfill["label"]])
                    });
                }
                if (this.backfillField && this.formData) {//回调字段
                    if (this.saveType && this.saveType == 'text') {
                        if(this.isUsertree){
                            let text = this.userIdObj[this.dataValue];
                            if(!this.showText || text){ // 查看时如果回调字段有值，赋值没值，则不赋值
                                this.$set(this.formData, this.backfillField, text);
                            }
                        }else{
                            //存的是文本的话不用转 直接赋值
                            if(!this.showText || this.dataValue) { // 查看时如果回调字段有值，赋值没值，则不赋值
                                this.$set(this.formData, this.backfillField, this.dataValue);
                            }
                        }
                    } else if (this.saveType && this.saveType == 'dataId') {
                        let result = "";
                        this.arrDatasCopy.forEach(item => {
                            if (Array.isArray(this.dataValue)) {//多选情况
                                this.dataValue.forEach(posItem => {
                                    if (posItem == item.id) {
                                        result += "," + item.dataName;
                                    }
                                });
                            } else if (this.dataValue && this.dataValue == item.id) {//单选
                                result = item.dataName;
                            }
                        })
                        if(result[0] == ","){
                            result = result.substring(1);
                        }
                        if(!this.showText || result){ // 查看时如果回调字段有值，赋值没值，则不赋值
                            this.$set(this.formData, this.backfillField, result);
                        }
                    }
                }
            },
            //初始化组织树下拉框
            initOrgTree(){
                let param={};
                this.arrDatas=[];
                this.showSelectTree=false;
                this.$set(param,"orgDim",this.orgDim);
                if(this.orgLevel){
                    this.$set(param,"orgLevel",this.orgLevel);
                }
                let userDept = this.CACHE_GLOBAL.getLoginDept();
                if(userDept && userDept.id){
                    this.$set(param,"id",userDept.id);
                }
                if(userDept && userDept.orgParentId){
                    this.$set(param,"orgParentId",userDept.orgParentId);
                }
                this.axios.post(this.api.sysOrg.findOrgTree,param).then(res=>{
                    this.initDataValue();
                    if(res.data&&res.data.operateObj){
                        let resData=res.data.operateObj || [];
                        let result="";
                        resData.forEach(item=>{
                            if(this.saveType == "text"){
                                this.arrDatas.push(item);
                                if(!this.multiple && item.orgName == this.dataValue){//单选
                                    result +=","+ item.id;
                                }else if(this.multiple){ //多选
                                    if(this.dataValue.includes(",")){//多数据--字符串
                                        ( this.dataValue.split(",") || []).forEach(mulItem => {
                                            if(mulItem == item.orgName){
                                                result +=","+item.id;
                                            }
                                        })
                                    }else if(Array.isArray(this.dataValue)){//多数据--数组
                                        ( this.dataValue || []).forEach(mulItem => {
                                            if(mulItem == item.orgName){
                                                result +=","+item.id;
                                            }
                                        })
                                    } else if(this.dataValue == item.orgName){//单数据
                                        result =","+item.id;
                                    }
                                }
                            }else if(this.saveType == "dataId"){
                                this.arrDatas.push(item);
                                if(!this.multiple && item.id == this.dataValue){//单选
                                    result +=","+ item.orgName;
                                }else if(this.multiple){ //多选
                                    if(this.dataValue.includes(",")){//多数据--字符串
                                        ( this.dataValue.split(",") || []).forEach(mulItem => {
                                            if(mulItem == item.id){
                                                result +=","+item.orgName;
                                            }
                                        })
                                    }else if(Array.isArray(this.dataValue)){//多数据--数组
                                        ( this.dataValue || []).forEach(mulItem => {
                                            if(mulItem == item.id){
                                                result +=","+item.orgName;
                                            }
                                        })
                                    } else if(this.dataValue == item.id){//单数据
                                        result =","+item.orgName;
                                    }
                                }
                            }
                        })
                        if(this.saveType == "text"){//文本格式的赋值
                            this.dataValueUser=this.dataValue;
                            this.dataValue=result.substring(1);
                        }
                        if(this.saveType == "dataId"){//关联标识的赋值
                            this.dataValueUser=result.substring(1);
                        }
                        if(this.backfillField){//回调初始化赋值
                            this.$set(this.formData, this.backfillField, this.dataValueUser);
                        }
                        if(this.openTree){
                            let paramSetting={};
                            paramSetting["id"] = "id";
                            paramSetting["pId"] = "orgParentId";
                            paramSetting["children"] = "children"; // 设置children可配置
                            if(!this.dataValue || this.dataValue.length==0){//空数据
                                this.dataValue="";
                            }else if(Array.isArray(this.dataValue)){
                                this.dataValue=this.dataValue.join(",")
                            }
                            this.arrDatasCopy=JSON.parse(JSON.stringify(this.arrDatas));
                            this.arrDatas=this.initTreeData(this.arrDatas,paramSetting);
                            this.showSelectTree=true;
                        }

                    }
                })
            },
            //初始化岗位树下拉框
            initPosTree(){
                let param={};
                this.arrDatas=[];
                this.showSelectTree=false;
                this.$set(param,"orgDim",this.orgDim);
                if(this.orgLevel){
                    this.$set(param,"orgLevel",this.orgLevel);
                }
                let userDept = this.CACHE_GLOBAL.getLoginDept();
                if(userDept && userDept.id){
                    this.$set(param,"id",userDept.id);
                }
                if(userDept && userDept.orgParentId){
                    this.$set(param,"orgParentId",userDept.orgParentId);
                }
                this.axios.post(this.api.sysOrg.findOrgTree,param).then(res=>{
                    this.initDataValue();
                    if(res.data&&res.data.operateObj){
                        let orgArr=res.data.operateObj;
                        let posArr=[];
                        this.axios.post(this.api.sysPos.findNoPage,{"orgDim":this.orgDim}).then(posres=>{
                            posArr=posres.data;
                            let result="";
                            posArr.forEach(item=>{
                                if(this.saveType == "text"){
                                    if(!this.multiple && item.posName == this.dataValue){//单选
                                        result +=","+ item.id;
                                    }else if(this.multiple){ //多选
                                        if(this.dataValue.includes(",")){//多数据--字符串
                                            ( this.dataValue.split(",") || []).forEach(mulItem => {
                                                if(mulItem == item.posName){
                                                    result +=","+item.id;
                                                }
                                            })
                                        }else if(Array.isArray(this.dataValue)){//多数据--数组
                                            ( this.dataValue || []).forEach(mulItem => {
                                                if(mulItem == item.posName){
                                                    result +=","+item.id;
                                                }
                                            })
                                        } else if(this.dataValue == item.posName){//单数据
                                            result =","+item.id;
                                        }
                                    }
                                }else if(this.saveType == "dataId"){
                                    if(!this.multiple && item.id == this.dataValue){//单选
                                        result +=","+ item.posName;
                                    }else if(this.multiple){ //多选
                                        if(this.dataValue.includes(",")){//多数据--字符串
                                            ( this.dataValue.split(",") || []).forEach(mulItem => {
                                                if(mulItem == item.id){
                                                    result +=","+item.posName;
                                                }
                                            })
                                        }else if(Array.isArray(this.dataValue)){//多数据--数组
                                            ( this.dataValue || []).forEach(mulItem => {
                                                if(mulItem == item.id){
                                                    result +=","+item.posName;
                                                }
                                            })
                                        } else if(this.dataValue == item.id){//单数据
                                            result =","+item.posName;
                                        }
                                    }
                                }
                            })
                            if(this.saveType == "text"){//文本格式的赋值
                                this.dataValueUser=this.dataValue;
                                this.dataValue=result.substring(1);
                            }
                            if(this.saveType == "dataId"){//关联标识的赋值
                                this.dataValueUser=result.substring(1);
                            }
                            if(this.backfillField){//回调初始化赋值
                                this.$set(this.formData, this.backfillField, this.dataValueUser);
                            }
                            if(this.openTree){
                                let paramSetting={};
                                paramSetting["id"] = "id";
                                paramSetting["pId"] = "orgParentId";
                                paramSetting["children"] = "children"; // 设置children可配置
                                if(!this.dataValue || this.dataValue.length==0){//空数据
                                    this.dataValue="";
                                }else if(Array.isArray(this.dataValue)){
                                    this.dataValue=this.dataValue.join(",")
                                }
                                orgArr=this.initTreeData(orgArr,paramSetting);
                                this.dealData(orgArr,posArr);
                                this.arrDatas=orgArr;
                                this.showSelectTree=true;
                            }
                        })
                    }
                })
            },
            /*
              递归处理岗位数据
           */
            dealData(arr,posArr){
                if(Array.isArray(arr)){
                    arr.forEach(item =>{
                        if(item.children){//有下级
                            (posArr || []).forEach(pos => {
                                if(pos.orgId == item.id){
                                    pos.orgName =pos.posName;
                                    item.children.unshift(pos);
                                }
                            })
                            this.dealData(item.children,posArr);
                        }else{//无下级
                            (posArr || []).forEach(pos => {
                                if(pos.orgId == item.id){
                                    pos.orgName =pos.posName;
                                    if(item.children){
                                        item.children.unshift(pos);
                                    }else{
                                        item.children=[];
                                        item.children.push(pos)
                                    }
                                }
                            })
                            return ;
                        }
                    })
                }
            },
            //初始化用户树下拉框
            initUserTree(){
                this.axios.post(this.api.plFormParam.find, {'paramKey': 'userTreeDim'}).then(paramRes => {
                    this.initDataValue();
                    let currentDim = ((paramRes.data || [])[0] || {}).paramVal || "";
                    try{
                        if(typeof this.dataValue=='string' && this.dataValue.includes("[")){
                            this.dataValue=JSON.parse(this.dataValue);
                        }
                    }catch (e) {
                        console.log(e)
                    }
                    let userObj = {};
                    if(this.userData){
                        let arr=this.userData || [];
                        let result="";
                        arr.forEach(item=>{
                            if(userObj[item.userId]){
                                return;
                            }
                            if(currentDim){
                                if(currentDim == item.orgDim){
                                    userObj[item.userId] = true;
                                }else{
                                    return;
                                }
                            }else{
                                userObj[item.userId] = true;
                            }
                            this.userOrgObj[item.userId] = item.orgName;
                            this.userIdObj[item.userId] = item.userName;
                            if(this.saveType == "text"){
                                if(this.value){
                                    result=","+this.value;
                                }
                                this.arrDatasCopy.push({"id":item.userId,"userId":item.userId,"dataId":item.userName,"dataName":item.userName});
                            }else if(this.saveType == "dataId"){
                                this.arrDatasCopy.push({"id":item.userId,"userId":item.userId,"dataId":item.userId,"dataName":item.userName});
                                //当是查看时
                                if(this.showText){
                                    let arr=[];
                                    if(Array.isArray(this.value)){//数组格式
                                        arr=this.value;
                                    }else{
                                        arr=this.value.split(",");
                                    }
                                    arr.forEach(posItem => {
                                        if(posItem == item.userId && item.userName){
                                            result+=","+item.userName;
                                        }
                                    })
                                }
                            }
                            this.usersNameArr.push(item.userName);
                        })
                        this.dataValueUser=result.substring(1);
                        this.arrDatas=JSON.parse(JSON.stringify(this.arrDatasCopy));
                        this.initBackField();
                        this.showSelect=true;
                    }else{
                        this.CACHE_GLOBAL.getAllPosUser(this.showLockUser).then(res=>{//从缓存中读取用户列表
                            if(res){
                                let arr=res || [];
                                let result="";
                                arr.forEach(item=>{
                                    if(userObj[item.userId]){
                                        return;
                                    }
                                    if(currentDim){
                                        if(currentDim == item.orgDim || (this.showLockUser && item.isLockUser)){
                                            userObj[item.userId] = true;
                                        }else{
                                            return;
                                        }
                                    }else{
                                        userObj[item.userId] = true;
                                    }
                                    this.userOrgObj[item.userId] = item.orgName;
                                    this.userIdObj[item.userId] = item.userName;
                                    if(this.saveType == "text"){
                                        if(this.value){
                                            result=","+this.value;
                                        }
                                        this.arrDatasCopy.push({"id":item.userId,"userId":item.userId,"dataId":item.userName,"dataName":item.userName});
                                    }else if(this.saveType == "dataId"){
                                        this.arrDatasCopy.push({"id":item.userId,"userId":item.userId,"dataId":item.userId,"dataName":item.userName});
                                        //当是查看时
                                        if(this.showText){
                                            let arr=[];
                                            try {
                                                this.value=JSON.parse(this.value);
                                            }catch (e) {

                                            }

                                            if(Array.isArray(this.value)){//数组格式
                                                arr=this.value;
                                            }else{
                                                arr=this.value.split(",");
                                            }
                                            arr.forEach(posItem => {
                                                if(posItem == item.userId && item.userName){
                                                    result+=","+item.userName;
                                                }
                                            })
                                        }
                                    }
                                    this.usersNameArr.push(item.userName);
                                })

                                this.dataValueUser=(result || "").substring(1);
                                this.arrDatas=JSON.parse(JSON.stringify(this.arrDatasCopy));
                                this.initBackField();
                                this.showSelect=true;
                            }
                        })
                    }
                })
            },

            changeUserBlur(value){
                // this.$nextTick(() => {
                //     this.arrDatas=JSON.parse(JSON.stringify( this.arrDatasCopy));
                // })
            },

            //用户名搜索
            changeUser(value){
                if(this.$refs.userTreeRef.$refs.input){ // 处理多选时ELEMENTUI底层无法触发blur事件的问题
                    this.$refs.userTreeRef.$refs.input.blur = () => {
                        this.arrDatas=JSON.parse(JSON.stringify( this.arrDatasCopy));
                    }
                }

                if(value){
                    if (/[^\x00-\xff]/g.test(value)) {
                        //输入汉字
                        this.arrDatas = this.arrDatasCopy.filter(item => {//下拉框赋值
                            if(item.dataName.includes(value)){
                                return item;
                            }
                        });
                    } else {//拼音
                        let str = this.usersNameArr.join(",");
                        let arr = PinyinMatch.match(str, value);
                        let content = str.substring(arr[0], arr[1] + 1);
                        let contentArr = [];
                        while(content){
                            contentArr.push(content);
                            str = str.substring(arr[1] + 1);
                            arr = PinyinMatch.match(str, value);
                            content = str.substring(arr[0], arr[1] + 1);
                        }
                        if(contentArr.length > 0){
                            this.arrDatas = this.arrDatasCopy.filter(item => {//下拉框赋值
                                let flag = false;
                                for(let contentData of contentArr){
                                    if(item.dataName.includes(contentData)){
                                        flag = true;
                                        break;
                                    }
                                }
                                return flag;
                            });
                        }
                    }
                }else{//为空，赋值所有
                    this.arrDatas=JSON.parse(JSON.stringify( this.arrDatasCopy));
                }
            },
            /*
                处理树数据 输入正常数组，返回树格式数据
             */
            initTreeData(resData,paramSetting){
                let vm =this;
                if(!paramSetting){
                    paramSetting["id"] = "id";
                    paramSetting["pId"] = "parentId";
                    paramSetting["children"] = "children"; // 设置children可配置
                }

                return vm.COMMON_FUNC.buildElTree(resData,paramSetting);
            },
            /*
             树回调
             */
            changeData(label,val){
                this.dataValue = val;
                if(this.saveType == "text"){
                    this.changeField(this.field,label);
                    this.$set(this.formData, this.backfillField, label);
                }else{
                    this.changeField(this.field,val);
                    this.$set(this.formData, this.backfillField, label);
                }

            },
            /**
             * 远程连接树数据回调
             */
            changeDataTree(label,val){
                this.dataValue = label;
                this.changeField(this.field,val);
            },
            onEyeChange() {
                this.onSelectChange && this.onSelectChange(this.field);
            }
        }
    }
</script>

<style lang="scss">
</style>
