"use strict";

import {util} from "../../../../util/util.js";

class componentFieldList {
    constructor(data) {
        this.data = data;
        //给当前对象创建一个id，同时该id也是对象的domid
        this.eleID = util.getUUID();
        this.objID = this.eleID + 'div';
    }
    remove() {
        $('#' + this.objID).remove();
    }
    getData() {
        return this.data;
    }
    getObjID() {
        return this.objID;
    }
    render(renderParentID) {
        let that=this;
        let html='<div class="py-3" id="'+that.objID+'" style="display: none;height: 780px;">';
        html+='<ul class="sidenav-inner py-3 ps ps--active-y">'
        for(let j=0;j< that.data.dataList.length;j++){
            html+=that._getInputHtml(that.data.dataList[j])
        }
        $('#' + renderParentID).html(html);
        new PerfectScrollbar(document.getElementById(`${that.objID}`));
        that.addClickEvent();
    }
    _getInputHtml(inputData){
        let that=this;
        const map=
            [[
                ()=>inputData.show_type=='text',()=>{
                    return that._getTextHtml(inputData)
                }],[
                ()=>inputData.show_type=='textarea',()=>{
                    return that._getTextareaHtml(inputData)
                }],[
                ()=>inputData.show_type=='select',()=>{
                    return that._getSelectHtml(inputData)
                }],[
                ()=>inputData.show_type=='switch',()=>{
                    return that._getSwitchHtml(inputData)
                }],[
                ()=>inputData.show_type=='kv',()=>{
                    return that._getKVHtml(inputData)
                }],[
                ()=>inputData.show_type=='slider',()=>{
                    return that._getSliderHtml(inputData)
                }]
            ]
        let target=map.find((m)=>m[0]());//find()是es6新加的方法，具体可以看ES6文档
        if(target){
            return target[1]()
        }else{
            console.log( '未加入渲染的表单类型：'+inputData.show_type)
        }
    }
    _getTextHtml(inputData){
        return `<div class="form-group row" name="${inputData.name}_div">
                    <label class="col-form-label text-sm-right" style="width: 100px">${inputData.label_name}</label>
                    <div class="col-sm-7">
                        <input type="text" name="${inputData.name}" class="form-control" placeholder="${inputData.placeholder}">
                    </div>
                </div>`
    }
    _getTextareaHtml(inputData){
        return `<div class="form-group row" name="${inputData.name}_div">
                    <label class="col-form-label text-sm-right" style="width: 100px">${inputData.label_name}</label>
                    <div class="col-sm-7">
                        <textarea type="text" rows="6" name="${inputData.name}" class="form-control" placeholder="${inputData.placeholder}"></textarea>
                    </div>
                </div>`
    }
    _getSelectHtml(inputData){
        let optionHtml=``;
        for (let i = 0; i < inputData.dict_code.data.length; i++) {
            optionHtml+=`<option value="${inputData.dict_code.data[i]['key']}">${inputData.dict_code.data[i]['value']}</option>`;
        }
        return `<div class="form-group row" name="${inputData.name}_div" >
                    <label class="col-form-label text-sm-right" style="width: 100px">${inputData.label_name}</label>
                    <div class="col-sm-7">
                        <div class="input-group-append" style="width: 135px">
                            <select class="custom-select" name="${inputData.name}">
                                <option value="">请选择</option>
                                ${optionHtml}
                            </select>
                        </div>
                    </div>
                </div>`
    }
    _getSwitchHtml(inputData){
        return `<div class="form-group row" name="${inputData.name}_div">
                    <label class="col-form-label text-sm-right" style="width: 100px">${inputData.label_name}</label>
                    <div class="col-sm-5" style="top: 6px;vertical-align: middle;">
                        <label class="switcher">
                            <input type="checkbox" class="switcher-input" name="${inputData.name}">
                            <span class="switcher-indicator">
                              <span class="switcher-yes">是</span>
                              <span class="switcher-no">否</span>
                            </span>
                        </label>
                        <small class="form-text text-muted"><font style="display:none" validate="validate" color="red">12412345123</font></small>
                    </div>
                </div>`
    }
    _getKVHtml(inputData){
        let optionHtml=``;
        inputData.dict_code_json_map=new Map();
        for (let i = 0; i < inputData.dict_code_json.length; i++) {
            let thisDict=inputData.dict_code_json[i];
            thisDict.sort=(i+1)*10;
            thisDict['uuid']=util.getUUID();
            inputData.dict_code_json_map.set(thisDict['uuid'],thisDict)
            optionHtml+=`<div class="form-inline mb-2 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: 60px" type="text" id="${thisDict['uuid']}_key"
                             class="form-control form-control-sm mr-sm-2 mb-2 mb-sm-0" placeholder="选项值" value="${inputData.dict_code_json[i].key}">
                             <input style="width: 80px" type="text" id="${thisDict['uuid']}_value"
                             class="form-control form-control-sm mr-sm-2 mb-2 mb-sm-0" placeholder="选项名" value="${inputData.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 `<div class="form-group row" name="${inputData.name}_div">
                    <label class="col-form-label text-sm-right" style="width: 100px">${inputData.label_name}</label>
                    <div id="${inputData.name}_sortable_div">
                        ${optionHtml}
                    </div>
                    <div class="form-inline mb-2 ml-4 mt-2" style="" draggable="false">
                        <span class="btn btn-sm btn-outline-info" id="${inputData.name}_add">
                            <span class="fas fa-plus"></span>&nbsp;添加选项
                        </span>
                    </div>
                </div>`
    }
    _getSliderHtml(inputData){
        return `<div class="form-group row" name="${inputData.name}_div">
                    <label class="col-form-label text-sm-right" style="width: 100px">${inputData.label_name}</label>
                    <div class="col-sm-7">
                        <div class="slider-primary" style="width: 130px;margin-top: 6px;">
                            <input class="bs-slider-variant_${inputData.name}" name="${inputData.name}" type="text" 
                            data-slider-min="${inputData.sliderInfo['data-slider-min']}" data-slider-max="${inputData.sliderInfo['data-slider-max']}" 
                            data-slider-step="${inputData.sliderInfo['data-slider-step']}" data-slider-value="${inputData.sliderInfo['data-slider-value']}">
                        </div>
                    </div>
                </div>`
    }
    showDiv(){
        let eleObj = document.getElementById(this.getObjID());
        eleObj.style.display='';
    }
    hideDiv(){
        let eleObj = document.getElementById(this.getObjID());
        eleObj.style.display='none';
    }
    setInputComponent(inputComponent){
        let that=this;
        let eleObj = document.getElementById(that.getObjID());
        if(util.isNull(inputComponent)){
            that.inputComponent=null;
            eleObj.querySelector('[name="label_name"]').value='';
            eleObj.querySelector('[name="placeholder"]').value='';
            eleObj.querySelector('[name="default_value"]').value='';
            eleObj.querySelector('[name="col"]').value='';
            eleObj.querySelector('[name="rows"]').value='';
            eleObj.querySelector('[name="rows_div"]').style.display='none';
        }else{
            that.inputComponent=inputComponent;
            that.inputComponent.updateFieldView(that)
        }

    }
    addClickEvent(){
        let that=this;
        for(let j=0;j< that.data.dataList.length;j++){
            if(that.data.dataList[j].show_type=='text'||that.data.dataList[j].show_type=='textarea'){
                let ele=document.getElementById(that.getObjID()).querySelector('[name="'+that.data.dataList[j].name+'"]');
                ele.addEventListener('input',function (){
                    if(!util.isNull(that.inputComponent)){
                        that.inputComponent.data.inputData[that.data.dataList[j].name]=ele.value
                        that.inputComponent.updateView()
                    }
                })
            }
            if(that.data.dataList[j].show_type=='switch'){
                let ele=document.getElementById(that.getObjID()).querySelector('[name="'+that.data.dataList[j].name+'"]');
                ele.addEventListener('click',function (){
                    console.log(11111)
                    if(!util.isNull(that.inputComponent)){
                        let checkBoxValue='';
                        if (ele.checked == true) {
                            checkBoxValue+=ele.value+",";
                        }
                        let isYN='Y'
                        if(checkBoxValue.length==0){
                            isYN='N'
                        }
                        that.inputComponent.data.inputData[that.data.dataList[j].name]=isYN
                        that.inputComponent.updateView()
                    }
                })
            }
            if(that.data.dataList[j].show_type=='select'){
                let ele=document.getElementById(that.getObjID()).querySelector('[name="'+that.data.dataList[j].name+'"]');
                ele.addEventListener('change',function (){
                    if(!util.isNull(that.inputComponent)){
                        that.inputComponent.data.inputData[that.data.dataList[j].name]=ele.value
                        that.inputComponent.updateView()
                    }
                })
            }
            if(that.data.dataList[j].show_type=='kv'){
                Sortable.create(document.getElementById(`${that.data.dataList[j].name}_sortable_div`), {
                    animation: 150,
                    handle: '.ion',
                    onEnd: function (evt) {
                        let sortValue = 0;
                        let dict_code_json=[]
                        console.log(1111)
                        $(`#${that.data.dataList[j].name}_sortable_div`).children().each(function (index, element) {
                            sortValue++;
                            that.inputComponent.dict_code_json_map.get($(this).attr('id')).sort = sortValue * 10;
                            dict_code_json.push(that.inputComponent.dict_code_json_map.get($(this).attr('id')))
                            // 判断是否为最后一个元素
                            if (index === $(this).parent().children().length - 1) {
                                that.inputComponent.data.inputData.dict_code_json=dict_code_json;
                                that.inputComponent.updateView();
                                that.inputComponent.updateFieldView(that);
                            }
                        });

                    },
                });
                document.getElementById(`${that.data.dataList[j].name}_add`).addEventListener('click',function (){
                    let dictLength=that.inputComponent.data.inputData.dict_code_json.length+1;
                    let newSort=dictLength*10
                    let addDictCodeJSON={key:dictLength,value:'选项'+dictLength,uuid:util.getUUID(),sort:newSort}
                    that.inputComponent.data.inputData.dict_code_json.push(addDictCodeJSON);
                    that.inputComponent.updateView();
                    that.inputComponent.updateFieldView(that);
                })
                for (let i = 0; i < that.data.dataList[j].dict_code_json.length; i++) {
                    let thisDict=that.data.dataList[j].dict_code_json[i];
                    document.getElementById(`${thisDict['uuid']}_key`).addEventListener('input',function (){
                        that.data.inputData.dict_code_json[i].key=this.value
                        that.inputComponent.updateView();
                    })
                    document.getElementById(`${thisDict['uuid']}_value`).addEventListener('input',function (){
                        that.data.inputData.dict_code_json[i].value=this.value
                        that.inputComponent.updateView();
                    })
                    document.getElementById(`${thisDict['uuid']}_remove`).addEventListener('click',function (){
                        that.data.inputData.dict_code_json.splice(i, 1);
                        that.inputComponent.updateView();
                        that.inputComponent.updateFieldView(that);
                    })
                }
            }
            if(that.data.dataList[j].show_type=='slider'){
                $(`.bs-slider-variant_${that.data.dataList[j].name}`).slider();
                // 监听 slide event
                $(`.bs-slider-variant_${that.data.dataList[j].name}`).on('slide', function(event) {
                    const newValue = event.value;
                    if(!util.isNull(that.inputComponent)){
                        that.inputComponent.data.inputData[that.data.dataList[j].name]=newValue
                        that.inputComponent.updateView()
                    }
                });
                $(`.bs-slider-variant_${that.data.dataList[j].name}`).on('change', function(event) {
                    const newValue = event.value.newValue;
                    if (!util.isNull(that.inputComponent)) {
                        that.inputComponent.data.inputData[that.data.dataList[j].name] = newValue;
                        that.inputComponent.updateView();
                    }
                });
            }
        }
    }
}
export { componentFieldList }