"use strict";
import {base} from './base.js'
import { util } from '../../util/util.js'
class inputText extends base{
    constructor(data) {
        super(data);
        this.type='text';
        this.isEventInput=false;//是否set值时是否手动处发input事件
    }
    //这里解释一下 renderParentID 和 parentObjID
    //renderParentID是在form表单才会用到，主要能找到上级对象是cutChar还是tabs对象
    //parentObjID则会在query和form都会用到，可直接找到上级是query对象还是form对象
    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);
        }
        if(data.kind=='text_detail'){
            that.renderTextDetail(renderParentID);
        }
    }
    hide(){
        if(this.data.kind=='text_detail')return
        document.getElementById(this.objID).setAttribute('style', 'display:none');//隐藏
    }
    show(){
        if(this.data.kind=='text_detail')return
        document.getElementById(this.objID).setAttribute('style', '');//展示
    }
    getValue() {
        let that=this;
        let data=that.data
        if(data.query_type=='1'){
            let start=document.getElementById('start_'+that.eleID).value
            let end=document.getElementById('end_'+that.eleID).value
            start==''&& (start='null')
            end==''&& (end='null')
            return start+','+end;
        }else{
            return document.getElementById(that.eleID).value;
        }
    }
    setValue(value) {
        let that=this;
        if(that.data.kind=='text_detail'){
            document.getElementById(that.eleID).innerHTML = util.toOldChar(value);
        }else{
            document.getElementById(that.eleID).value = util.toOldChar(value);
        }

    }
    initFunc(){
        let that=this;
        that.bindValueValidate= ()=>{
            if(that.data.query_type!=undefined){
                return ;//是query组件就不校验，不绑定事件
            }
            if(!util.isNull(that.data.field_unit)){//有单位，重写提示信息
                that.defaultValidateTextFunc= (obj)=>{
                    that.customValidateTextFunc(obj);
                }
            }
            that.validateFunc= ()=>{
                that.validate();
            }
            util.addEventListener(that.eleID,'blur',that.validateFunc)
        }
        that.bindValueTextMask= ()=>{
            let input=document.getElementById(that.eleID);
            if(that.data.text_mask_type=='1'){
                that.isEventInput=true;
                let textNumberMask=util.toOldChar(that.data.text_mask_number_config);
                vanillaTextMask.maskInput({
                    inputElement: input,
                    mask: textMaskAddons.createNumberMask(util.executeDynamicCode('return '+textNumberMask,{}))
                });
                that.getValue=()=>{//重写getValue
                    return input.value.replace(/[^\d.-]/g, '')
                }
                that.setValue=(value)=>{//重写setValue
                    input.value = util.toOldChar(value);
                    input.dispatchEvent(new Event('input'));
                }
            }

            if(that.data.text_mask_type=='2'){
                that.isEventInput=true;
                let textStringMask=util.toOldChar(that.data.text_mask_string_config);
                vanillaTextMask.maskInput({
                    inputElement: input,
                    mask: util.executeDynamicCode('return '+textStringMask,{})
                });
                that.getValue=()=>{//重写getValue
                    return input.value.replace(/[\D+]/g, '')
                }
                that.setValue=(value)=>{//重写setValue
                    input.value = util.toOldChar(value);
                    input.dispatchEvent(new Event('input'));
                }
            }
        }
        that.bindInputButtonFunc=()=>{
            that.inputButtonFunc()
        }
        that.inputButtonFunc=()=>{//较复杂的代码逻辑请重写此方法
            let myselfFuncStr=util.toOldChar(that.data.input_button_func);
            util.executeDynamicCode(myselfFuncStr,{eleObj:that});
        }
        that.bindInputSpinnerMinusFunc=()=>{
            let inputSpinnerConfig=JSON.parse(that.data.input_spinner_config)
            let value=that.getValue();
            let stepValue=Number(inputSpinnerConfig['stepValue'])
            let maxValue=Number(inputSpinnerConfig['maxValue'])
            let minValue=Number(inputSpinnerConfig['minValue'])
            if(Number.isInteger(stepValue)){
                value=(Number(value)-stepValue)
            }else{
                value=(Number(value)-stepValue).toFixed(2)
            }
            if(value>maxValue){
                that.setValue(maxValue)
                return
            }
            if(value<=minValue){
                that.setValue(minValue)
            }else{
                that.setValue(value)
            }
        }
        that.bindInputSpinnerPlusFunc=()=>{
            let inputSpinnerConfig=JSON.parse(that.data.input_spinner_config)
            let value=that.getValue();
            let stepValue=Number(inputSpinnerConfig['stepValue'])
            let maxValue=Number(inputSpinnerConfig['maxValue'])
            let minValue=Number(inputSpinnerConfig['minValue'])
            if(Number.isInteger(stepValue)){
                value=(Number(value)+stepValue)
            }else{
                value=(Number(value)+stepValue).toFixed(2)
            }
            if(value<minValue){
                that.setValue(minValue)
                return
            }
            if(value>=maxValue){
                that.setValue(maxValue)
            }else{
                that.setValue(value)
            }
        }
    }
    bindFunc(){
        let that=this;
        if(that.data.is_text_mask=='Y'){
            that.bindValueTextMask();
        }
        that.bindValueValidate();//绑定校验函数
        if(that.data.is_show_input_button=='Y'){
            document.getElementById(that.eleID+'_input_button').addEventListener('click',that.bindInputButtonFunc);
        }
        if(that.data.is_input_spinner=='Y'){
            document.getElementById(that.eleID+'_minus').addEventListener('click',that.bindInputSpinnerMinusFunc);
            document.getElementById(that.eleID+'_plus').addEventListener('click',that.bindInputSpinnerPlusFunc);
        }
    }
    renderDefault(renderParentID){
        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 unit=data.field_unit;
        let canNull=data.can_null;
        let isReadOnly=data.is_read_only;
        let queryType=data.query_type;//查询组件属性
        that.initFormCol(that);
        let readOnlyHtml=''
        if (isReadOnly == 'Y') {
            readOnlyHtml=' readonly="readonly" ';
        }
        let unitHtmlTemplate=`
        <div class="input-group-append">
        <span class="input-group-text" style="background-color:#eeeeee">${unit}</span>
        </div>
        `
        let inputTemplateHtml=``;
        if(queryType=='1') {//段查询
            inputTemplateHtml=`
            <div class="input-daterange input-group" id="datepicker-range">
            <input id="start_${that.eleID}" type="text" class="form-control" ${readOnlyHtml} name="start_${eleName}">
            <div class="input-group-prepend">
            <span class="input-group-text">至</span>
            </div>
            <input id="end_${that.eleID}" type="text" class="form-control khc-theme-input-color" ${readOnlyHtml} name="end_${eleName}">
            </div>
            `;
        }else{
            inputTemplateHtml=`
            <input type="text" id="${that.eleID}" value="${!util.isNull(defaultValue)?defaultValue:''}" name="${eleName}" class="form-control khc-theme-input-color" ${readOnlyHtml} placeholder="${placeholder}">
            ${!util.isNull(unit)?unitHtmlTemplate:''}
            `;
        }
        let questionCircleHtml=that.getQuestionCircleIconHtml();
        let layoutType=util.isNull(data.field_layout_type)?'horizontal':data.field_layout_type
        let htmlTemplate=``;
        htmlTemplate=`
        <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="${layoutType=='horizontal'?`line-height:25px;`:'line-height:16px;padding-top: 0px;'} vertical-align: middle;">
        <font id="${that.objID}CanNull" style="font-size: ${layoutType=='horizontal'?'22px;vertical-align: middle;':'15px;'} ${canNull!='Y'?'display:none;':''}" color="red">*</font>
        ${labelName}
        ${questionCircleHtml}
        </label>
        <div class="${layoutType=='horizontal'?`col-sm-${that.inputCol}`:''}">
        ${!util.isNull(unitHtmlTemplate)||data.is_show_input_button=='Y'?'<div class="input-group-append">':''}
        ${inputTemplateHtml}
        ${!util.isNull(data['is_input_spinner'])&&data['is_input_spinner']=='Y'?
            `<span class="input-group-append">
                 <button class="btn btn-default" type="button" id="${that.eleID}_minus"><span class="fas fa-minus"></span></button>
                 <button class="btn btn-default" type="button" id="${that.eleID}_plus"><span class="fas fa-plus"></span></button>
             </span>`:``}
        ${data.is_show_input_button=='Y'?`<span class="input-group-append">
            <button class="btn btn-secondary" type="button" id="${that.eleID}_input_button">${data.input_button_name}</button></span>`:''}
        ${!util.isNull(unitHtmlTemplate)||data.is_show_input_button=='Y'?'</div>':''}
        <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(queryType=='1') {//段查询
            if(!util.isNull(defaultValue)){
                let values = defaultValue.split(',')
                document.getElementById('start_'+that.getEleID()).value=values[0];
                document.getElementById('end_'+that.getEleID()).value=values[1];
            }
        }else{
            if(!util.isNull(defaultValue)){
                document.getElementById(that.getEleID()).value=defaultValue;
            }
        }
        that.bindFunc();
    }

    renderCustom(renderParentID){
        let that=this;
        let data=that.data
        let obj=document.getElementById(renderParentID).querySelector('input[name="' + data.name + '"]');
        if(obj==null){
            let hiddenFieldsDiv=document.getElementById(renderParentID).querySelector('div[name="hiddenFields"]');
            let hiddenHtmlTemplate=`<input type="hidden" name="${data.name}" id="${that.eleID}" value="">`;
            hiddenFieldsDiv.insertAdjacentHTML("beforeEnd", hiddenHtmlTemplate)
        }else{
            obj.setAttribute("id", that.eleID);
            that.bindFunc();
        }


    }
    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 {inputText}