"use strict";
import {base} from './base.js'
import { util } from '../../util/util.js'
import {fullMap} from "../../fullMap.js";
import {khcToastr} from "../alert/khcToastr.js";

class inputMultiPicker extends base {
    constructor(data) {
        super(data);
        this.type='multiPicker';//级联选择
    }
    render(renderParentID) {
        let that=this;
        that.initFunc();
        let data=that.data
        if(data.kind==undefined||data.kind=='default'){
            that.renderDefault(renderParentID);
        }
        if(data.kind=='custom'){
            that.renderCustom(renderParentID);
        }
    }
    hide(){
        document.getElementById(this.objID).setAttribute('style', 'display:none');//隐藏
    }
    show(){
        document.getElementById(this.objID).setAttribute('style', '');//展示
    }

    renderDefault(renderParentID){
        let that=this;
        let data = that.data
        let eleName=that.data.name;
        let defaultValue=data.default_value;
        let canNull=data.can_null;
        let labelName=data.label_name;
        that.initFormCol(that);
        let dict=that.data.dict_code.data;
        let levelArray=[]
        that.dictMap=new Map();
        if(util.isNull(dict))khcToastr.showErrorMessage(labelName+' 配置的字典异常');
        dict.some(function(item) {
            levelArray.push(Number(item.level));
            that.dictMap.set(String(item.id),item.name)
        })
        let unique=(arr)=>[...new Set(arr)]
        let filterLevel=[0]//过滤的level
        levelArray = levelArray.filter(item => !filterLevel.includes(item))
        let allLevelArray=unique(levelArray);//去重
        that.showSelectNumber=allLevelArray.length;//展示多少个选择器
        that.mixLevel=Math.min(...allLevelArray);//获取最小层级
        let newTree=that.getTree(dict,null,that.mixLevel);//获取第一层数据
        //如果是5个级联col则设2 如果是1,2,3,4,6其中一个级联都使用 12除即可
        let col=(that.showSelectNumber==5)? 2 : 12/that.showSelectNumber;
        let firstSelectHtml='<option value="">请选择</option>';
        for (let i = 0; i < newTree.length; i++) {
            firstSelectHtml+=`<option value="${newTree[i].id}">${newTree[i].name}</option>`;
        }
        let multiPickerDivHtml=``;
        for (let i = 0; i < that.showSelectNumber; i++) {
            multiPickerDivHtml+=`<div class="col-md-${col}" style="margin-bottom: 10px;">
                                <select class="custom-select" level="${i+1}" id="${that.eleID}${i+1}" ${i>0||data.is_read_only=='Y'?'disabled':''}>${i==0?`${firstSelectHtml}`:''}</select>
                            </div>`;
        }
        let questionCircleHtml=that.getQuestionCircleIconHtml();
        let htmlTemplate=`
        <div class="form-group row col-sm-${data.col}" id="${that.objID}" style="display: none">
        <label class="col-form-label col-sm-${that.labelCol} text-sm-right" style="line-height:30px;vertical-align: middle;">
        <font id="${that.objID}CanNull" style="font-size: 22px;vertical-align: middle;${canNull!='Y'?'display:none;':''}" color="red">*</font>
        ${labelName}
        ${questionCircleHtml}
        </label>
        <div class="form-group row  col-sm-${that.inputCol}" id="${that.eleID}multiPickerDiv">
        <input type="hidden" class="form-control" id="${that.eleID}">
        ${multiPickerDivHtml}
        <small class="form-text text-muted"><font style="display:none;"  validate="validate"  color="red">12412345123</font></small>
        </div>
        </div>
        `;
        document.getElementById(renderParentID).insertAdjacentHTML("beforeEnd", htmlTemplate);
        if(!util.isNull(defaultValue)){
            document.getElementById(that.getEleID()).value=defaultValue;
        }
        //所有select绑定事件
        for (let i = 0; i < that.showSelectNumber; i++) {
            let nextLevel=i+1;
            document.getElementById(that.eleID+nextLevel).addEventListener('change',that.onChangeFunc)
        }
    }
    initFunc(){
        let that=this;
        that.onChangeFunc=function (){
            that.updateAllSelectValueToFiled.apply(this);
            that.updateLastSelectKeyToFiled.apply(this);
            let thisLevel=Number(this.getAttribute('level'))
            if(thisLevel==that.showSelectNumber)return ;
            if(this.value.length>0){
                let newTree=that.getTree(that.data.dict_code.data,this.value);
                if(newTree.length==0){
                    for (let i = thisLevel; i < that.showSelectNumber; i++) {
                        document.getElementById(that.eleID+(i+1)).disabled=true;
                        document.getElementById(that.eleID+(i+1)).innerHTML='';
                    }
                    return
                }
                for (let i = thisLevel; i < that.showSelectNumber; i++) {
                    let nextLevel=i+1;
                    document.getElementById(that.eleID+nextLevel).disabled=false;
                    document.getElementById(that.eleID+nextLevel).innerHTML='';
                    //如果选择一级时，也把三级选的内容清空，同理选择二级时，把四级内容清空
                    if(nextLevel!=that.showSelectNumber)document.getElementById(that.eleID+(nextLevel+1)).innerHTML='';
                    //当一级联动选中某个值时三级以上级联动以上的状态为只读，同理二级联动时，则四级以上联动只读
                    if(i>thisLevel)document.getElementById(that.eleID+nextLevel).disabled=true;
                }
                let nextSelectHtml='<option value="">请选择</option>';
                for (let i = 0; i < newTree.length; i++) {
                    nextSelectHtml+=`<option value="${newTree[i].id}">${newTree[i].name}</option>`;
                }
                document.getElementById(that.eleID+(thisLevel+1)).insertAdjacentHTML("beforeEnd", nextSelectHtml);
            }else{
                //当一级联动为(请选择)时二级联动以上的状态为只读
                for (let i = thisLevel; i < that.showSelectNumber; i++) {
                    document.getElementById(that.eleID+(i+1)).disabled=true;
                    document.getElementById(that.eleID+(i+1)).innerHTML='';
                }
            }
        }
        that.updateAllSelectValueToFiled=function (){//将多级联动所有选中的值使用字典转换后拼接set到其他字段
            let thisLevel=Number(this.getAttribute('level'))
            document.getElementById(that.eleID).value='';
            let keyArray=[];
            let strValue='';
            if(that.mixLevel==thisLevel){
                if(this.value.length>0){
                    keyArray.push(this.value);
                    document.getElementById(that.eleID).value=keyArray;
                    strValue=that.dictMap.get(this.value)
                }
            }else{
                for (let i = (that.mixLevel-1); i < thisLevel; i++) {
                    let key=document.getElementById(that.eleID+(i+1)).value;
                    if(util.isNull(key)){
                        break;
                    }
                    keyArray.push(key);
                    strValue+=that.dictMap.get(key)
                }
                document.getElementById(that.eleID).value=keyArray;
            }
            let allValueSetField=that.data.mutli_picker_all_select_value_to_filed;
            if(!util.isNull(allValueSetField)){//set值到其他字段存储
                let fieldArray = allValueSetField.split(',')
                let formObj=fullMap.getObj(that.data.parentObjID)
                let eleMap=formObj.getFormMap();
                for (let i = 0; i < fieldArray.length; i++) {
                    eleMap.get(fieldArray[i]).setValue(strValue);
                }
            }
        }
        that.updateLastSelectKeyToFiled=function (){//将最后一个选中的值set到其他字段
            let thisLevel=Number(this.getAttribute('level'))
            let key='';
            if(this.value.length>0){
                key=this.value;
            }else if(that.mixLevel!=thisLevel){
                let parentSelectObj=document.getElementById(that.eleID+(Number(thisLevel)-1));
                key=parentSelectObj.value;
            }
            let lastKeySetField=that.data.mutli_picker_last_select_key_to_filed;
            if(!util.isNull(lastKeySetField)){//set值到其他字段存储
                let fieldArray = lastKeySetField.split(',')
                let formObj=fullMap.getObj(that.data.parentObjID)
                let eleMap=formObj.getFormMap();
                for (let i = 0; i < fieldArray.length; i++) {
                    eleMap.get(fieldArray[i]).setValue(key);
                }
            }
        }
    }
    getTree(dict,pid,level){
        let newTree=[];
        dict.some(function(item) {
            if (pid!=undefined&&pid!=null&&item.pId == pid) {
                newTree.push(item);
            }
            if (level!=undefined&&level!=null&&item.level == level) {
                newTree.push(item);
            }
        })
        return newTree;
    }
    setValue(value) {
        let that=this;
        document.getElementById(that.eleID).value = util.toOldChar(value);
        let arr = value.split(',')
        if(util.isNull(value)){
            //传入空时，除一级都设置为只读
            for (let i = 1; i < that.showSelectNumber; i++) {
                document.getElementById(that.eleID+(i+1)).disabled=true;
                document.getElementById(that.eleID+(i+1)).innerHTML='';
            }
        }else{
            let pId='';
            for (let i = 0; i < arr.length; i++) {
                let newTree;//获取第一层数据
                if(i==0){
                    newTree=that.getTree(that.data.dict_code.data,null,that.mixLevel);//获取第一层数据
                    pId=newTree[0].id;
                }else{
                    newTree=that.getTree(that.data.dict_code.data,pId);//获取第一层数据
                }
                let selectHtml='<option value="">请选择</option>';
                for (let j = 0; j < newTree.length; j++) {
                    if(newTree[j].id==arr[i]){
                        pId=newTree[j].id;
                    }
                    selectHtml+=`<option value="${newTree[j].id}" ${newTree[j].id==arr[i]?'selected':''}>${newTree[j].name}</option>`;
                }
                if(that.data.is_read_only!='Y')document.getElementById(that.eleID+(i+1)).disabled=false;
                document.getElementById(that.eleID+(i+1)).innerHTML='';
                document.getElementById(that.eleID+(i+1)).insertAdjacentHTML("beforeEnd", selectHtml);
            }
        }
    }
}
export { inputMultiPicker }
