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

class inputSelectSearch extends base {
    constructor(data) {
        super(data);
        this.type='selectSearch';
    }
    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', '');//展示
    }
    //value自定义value转换showValue，可以为空
    getShowValue(value='') {//获取展示的值，主要是将用到字典的值转换
        let that=this;
        if(util.isNull(value)){
            value=that.getValue();
        }
        if(util.isNull(value)){
            return '';
        }
        return that.dictMap.get(value);
    }

    renderDefault(renderParentID){
        let that=this;
        let data = that.data
        let dictDataArray=that.data.dict_code.data;
        if(util.isNull(dictDataArray)){
            if(util.isNull(that.data.dict_code_json)){
                dictDataArray=[];
            }else{
                try {
                    if (typeof that.data.dict_code_json == 'string') {
                        dictDataArray=JSON.parse(that.data.dict_code_json)
                        dictDataArray.length;
                    }else{
                        dictDataArray=that.data.dict_code_json
                    }
                } catch (error) {
                }
            }
        }
        for(let i=0;i<dictDataArray.length;i++){
            that.dictMap.set(dictDataArray[i].key.toString(),dictDataArray[i].value);
        }
        let eleName=that.data.name;
        let defaultValue=data.default_value;
        let canNull=data.can_null;
        let labelName=data.label_name;
        let isReadOnly=data.is_read_only;
        that.initFormCol(that);
        let selectHtmlTemplate=``;
        for(let i=0;i<dictDataArray.length;i++){
            selectHtmlTemplate += ' <option value="'+dictDataArray[i].key+'">'+dictDataArray[i].value+'</option>';
        }
        let questionCircleHtml=that.getQuestionCircleIconHtml();
        let layoutType=util.isNull(data.field_layout_type)?'horizontal':data.field_layout_type
        let 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="line-height:25px;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}`:''}">
        <div class="input-group-append">
            <div style="width: 100%">
                <select class="select2-demo form-control" style="width: 100%" data-allow-clear="true" id="${that.eleID}" name="${eleName}" ${isReadOnly=='Y'?'disabled':''} >
                    <option value="">请选择</option>
                    ${selectHtmlTemplate}
                </select>
                ${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>`:''}
            </div>
        </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);
        $('#'+that.eleID).each(function() {
            $(this)
                .wrap('<div class="position-relative"></div>')
                .select2({
                    placeholder: '请选择',
                    dropdownParent: $(this).parent()
                });
        })
        if(!util.isNull(defaultValue)){
            document.getElementById(that.getEleID()).value=defaultValue;
        }
        // 首先确保select2初始化完成
        $('#'+that.eleID).on('select2:select', function (e) {
            // 获取被选中的选项的数据
            let data = e.params.data;
            // 执行你需要的操作
            //console.log('选中的数据:', data);
            if(that.data.query_type!=undefined){
                return ;//是query组件就不校验
            }
            that.validateFunc()
        });
        that.bindFunc();
    }
    setValue(value) {//重写setValue  set后需要change一下
        if(this.isValue){
            document.getElementById(this.eleID).value = util.toOldChar(value);
            $('#'+this.eleID).trigger("change")
        }
    }
    initFunc(){
        let that=this;
        that.bindValueValidate= ()=>{
            if(that.data.query_type!=undefined){
                return ;//是query组件就不校验，不绑定事件
            }
            that.validateFunc= ()=>{
                that.validate();
            }
            util.addEventListener(that.eleID,'change',that.validateFunc)
        }
        that.bindInputButtonFunc=()=>{
            that.inputButtonFunc();
        }
        that.inputButtonFunc=()=>{//较复杂的代码逻辑请重写此方法
            let myselfFuncStr=util.toOldChar(that.data.input_button_func);
            util.executeDynamicCode(myselfFuncStr,{eleObj:that});
        }
    }
    bindFunc(){
        let that=this;
        that.bindValueValidate();//绑定校验函数
        if(that.data.is_show_input_button=='Y'){
            document.getElementById(that.eleID+'_input_button').addEventListener('click',that.bindInputButtonFunc);
        }
    }

    /**
     * set可选的值，默认全部都可选
     */
    setOptionalValue(str){
        if(!util.isNull(str)){
            let that=this;
            let selectHtmlDefaultTemplate=`<option value="">请选择</option>`
            let selectHtmlTemplate=``;
            let dictDataArray=that.data.dict_code.data;
            that.data.dict_code.optional_value=str;
            for(let i=0;i<dictDataArray.length;i++){
                if(str.indexOf(dictDataArray[i].key)==-1){
                    continue;
                }
                selectHtmlTemplate += ' <option value="'+dictDataArray[i].key+'">'+dictDataArray[i].value+'</option>';
            }
            if(!util.isNull(selectHtmlTemplate)){
                document.getElementById(that.eleID).innerHTML=selectHtmlDefaultTemplate+selectHtmlTemplate;
            }
        }
    }
}
export { inputSelectSearch }
