"use strict";

import {base} from "./base.js";
import {util} from "../../../../../util/util.js";
import {khcAlert} from "../../../../../component/alert/khcAlert.js";

class buildCheckbox extends base {
    constructor(data) {
        super(data);
        this.type='checkbox';
    }
    render() {
        let that=this;
        that.remove();
        that.writeBefore(that.data['parentDomId']);
    }
    reRender(){
        let that=this;
        // 获取目标元素，通过 objID 定位
        let targetElement = document.getElementById(that.objID);
        // 重新渲染新的 HTML 内容
        targetElement.innerHTML = that.getContentHtml();
        that.initEvent();
        that.setValue(that.data.inputData.default_value)
    }
    writeBefore(parentDomId) {
        let that=this;
        let html=`
            <div class="col-${that.data.inputData.col}" style="border:0" id="${that.objID}">
                ${that.getContentHtml()}
            </div>`
        $('#'+parentDomId).append(html);
        that.initEvent();
        that.setValue(that.data.inputData.default_value)
    }
    getContentHtml() {
        let that=this;
        let mangerHtml=``
        for(let i=0;i<that.data.listManager.length;i++){
            mangerHtml+=`
                <span title="${that.data.listManager[i].title}" area="${that.data.listManager[i].areaName}" class="footer-link pt-10 ml-1 mr-2" style="cursor:pointer">
                    <i class="${that.data.listManager[i].iconClass}" style="${that.data.listManager[i].iconCss}"></i>
                </span>`
        }
        let inputHtml=``;
        let renderDictCodeJson=[];
        if(util.isNull(that.data.inputData.dict_code_json)) {
            if(that.data.inputData.dict_code!=null){
                renderDictCodeJson = that.data.inputData.dict_code.data
            }
        }else{
            try {
                if (typeof that.data.inputData.dict_code_json == 'string') {
                    renderDictCodeJson=JSON.parse(that.data.inputData.dict_code_json)
                    renderDictCodeJson.length;
                }else{
                    renderDictCodeJson=that.data.inputData.dict_code_json;
                }
            } catch (error) {
            }
        }
        for(let i=0;i<renderDictCodeJson.length;i++){
            inputHtml+=`<label class="form-check form-check-inline" style="top:11px;vertical-align: middle;">
            <input class="form-check-input" type="checkbox" name="${that.getEleID()}" value="${renderDictCodeJson[i].key}">
            <span class="form-check-label">${renderDictCodeJson[i].value}</span>
            </label>`
        }
        let labelNameHtml=``;
        if(!util.isNull(that.data.inputData.can_null)&&that.data.inputData.can_null=='Y'){
            labelNameHtml=`<font style="font-size: 22px;vertical-align: middle;" color="red">*</font>${that.data.inputData.label_name}`
        }else{
            labelNameHtml=`<font style="font-size: 22px;vertical-align: middle; display:none;" color="red">*</font>${that.data.inputData.label_name}`
        }
        let html=`
        <div class="card-body" style="padding:0.5rem" area="hoverbody">
            <div class="${that.data.inputData.field_layout_type=='horizontal'?'row':'form-group'}" style="margin-bottom: 0.01rem;" name="layout_div">
                <div area="manageDiv" style="position: absolute;top: -18px;right: 20px;z-index: 10;display: none">
                   ${mangerHtml}
                </div>
                <label name="layout_label" class="col-form-label ${that.data.inputData.field_layout_type=='horizontal'?'col-sm-3':''} text-sm-right" style="line-height:25px;vertical-align: middle;">
                    ${labelNameHtml}
                </label>
                <div name="layout_input_div" class="${that.data.inputData.field_layout_type=='horizontal'?'col-sm-9':''}">
                    ${inputHtml}
                </div>
            </div>
        </div>
`
        return html;
    }
    initEvent() {
        let that=this;
        let eleObj=document.getElementsByName(that.eleID);
        for (let i = 0; i < eleObj.length; i++) {
            eleObj[i].addEventListener('click',function (){
                let checkBoxValue='';
                for (let i = 0; i < eleObj.length; i++) {
                    if (eleObj[i].checked == true) {
                        checkBoxValue+=eleObj[i].value+",";
                    }
                }
                if(checkBoxValue.length>0){
                    checkBoxValue=','+checkBoxValue;//前后都保留逗号，可做模糊查询
                }
                that.data.inputData.default_value=checkBoxValue
                that.data.parentObj.data.componentFieldListObj.setInputComponent(that)
            })
        }

        $('#' + that.objID).find('[area=copy]').unbind("click").click(function () {
            that.data.parentObj[that.data.funcName]();
        });

        $('#' + that.objID).find('[area=remove]').unbind("click").click(function () {
            let alertData = {};
            alertData.title = `确定要删除吗`;
            alertData.preConfirm= async () => {
                return new Promise((resolve, reject) => {
                    setTimeout(function (){
                        that.remove();
                        resolve(true);
                        that.data.parentObj.removeFormSort(that);
                        that.data.parentObj.data.componentFieldListObj.setInputComponent();
                        that.data.parentObj.data.componentFieldListObj.hideDiv();
                        //refreshSort();
                        //message.showSuccessMessage('删除成功')
                    },700)
                })
            }
            khcAlert.showConfirm(alertData, () => {})
        });

        $('#' + that.objID).click(function (){
            that.data.parentObj.data.componentFieldListObj.setInputComponent(that);
            that.data.parentObj.data.componentFieldListObj.showDiv();
        })

        $('#' + that.objID).hover(function(){
            $('#' + that.objID).find('[area=hoverbody]').css("background-color", "#eeeeee");
            $('#' + that.objID).find('[area=manageDiv]').css('display','block')
            $('#' + that.objID).find('[area=bodyShowDiv]').find("input:text").css("background-color", "#eeeeee");
        },function(){
            $('#' + that.objID).find('[area=hoverbody]').css("background-color", "white");
            $('#' + that.objID).find('[area=manageDiv]').css('display','none')
            $('#' + that.objID).find('[area=bodyShowDiv]').find("input:text").css("background-color", "white");
        })
        if(that.data.inputData.is_read_only=='Y'){
            that.setDisabled();
        }else{
            that.removeDisabled();
        }
    }
    setDisabled(){
        let that=this;
        let eleObj = document.getElementsByName(that.getEleID());
        for (let i = 0; i < eleObj.length; i++) {
            eleObj[i].disabled=true;
        }
    }
    removeDisabled(){
        let that=this;
        let eleObj = document.getElementsByName(that.getEleID());
        for (let i = 0; i < eleObj.length; i++) {
            eleObj[i].disabled=false;
        }
    }
    updateView(){
        let that=this;
        if(that.type!=that.data.inputData.show_type){
            that.data.parentObj.toggleInputComponent(that.data.inputData.show_type,that)
            return ;
        }
        let labelNameHtml=``;
        let dictCodeJSON=[];
        try {
            if (typeof that.data.inputData.dict_code_json == 'string') {
                dictCodeJSON=JSON.parse(that.data.inputData.dict_code_json)
                dictCodeJSON.length;
            }else{
                dictCodeJSON=that.data.inputData.dict_code_json
            }
        } catch (error) {
            return ;
        }
        let inputHtml=``;
        for(let i=0;i<dictCodeJSON.length;i++){
            inputHtml+=`<label class="form-check form-check-inline" style="top:11px;vertical-align: middle;">
            <input class="form-check-input" type="checkbox" name="${that.getEleID()}" value="${dictCodeJSON[i].key}">
            <span class="form-check-label">${dictCodeJSON[i].value}</span>
            </label>`
        }
        document.getElementById(this.getObjID()).querySelector('[name="layout_input_div"]').innerHTML=inputHtml;
        that.initEvent();
        let eleObj = document.getElementsByName(that.getEleID());
        if(!util.isNull(that.data.inputData.can_null)&&that.data.inputData.can_null=='Y'){
            labelNameHtml=`<font style="font-size: 22px;vertical-align: middle;" color="red">*</font>${that.data.inputData.label_name}`
        }else{
            labelNameHtml=`<font style="font-size: 22px;vertical-align: middle; display:none;" color="red">*</font>${that.data.inputData.label_name}`
        }
        if(!util.isNull(that.data.inputData.is_read_only)&&that.data.inputData.is_read_only=='Y'){
            for (let i = 0; i < eleObj.length; i++) {
                eleObj[i].disabled=true;
            }
        }else{
            for (let i = 0; i < eleObj.length; i++) {
                eleObj[i].disabled=false;
            }
        }
        if(util.isNull(that.data.inputData.col)||that.data.inputData.col>12){
            that.data.inputData.col=12;
        }
        if(util.isNull(that.data.inputData.field_layout_type)){
            that.data.inputData.field_layout_type='horizontal';
        }
        if(that.data.inputData.field_layout_type=='horizontal'){
            document.getElementById(this.getObjID()).querySelector('[name="layout_div"]').className='row'
            document.getElementById(this.getObjID()).querySelector('[name="layout_label"]').classList.add('col-sm-3');
            document.getElementById(this.getObjID()).querySelector('[name="layout_input_div"]').classList.add('col-sm-9');
        }else{
            document.getElementById(this.getObjID()).querySelector('[name="layout_div"]').className='form-group'
            document.getElementById(this.getObjID()).querySelector('[name="layout_label"]').classList.remove('col-sm-3');
            document.getElementById(this.getObjID()).querySelector('[name="layout_input_div"]').classList.remove('col-sm-9');
        }
        document.getElementById(this.getObjID()).className="col-"+that.data.inputData.col
        document.getElementById(this.getObjID()).querySelector('[name="layout_label"]').innerHTML=labelNameHtml
        that.setValue(that.data.inputData.default_value)
    }
    setValue(value){
        let that=this;
        let eleObj = document.getElementsByName(that.getEleID());
        for (let i = 0; i < eleObj.length; i++) {
            // 确保前后都有逗号
            value = ',' + value.replace(/^,|,$/g, '') + ',';
            if (value.indexOf(',' + eleObj[i].value + ',') >= 0) {
                eleObj[i].checked = true;
            }else{
                eleObj[i].checked = false;
            }
        }
    }
    updateFieldView(fieldObj){
        let that=this;
        let eleObj = document.getElementById(fieldObj.getObjID());
        eleObj.querySelector('[name="show_type"]').value=that.data.inputData.show_type;
        eleObj.querySelector('[name="name"]').value=that.data.inputData.name;
        eleObj.querySelector('[name="label_name"]').value=that.data.inputData.label_name;
        eleObj.querySelector('[name="placeholder"]').value=that.data.inputData.placeholder;
        eleObj.querySelector('[name="placeholder_div"]').style.display='none';
        eleObj.querySelector('[name="default_value"]').value=that.data.inputData.default_value;
        eleObj.querySelector('[name="col"]').value=that.data.inputData.col;
        $('.bs-slider-variant_col').slider('setValue', that.data.inputData.col);
        eleObj.querySelector('[name="field_layout_type"]').value=that.data.inputData.field_layout_type;
        eleObj.querySelector('[name="rows"]').value=that.data.inputData.rows;
        eleObj.querySelector('[name="rows_div"]').style.display='none';
        eleObj.querySelector('[name="dict_code_json_div"]').style.display='';
        eleObj.querySelector('[name="switch_yes_key_div"]').style.display='none';
        eleObj.querySelector('[name="switch_no_key_div"]').style.display='none';
        //eleObj.querySelector('[name="dict_code_json"]').innerHTML=JSON.stringify(that.data.inputData.dict_code_json);
        let optionHtml=``;
        that.dict_code_json_map=new Map();
        if(util.isNull(that.data.inputData.dict_code_json)) {
            that.data.inputData.dict_code_json = [];
        }
        try {
            if (typeof that.data.inputData.dict_code_json == 'string') {
                that.data.inputData.dict_code_json=JSON.parse(that.data.inputData.dict_code_json)
                that.data.inputData.dict_code_json.length;
            }
        } catch (error) {
        }
        for (let i = 0; i < that.data.inputData.dict_code_json.length; i++) {
            let thisDict=that.data.inputData.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-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="${thisDict.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="${thisDict.value}">
                             <span class="btn icon-btn btn-sm btn-outline-danger" id="${thisDict['uuid']}_remove">
                                 <span class="far fa-trash-alt"></span>
                             </span>
                         </div>`
        }
        document.getElementById(`dict_code_json_sortable_div`).innerHTML=optionHtml;
        for (let i = 0; i < that.data.inputData.dict_code_json.length; i++) {
            let thisDict=that.data.inputData.dict_code_json[i];
            document.getElementById(`${thisDict['uuid']}_key`).addEventListener('input',function (){
                that.data.inputData.dict_code_json[i].key=this.value
                that.updateView();
            })
            document.getElementById(`${thisDict['uuid']}_value`).addEventListener('input',function (){
                that.data.inputData.dict_code_json[i].value=this.value
                that.updateView();
            })
            document.getElementById(`${thisDict['uuid']}_remove`).addEventListener('click',function (){
                that.data.inputData.dict_code_json.splice(i, 1);
                that.updateView();
                that.updateFieldView(that.data.parentObj.data.componentFieldListObj);
            })
        }
        let value='';
        if(that.data.inputData.can_null=='Y'){
            value=',on,'
        }
        let canNullObj = eleObj.querySelector('[name="can_null"]');
        if (value.indexOf(','+canNullObj.value+',')>=0) {
            canNullObj.checked = true;
        }else{
            canNullObj.checked = false;
        }
        value='';//重置
        if(that.data.inputData.is_read_only.length>0){
            value=',on,'
        }
        let isReadOnlyObj = eleObj.querySelector('[name="is_read_only"]');
        if (value.indexOf(','+isReadOnlyObj.value+',')>=0) {
            isReadOnlyObj.checked = true;
        }else{
            isReadOnlyObj.checked = false;
        }
    }
}
export { buildCheckbox }