<template>
    <div>
        <span v-if="isShowSpan">
          <div v-if="showText" style="min-height: 36px;">
              {{valueLabel}}
              <pl-eye-image v-if="showSee" :field="fieldId" :onEyeChange="onEyeChange"></pl-eye-image>
          </div>
          <el-cascader v-else v-model="formData[fieldId]" :options="cascadeDataArr" :props="{value: 'id'}"
                       clearable style="width: 100%;" :popper-class="skinType === 'dark' ? 'listview-dark' : ''"
                       filterable :placeholder="placeholder || '请选择'">
          </el-cascader>
        </span>
        <span v-else>
          <el-cascader v-model="formData[fieldId]" :options="dataTreeArr" :props="optionProps" filterable
                       :placeholder="placeholder || '请选择'" :popper-class="skinType === 'dark' ? 'listview-dark' : ''"
                       clearable style="width: 100%;" v-if="isShow && !showText"  @change="changeValue">
          </el-cascader>
          <div v-if="showText" style="min-height: 36px;">
              {{valueLabel}}
             <pl-eye-image v-if="showSee" :field="fieldId" :onEyeChange="onEyeChange"></pl-eye-image>
          </div>
        </span>
    </div>
</template>

<script>

    export default {
        name: "pl-cascade-single",
        props:{
            dataTypeId:{type:String,default:""},
            parentId:{type:String,default: ""},
            fieldId:{type:String,default:""},
            formData:{type:Object,default:() => {return {};}},
            defaultValue:{type:Array,default:() => {return [];}},
            isMuliti:{type:Boolean,default:false},
            showText:{required: false, default: false, type: Boolean},
            showSee:{required: false, default: false, type: Boolean},
            rememberSysDataObj:{type:Function},
            onEyeChange:{type:Function},
            checkStrictly:{type:Boolean,default:false}, //是否可选任一级
            placeholder:{type:String,default:""},
            optionSetting: {type: Array,default: () => []},
            separator: {type: String, default: "/"},
            skinType: {type: String, default: ""}, //组件皮肤类型
        },
        data(){
            return {
                isShow:false,
                dataTreeArr:[],
                dataTreeArrObj:{},
                defaultProps:{children: 'children', label: 'dataName'}, // 树组件的配置信息
                modelValue: [],
                optionProps: {
                    value: 'id',
                    label: 'label',
                    children: 'children',
                    multiple:this.isMuliti,
                    checkStrictly:this.checkStrictly
                },
                valueLabel:"",
                isShowSpan:false,
                cascadeData: [{
                    id: 'firstOption',
                    label: '选项1',
                    children: [{
                        id: 'firstGroupOne',
                        label: '选项1-1',
                    }, {
                        id: 'firstGroupTwo',
                        label: '选项1-2',
                    }]
                }, {
                    id: 'secondOption',
                    label: '选项2',
                    children: [{
                        id: 'secondGroupOne',
                        label: '选项2-1'
                    }, {
                        id: 'secondGroupTwo',
                        label: '选项2-2'
                    }, {
                        id: 'secondGroupThird',
                        label: '选项2-3'
                    }]
                }],
                cascadeDataArr: [],
            }
        },

        watch:{
            dataTypeId(){
                this.isShowSpan = !this.dataTypeId
                this.initData();
            },
            parentId(){
                this.initData();
            },
            defaultValue(){
                this.isShow = false;
                if(!this.formData[this.fieldId]){
                    this.$set(this.formData,this.fieldId,this.defaultValue || []);
                }
                this.$nextTick(() => {
                    this.isShow = true;
                });
            },
            formData: {
              deep: true,
              handler() {
                  if(this.showText){
                      this.initData();
                  }
              }
            }
        },

        created(){
            this.isShowSpan = !this.dataTypeId;
            this.initData();
        },

        methods:{
            initData(){
                if (this.isShowSpan) {
                    if (!this.showText && this.optionSetting.length > 0) {
                        this.cascadeDataArr = this.optionSetting;
                        let diyValue;
                        if (typeof this.formData[this.fieldId] === "string") {
                            diyValue = (this.formData[this.fieldId] || "").split(",").filter(diyId => diyId);
                        } else {
                            diyValue = this.formData[this.fieldId] || [];
                        }
                        this.$set(this.formData, this.fieldId, diyValue);
                    } else {
                        this.cascadeDataArr = this.cascadeData;
                    }
                    if (this.showText) {
                        let diyValue = (this.formData[this.fieldId] || "").split(",");
                        let currOption = this.optionSetting;
                        diyValue.forEach(diyId => {
                            let obj = currOption.find(item => item.id === diyId) || {};
                            this.modelValue.push(obj.label || "");
                            currOption = obj.children || [];
                        });
                        this.valueLabel = this.modelValue.filter(key => key).join(this.separator);
                        // console.log(this.modelValue,'formData[fieldId]',this.optionSetting);
                    }
                    return;
                }
                if(!this.showText){
                    this.isShow = false;
                    /*this.DATA_GLOBAL.getDatas(this.dataTypeId).then(datas => {
                        let arr = [];
                        datas.forEach(item => {
                            item.label = item.dataName;
                            if(this.parentId && item.parentId != this.parentId){
                                arr.push(item);
                            }else{
                                arr.push(item);
                            }
                        });
                        let paramSetting = {};
                        paramSetting["id"] = "id";
                        paramSetting["pId"] = "parentId";
                        paramSetting["children"] = this.defaultProps["children"]; // 设置children可配置
                        this.dataTreeArr = this.COMMON_FUNC.buildElTree(arr,paramSetting);
                        console.log(this.dataTreeArr);
                        this.isShow = true;
                    });*/
                    this.spcpFormAxios.post(this.api.mixDataTool.getDataTree,{typeId:this.dataTypeId,parentId:this.parentId}).then(res => {
                        if(res.data){
                            this.dataTreeArr = res.data || [];
                            this.dataTreeArr.forEach(item => {
                                this.$set(this.dataTreeArrObj,item.id,item.label);
                            })
                        }

                        let value = this.formData[this.fieldId];
                        let result={}
                        if(value && value.indexOf(";") > -1){//级联框有多个下级并且多选数量大于1的情况会有分号
                            let valueArr = [];
                            let idArr=[];
                            (value.split(";") || []).forEach(item => {
                                let  arr=item.split(",")|| [];
                                valueArr.push(item.split(","));
                                let id ="";
                                arr.forEach( item2 =>{
                                    id=item2;
                                })
                                idArr.push(id);
                            });
                            this.DATA_GLOBAL.getDataByIds(idArr.join(",")).then(idRes =>{
                                idRes.forEach((id,index)=>{
                                    this.$set(result,idArr[index],id);
                                })
                                if(Object.keys(result).length >0){
                                    this.rememberSysDataObj && this.rememberSysDataObj(this.fieldId,result);
                                }
                            })
                            this.$set(this.formData,this.fieldId,valueArr);
                            this.isShow = true;
                        }else {
                            if(value && value.indexOf(",") > -1){//级联没有下级或者有下级但是多选数量为1的时候
                                let valueArr=value.split(",");
                                if(this.dataTreeArr[0].children){//有下级数据
                                    this.$set(this.formData,this.fieldId,value.split(","));
                                    let valLenth=valueArr.length;
                                    this.DATA_GLOBAL.getDataById(valueArr[valLenth-1]).then(valRess =>{
                                        this.$set(result,valueArr[valLenth-1],valRess);
                                        this.rememberSysDataObj && this.rememberSysDataObj(this.fieldId,result);
                                    })
                                }else{//没有下级数据
                                    this.$set(this.formData,this.fieldId,valueArr);
                                    valueArr.forEach(data =>{
                                        this.$set(result,data,this.dataTreeArrObj[data]);
                                    })
                                }
                                this.isShow = true;
                            }else if(value){//级联没有下级 单选的时候
                                this.$set(this.formData,this.fieldId,value);
                                this.$set(result,value,this.dataTreeArrObj[value]);
                                this.isShow = true;
                            }else{//初始化没数据的时候
                                if(this.dataTreeArr[0] && this.dataTreeArr[0].children){//有级联下级数据
                                    this.$set(this.formData,this.fieldId,this.defaultValue.join(","));
                                    let valLenth=this.defaultValue.length;
                                    if(this.defaultValue[valLenth-1]){ // 没有默认值
                                        this.DATA_GLOBAL.getDataById(this.defaultValue[valLenth-1]).then(valRess =>{
                                            this.$set(result,this.defaultValue[valLenth-1],valRess);
                                            this.rememberSysDataObj && this.rememberSysDataObj(this.fieldId,result);
                                            this.isShow = true;
                                        })
                                    }else{
                                        this.isShow = true;
                                    }
                                }else{//没有级联下级数据
                                    this.$set(this.formData,this.fieldId,this.defaultValue || "");
                                    if(this.defaultValue.length>0){
                                        this.$set(result,result,this.dataTreeArrObj[this.defaultValue]);
                                    }
                                    this.isShow = true;
                                }

                            }
                            if(Object.keys(result).length >0){
                                this.rememberSysDataObj && this.rememberSysDataObj(this.fieldId,result);
                            }
                        }
                    });
                }else{
                    if(this.formData[this.fieldId]){
                        let dataIds = "";
                        let length = 0;
                        if (this.formData[this.fieldId].length === 0) {
                          this.valueLabel = dataIds;
                          return;
                        }
                        this.formData[this.fieldId].split(";").forEach(item => {
                            dataIds += "," + item;
                            length = item.split(",").length;
                        });
                        dataIds = dataIds.substring(1);
                        if (dataIds.indexOf("*") !== -1 && length === 1) {
                          this.valueLabel = dataIds;
                        } else if(dataIds.indexOf("*") === -1 && length === 1 && dataIds.length !== 32) {
                          this.valueLabel = dataIds;
                        }else {
                          this.DATA_GLOBAL.getDataByIds(dataIds).then(datas => {
                            if(dataIds.indexOf(",") > -1){
                              let dataCopy = JSON.parse(JSON.stringify(datas));
                              let arr0 = dataCopy.splice(0,length);
                              let arr1 = datas.splice(length,datas.length);
                              this.valueLabel = arr0.join("/");
                              if(arr1.length > 0){
                                this.valueLabel += ";" + arr1.join("/")
                              }
                            }else{
                              this.valueLabel = datas;
                            }
                          });
                        }
                    }
                }
                if(!this.formData[this.fieldId]){
                    this.$set(this.formData,this.fieldId,this.defaultValue || []);
                }

            },
            changeValue(val){
                let value = this.formData[this.fieldId];
                let arr=val || [];
                let result={};
                let idArr=[];
                arr.forEach(item =>{
                    if(item.length === 1){//没有级联下级的时候
                        this.dataTreeArr.findIndex(data =>{
                            if(item == data.id){
                                this.$set(result,data.id,data.label);
                                return;
                            }
                        })
                        this.rememberSysDataObj && this.rememberSysDataObj(this.fieldId,result);
                    }else if(Array.isArray(item)){//有下级级联数据
                        let id ="";
                        item.forEach(item2 => {
                            id=item2;
                        });
                        idArr.push(id);
                    }else{//单选没有下级数据
                        idArr.push(item);
                    }

                })
                if(idArr.length>0){
                    this.DATA_GLOBAL.getDataByIds(idArr.join(",")).then(idRes =>{
                        let idResArr=[];
                        if(typeof idRes == 'string'){
                            idResArr.push(idRes)
                        }else{
                            idResArr=idRes || [];
                        }

                        idResArr.forEach((id,index)=>{
                            this.$set(result,idArr[index],id);
                        })
                        if(Object.keys(result).length >0){
                            this.rememberSysDataObj && this.rememberSysDataObj(this.fieldId,result);
                        }
                    })
                }
            }
        }
    }
</script>

<style scoped>

</style>
