"use strict";
import {base} from './base.js'
import { util } from '../../util/util.js'
class inputKV extends base{
    constructor(data) {
        super(data);
        this.type='kv';
    }
    render(renderParentID){
        let that=this;
        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);
        }
    }
    renderDefault(parentObjID){
        let that=this;
        that.initFunc();
        let data=that.data
        let labelName=data.label_name;
        let placeholder=data.placeholder;
        let defaultValue=data.default_value;
        let isReadOnly=data.is_read_only;
        let rows=data.rows;
        let canNull=data.can_null;
        that.initFormCol(that);
        let questionCircleHtml=that.getQuestionCircleIconHtml();
        that.dict_code_json_map=new Map();
        if(util.isNull(that.data.dict_code_json)){
            data.dict_code_json=[{key:1,value:'选项1'},{key:2,value:'选项2'}]
        }else{
            try {
                if (typeof that.data.dict_code_json == 'string') {
                    data.dict_code_json=JSON.parse(that.data.dict_code_json)
                    data.dict_code_json.length;
                }
            } catch (error) {
            }
        }
        let optionHtml=that.getOptionHtml();
        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="form-group row">
                <div id="${data.name}_sortable_div" class="row">
                    ${optionHtml}
                </div>
                <div class="form-group row col-sm-12 mt-2" style="margin-left: 12px;" draggable="false">
                    <span class="btn btn-sm btn-outline-info" id="${data.name}_add">
                        <span class="fas fa-plus"></span>&nbsp;添加选项
                    </span>
                </div>
                <small class="form-text text-muted"><font style="display:none;"  validate="validate"  color="red">12412345123</font></small>
            </div>
        </div>
        </div>
        `;
        document.getElementById(parentObjID).insertAdjacentHTML("beforeEnd",htmlTemplate);
        document.getElementById(`${that.data.name}_add`).addEventListener('click',function (){
            let dictLength=that.data.dict_code_json.length+1;
            let newSort=dictLength*10
            let addDictCodeJSON={key:dictLength,value:'选项'+dictLength,uuid:util.getUUID(),sort:newSort}
            that.data.dict_code_json.push(addDictCodeJSON);
            that.updateView();
        })
        that.bindFunc();
    }
    getOptionHtml(){
        let that=this;
        let data=that.data;
        that.dict_code_json_map=new Map();
        let optionHtml=``;
        for (let i = 0; i < data.dict_code_json.length; i++) {
            let thisDict=data.dict_code_json[i];
            thisDict.sort=(i+1)*10;
            thisDict['uuid']=util.getUUID();
            that.dict_code_json_map.set(thisDict['uuid'],thisDict)
            optionHtml+=`<div class="form-group row col-sm-12 ml-4 mt-2" id="${thisDict['uuid']}">
                             <span class="btn icon-btn btn-sm btn-outline-info mr-2">
                                 <span class="ion ion-ios-move"></span>
                             </span>
                             <input style="width: 80px" type="text" id="${thisDict['uuid']}_key"
                             class="form-control form-control-sm mr-sm-2 mb-2 mb-sm-0" placeholder="选项值" value="${data.dict_code_json[i].key}">
                             <input style="width: 100px" type="text" id="${thisDict['uuid']}_value"
                             class="form-control form-control-sm mr-sm-2 mb-2 mb-sm-0" placeholder="选项名" value="${data.dict_code_json[i].value}">
                             <span class="btn icon-btn btn-sm btn-outline-danger" id="${thisDict['uuid']}_remove">
                                 <span class="far fa-trash-alt"></span>
                             </span>
                         </div>`
        }
        return optionHtml;
    }
    updateView(){
        let that=this;
        let optionHtml=that.getOptionHtml();
        document.getElementById(`${that.data.name}_sortable_div`).innerHTML=optionHtml;
        that.bindFunc();
    }
    getValue() {
        return this.data.dict_code_json;
    }

    setValue(value) {
        let that=this;
        let dictCodeJSON=[];
        if(!util.isNull(value)){
            try {
                if (typeof value == 'string') {
                    dictCodeJSON=JSON.parse(value)
                    dictCodeJSON.length;
                }else{
                    dictCodeJSON=that.data.dict_code_json
                }
            } catch (error) {
            }
        }
        that.data.dict_code_json=dictCodeJSON
        that.updateView()
    }

    hide(){
        document.getElementById(this.objID).setAttribute('style', 'display:none');//隐藏
    }
    show(){
        if(this.data.kind=='text_detail')return
        document.getElementById(this.objID).setAttribute('style', '');//展示
    }
    initFunc(){
        let that=this;
    }
    bindFunc(){
        let that=this;
        Sortable.create(document.getElementById(`${that.data.name}_sortable_div`), {
            animation: 150,
            handle: '.ion',
            onEnd: function (evt) {
                let sortValue = 0;
                let dict_code_json=[]
                $(`#${that.data.name}_sortable_div`).children().each(function (index, element) {
                    sortValue++;
                    that.dict_code_json_map.get($(this).attr('id')).sort = sortValue * 10;
                    dict_code_json.push(that.dict_code_json_map.get($(this).attr('id')))
                    // 判断是否为最后一个元素
                    if (index === $(this).parent().children().length - 1) {
                        that.data.dict_code_json=dict_code_json;
                    }
                });

            },
        });
        for (let i = 0; i < that.data.dict_code_json.length; i++) {
            let thisDict=that.data.dict_code_json[i];
            document.getElementById(`${thisDict['uuid']}_key`).addEventListener('input',function (){
                that.data.dict_code_json[i].key=this.value
            })
            document.getElementById(`${thisDict['uuid']}_value`).addEventListener('input',function (){
                that.data.dict_code_json[i].value=this.value
            })
            document.getElementById(`${thisDict['uuid']}_remove`).addEventListener('click',function (){
                that.data.dict_code_json.splice(i, 1);
                that.updateView();
            })
        }
    }
    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 {inputKV}