"use strict";
import {base} from './base.js'
import { util } from '../../util/util.js'
import {khcToastr} from "../alert/khcToastr.js";
class inputTag extends base{
    constructor(data) {
        super(data);
        this.type='tag';
    }
    render(renderParentID){
        let that=this;
        that.initFunc();
        let data=that.data
        this.initFunc();
        if(data.kind==undefined||data.kind=='default'){
            that.renderDefault(renderParentID);
        }
        if(data.kind=='custom'){
            that.renderCustom(renderParentID);
        }
        if(data.kind=='text_detail'){
            that.renderTextDetail(renderParentID);
        }
    }
    renderDefault(parentObjID){
        let that=this;
        let data=that.data
        let labelName=data.label_name;
        let eleName=that.data.name;
        let placeholder=data.placeholder;
        let defaultValue=data.default_value;
        let canNull=data.can_null;
        let isReadOnly=data.is_read_only;
        that.initFormCol(that);
        let layoutType=util.isNull(data.field_layout_type)?'horizontal':data.field_layout_type
        let tagHtmlTemplate=`
        <div class="form-group ${layoutType=='horizontal'?'row':''} col-sm-${data.col}"  id="${that.objID}" style="display: none">
        <label class="col-form-label ${layoutType=='horizontal'?`col-sm-${that.labelCol}`:''} text-sm-right" style="line-height:25px;vertical-align: middle;">
        <font id="${that.objID}CanNull" style="font-size: 22px;vertical-align: middle;${canNull!='Y'?'display:none;':''}" color="red">*</font>
        ${labelName}
        ${data.is_question_circle=='Y'?`<i class="far fa-question-circle" style="font-size: 15px;cursor:pointer;" data-toggle="tooltip" data-placement="top" title="" data-original-title="${data.question_circle_text}"></i>`:''}
        </label>
        <div class="${layoutType=='horizontal'?`col-sm-${that.inputCol}`:''}">
        <div class="bootstrap-tagsinput khc-theme-input-color" id="${that.eleID}tagsinput" ${isReadOnly=='Y'?'style="background-color:#f1f1f2"':''}>
        <div style="position:absolute;width:0;height:0;z-index:-100;opacity:0;overflow:hidden;">
        <div class="bootstrap-tagsinput-input" style="position:absolute;z-index:-101;top:-9999px;opacity:0;white-space:nowrap;">
        </div></div>
        <div id="${that.eleID}showTagValue"></div>
        <input type="text" id="${that.eleID}addTagInput" placeholder="" style="width: 24px;" size="1" ${isReadOnly=='Y'?'readonly="readonly"':''}>
        </div>
        <input type="text" id="${that.eleID}" style="display:none;" value="${!util.isNull(defaultValue)?defaultValue:''}" name="${eleName}" 
        class="form-control" ${isReadOnly=='Y'?'readonly="readonly"':''} placeholder="${placeholder}">
        <small class="form-text text-muted"><font style="display:none;"  validate="validate"  color="red">12412345123</font></small>
        </div></div>
        `;
        document.getElementById(parentObjID).insertAdjacentHTML("beforeEnd",tagHtmlTemplate);
        if(!util.isNull(defaultValue)){
            document.getElementById(that.getEleID()).value=defaultValue;
        }
        util.addEventListener(that.eleID+'addTagInput','input',()=>{
            let tagEleObj=document.getElementById(that.eleID+'addTagInput')
            let width=24;
            if(tagEleObj.value.length!=0){
                width=25+(tagEleObj.value.length*14);
                // 回车事件
                util.addEventListener(document.body,'keyup',that.keyupFunc)
                util.addEventListener(that.eleID+'addTagInput','blur',that.addTagInputBlurFunc)
            }
            tagEleObj.style.width=width+'px';
        })
        util.addEventListener(that.eleID+'tagsinput','click',that.tagsinputClickFunc)
    }
    initFunc(){
        let that=this;
        that.keyupFunc= (e)=>{
            if(e.keyCode==13){
                that.setAddTagValue();
            }
        }
        that.addTagInputBlurFunc= ()=>{//失去焦点
            that.setAddTagValue();
            util.removeEventListener(document.body,'keyup',that.keyupFunc)//失去焦点后就移除回车事件
        }
        that.tagsinputClickFunc= ()=>{//最外层的div点击时，将焦点放到addTagInput
            document.getElementById(that.eleID+'addTagInput').focus();
        }
    }
    setAddTagValue(){
        let that=this;
        let oldValue=that.getValue();
        let addTagInput=document.getElementById(that.eleID+'addTagInput');
        let addTagValue=addTagInput.value
        if(addTagValue==''){
            return ;
        }else if(addTagValue.indexOf(",")!=-1){
            khcToastr.showErrorMessage('tag标签禁止使用逗号  “,”')
            return ;
        }
        if(oldValue==''){
            that.setValue(','+addTagValue+',');
        }else{
            let checkValues = oldValue.split(',')
            let isNewValue=true;
            for (let i = 0; i < checkValues.length; i++) {
                if(checkValues[i]==addTagValue){
                    isNewValue=false;
                }
            }
            if(isNewValue){
                checkValues.push(addTagValue)
            }
            let newValue='';
            for (let i = 0; i < checkValues.length; i++) {
                if(checkValues[i]=='')continue;
                newValue+=checkValues[i]+",";
            }
            newValue=','+newValue;//前后都保留逗号，可做模糊查询
            that.setValue(newValue);
            console.log(that.getValue());
        }
        addTagInput.value=''//置空
    }
    setValue(value) {
        let that=this;
        let htmlTemplate=``;
        let eleObj = document.getElementById(that.getEleID());
        that.tagUuidMap=new Map();
        eleObj.value=value;
        let data=that.data
        let isReadOnly=data.is_read_only;
        if(value!=''){
            let array = value.split(',')
            for (let i = 0; i < array.length; i++) {
                if(array[i]=='')continue;
                let uuid=util.getUUID();
                that.tagUuidMap.set(array[i],uuid);
                if(that.data.kind=='text_detail'){
                    htmlTemplate+=`
                <span class="tag label label-info">${array[i]}</span>`;
                }else{
                    htmlTemplate+=`
                <span class="tag label label-info">${array[i]}
                <span id="${uuid}" data-role="remove" ${isReadOnly=='Y'?'style="display:none"':''}></span>
                </span>
                `;
                }

            }
        }
        if(that.data.kind=='text_detail'){
            htmlTemplate=`<div class="bootstrap-tagsinput" style="border: 0px solid rgba(24, 28, 33, 0.1);background-color: transparent ;">${htmlTemplate}</div>`
            document.getElementById(that.eleID).innerHTML = htmlTemplate;
        }else{
            let eleObjShowTagValue = document.getElementById(that.getEleID()+'showTagValue');
            eleObjShowTagValue.innerHTML=htmlTemplate;//渲染
            if(value!=''){//渲染后绑定删除事件
                let array = value.split(',')
                for (let i = 0; i < array.length; i++) {
                    if(array[i]=='')continue;
                    let uuid=that.tagUuidMap.get(array[i]);
                    util.addEventListener(uuid,'click',()=>{
                        that.tagUuidMap.delete(array[i])
                        let newValue='';
                        that.tagUuidMap.forEach(async  (obj, key) =>{
                            newValue+=key+',';
                        })
                        if(newValue.length>0){
                            newValue=','+newValue;//前后都保留逗号，可做模糊查询
                        }
                        that.setValue(newValue);//刷新
                    })
                }
            }
        }


    }
    hide(){
        document.getElementById(this.objID).setAttribute('style', 'display:none');//隐藏
    }
    show(){
        if(this.data.kind=='text_detail')return
        document.getElementById(this.objID).setAttribute('style', '');//展示
    }
    renderCustom(parentObjID){
        let data=this.data
        let obj=document.getElementById(parentObjID).querySelector('input[name="' + data.name + '"]');
        //console.log('show my layout name：'+data.name+"   value："+obj.value+"    eleID："+this.eleID)
        obj.setAttribute("id", this.eleID);
    }
    renderTextDetail(renderParentID){
        let that=this;
        let data=that.data
        let html=`<tr>
                                <th>${data.label_name}</th>
                                <td name="${data.name}" id="${that.eleID}"></td>
                            </tr>`
        document.getElementById(renderParentID).insertAdjacentHTML("beforeEnd",html);
    }
    
}
export {inputTag}