"use strict";

import {util} from "../../../../util/util.js";
import {khcToastr} from "../../../../component/alert/khcToastr.js";
import {khcAlert} from "../../../../component/alert/khcAlert.js";
import {khcModal} from "../../../../component/alert/khcModal.js";
import {config} from "../../../../config.js";
import {form} from "../../../../component/page/form/form.js";
import {pageInfoMap} from "../../../../pageInfoMap.js";

class formHeaderButtonList {
    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() {
        //todo 待实现更多展示类型，暂时都默认只有文本
        let that=this;
        let leftHtml='<div id="'+that.objID+'Left">';
        for(let j=0;j< that.data.dataLeftButtonList.length;j++){
            leftHtml+=`<button type="button" class="btn btn-sm btn-round ${that.data.dataLeftButtonList[j].class} mr-2" id="${that.data.dataLeftButtonList[j].clickEvent}">
                     <i class="${that.data.dataLeftButtonList[j].icon}"></i><span class="d-none d-xxl-inline">&nbsp; ${that.data.dataLeftButtonList[j].label}</span>
                   </button>`
        }
        leftHtml+=`</div>`
        $('#' + that.data.buildFormHeaderButtonLeftID).html(leftHtml);
        let rightHtml='<div id="'+that.objID+'Left">';
        for(let j=0;j< that.data.dataRightButtonList.length;j++){
            rightHtml+=`<button type="button" class="btn btn-sm btn-round ${that.data.dataRightButtonList[j].class} ml-2" id="${that.data.dataRightButtonList[j].clickEvent}">
                     <i class="${that.data.dataRightButtonList[j].icon}"></i><span class="d-none d-xxl-inline">&nbsp; ${that.data.dataRightButtonList[j].label}</span>
                   </button>`
        }
        rightHtml+=`</div>`
        $('#' + that.data.buildFormHeaderButtonRightID).html(rightHtml);
        that.addClickEvent();
    }
    addClickEvent(){
        let that=this;
        for(let j=0;j< that.data.dataLeftButtonList.length;j++){
            document.getElementById(that.data.dataLeftButtonList[j].clickEvent).addEventListener('click',function (){
                if(that[that.data.dataLeftButtonList[j].clickEvent]==undefined){
                    khcToastr.showWarningMessage('该组件功能正在开发中，敬请期待！')
                    return
                }
                that[that.data.dataLeftButtonList[j].clickEvent]();
            })
        }
        for(let j=0;j< that.data.dataRightButtonList.length;j++){
            document.getElementById(that.data.dataRightButtonList[j].clickEvent).addEventListener('click',function (){
                if(that[that.data.dataRightButtonList[j].clickEvent]==undefined){
                    khcToastr.showWarningMessage('该组件功能正在开发中，敬请期待！')
                    return
                }
                that[that.data.dataRightButtonList[j].clickEvent]();
            })
        }
    }
    leftViewPc(){
        let that=this;
        document.getElementById(that.data.buildFormStartDivID).style.width='';
    }
    leftViewPad(){
        let that=this;
        document.getElementById(that.data.buildFormStartDivID).style.width='576px';
    }
    leftViewPhone(){
        let that=this;
        document.getElementById(that.data.buildFormStartDivID).style.width='420px';
    }
    rightImportJSON(){
        let that=this;
        let importJSONFunc=function (){
            let khcModalForForm = new khcModal({ modalAreaID: config.getConfigJson().modalAreaID });
            let showObjId=util.getUUID();
            let khcModalHtml = '';
            khcModalHtml += '<div class="card">'
            khcModalHtml += '<h6 class="card-header">'
            khcModalHtml += `JSON导入`
            khcModalHtml += '</h6>';
            khcModalHtml += '<div style="padding: 0.1rem;display: none" class="" id="'+showObjId+'">'
            khcModalHtml += '</div></div>';
            khcModalHtml += '<div class="card mb-4">'
            khcModalHtml += '<div style="padding: 0.1rem;" class="ql-container ql-snow" id="'+showObjId+'_preview">'
            khcModalHtml += '</div></div>';
            khcModalForForm.render().then(() => {
                document.getElementById(khcModalForForm.getEleID()).insertAdjacentHTML("beforeEnd", khcModalHtml);
                let html='<div class="ql-editor">'
                html+= `<div class="card-body">
                  <div class="form-group row">
                    <label class="col-form-label col-sm-2 text-sm-right">上传JSON文件</label>
                    <div class="col-sm-10">
                      <input type="file" id="${showObjId}_file" accept=".json"/>
                    </div>
                  </div>
                  <div class="form-group row">
                    <label class="col-form-label col-sm-2 text-sm-right">JSON</label>
                    <div class="col-sm-10">
                      <textarea class="form-control" id="${showObjId}_json" rows="10" placeholder="将拷贝的JSON粘贴在此，或上传JSON文件"></textarea>
                    </div>
                  </div>
                  <div class="form-group row">
                    <div class="col-sm-10 ml-sm-auto">
                      <button type="button" class="btn btn-primary" id="${showObjId}_importButton">导入</button>
                    </div>
                  </div>
              </div>`;
                html+='</div>'
                document.getElementById(showObjId+'_preview').insertAdjacentHTML("beforeEnd", html);
                document.getElementById(`${showObjId}_importButton`).addEventListener('click',function (){
                    let eleObj=document.getElementById(`${showObjId}_json`);
                    let importJSON={}
                    if(util.isNull(eleObj.value)){
                        khcToastr.showErrorMessage('JSON不能为空')
                        return ;
                    }
                    try {
                        importJSON=JSON.parse(eleObj.value)
                    }catch (e) {
                        khcToastr.showErrorMessage('JSON异常')
                        return
                    }
                    that.formBuildObj.formDataMap=new Map();
                    document.getElementById(that.formBuildObj.data.buildFormStartID).innerHTML='';
                    if(!util.isNull(importJSON.formInfo['form_name'])){
                        $(`#${that.componentFormObj.data.buildFormTitleID}`).html(importJSON.formInfo['form_name']);
                    }
                    that.componentFormObj.setValue(importJSON.formInfo);
                    that.formBuildObj.data.componentFieldListObj.hideDiv();
                    for (let i = 0; i < importJSON.formData.length; i++) {
                        that.formBuildObj.createImportJsonInputComponent(importJSON.formData[i].data)
                    }
                    khcAlert.showSuccessMessage('导入成功')
                    khcModalForForm.hide();
                })
                // 文件上传部分
                document.getElementById(`${showObjId}_file`).addEventListener('change', function(event) {
                    const file = event.target.files[0];  // 获取上传的文件

                    if (file && file.type === 'application/json') {  // 检查文件类型是否为JSON
                        const reader = new FileReader();  // 创建一个FileReader实例

                        // 设置读取文件成功的回调函数
                        reader.onload = function(e) {
                            try {
                                const jsonData = JSON.parse(e.target.result);  // 解析JSON
                                document.getElementById(`${showObjId}_json`).value=JSON.stringify(jsonData, null, 2);  // 显示解析后的数据
                            } catch (error) {
                                khcToastr.showErrorMessage('Error parsing JSON: ' + error.message)
                            }
                        };

                        reader.readAsText(file);  // 读取文件内容
                    } else {
                        khcToastr.showErrorMessage('Please upload a valid JSON file.')
                    }
                });
            })
            khcModalForForm.show();
        }

        if(that.formBuildObj.formDataMap.size==0){
            importJSONFunc();
        }else{
            let alertData = {};
            alertData.title = `当前有其他组件，是否覆盖导入？`;
            alertData.preConfirm= async () => {
                return new Promise((resolve, reject) => {
                    setTimeout(function (){
                        importJSONFunc();
                        resolve(true);
                    },700)
                })
            }
            khcAlert.showConfirm(alertData, () => {})
        }

    }
    rightExport(){
        let that=this;
        let khcModalForForm = new khcModal({ modalAreaID: config.getConfigJson().modalAreaID });
        let showObjId=util.getUUID();
        let khcModalHtml = '';
        khcModalHtml += '<div class="card">'
        khcModalHtml += '<h6 class="card-header">'
        khcModalHtml += `选择导出类型`
        khcModalHtml += '</h6>';
        khcModalHtml += '<div style="padding: 0.1rem;display: none" class="" id="'+showObjId+'">'
        khcModalHtml += '</div></div>';
        khcModalHtml += '<div class="card mb-4">'
        khcModalHtml += '<div style="padding: 0.1rem;" class="ql-container ql-snow" id="'+showObjId+'_preview">'
        khcModalHtml += '</div></div>';
        khcModalForForm.render().then(() => {
            document.getElementById(khcModalForForm.getEleID()).insertAdjacentHTML("beforeEnd", khcModalHtml);
            let html='<div class="ql-editor">'
            html+= `<div class="card-body">
                  <div class="form-group row">
                    <label class="col-form-label col-sm-2 text-sm-right">导出类型</label>
                    <div class="col-sm-10">
                      <div class="col-sm-10" style="top:8px;vertical-align: middle;">
                            <label class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="${showObjId}_radio" value="JSON" checked>
                                <span class="form-check-label">JSON</span>
                            </label>
                            
                            <label class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="${showObjId}_radio" value="HTML">
                                <span class="form-check-label">HTML（待开发）</span>
                            </label>
                        </div>
                    </div>
                  </div>
                  <div class="form-group row">
                    <div class="col-sm-10 ml-sm-auto">
                      <button type="button" class="btn btn-primary" id="${showObjId}_copyButton">复制</button><button type="button" class="btn btn-info ml-4" id="${showObjId}_exportButton">导出</button>
                    </div>
                  </div>
              </div>`;
            html+='</div>'
            document.getElementById(showObjId+'_preview').insertAdjacentHTML("beforeEnd", html);
            document.getElementById(`${showObjId}_copyButton`).addEventListener('click',function (){
                let eleObj=document.getElementsByName(`${showObjId}_radio`);
                let radioValue='';
                for (let i = 0; i < eleObj.length; i++) {
                    if (eleObj[i].checked == true) {
                        radioValue=eleObj[i].value;
                        break;
                    }
                }
                if(radioValue=='JSON'){
                    let exportFormData=[];
                    $(`#${that.formBuildObj.data.buildFormStartID}`).children().each(function () {
                        let inputData={};
                        inputData.data=that.formBuildObj.formDataMap.get($(this).attr('id')).getData().inputData;
                        inputData.data.field_show_type="createAndEditShow"
                        inputData.name=inputData.data.name
                        inputData.show_type=inputData.data.show_type
                        exportFormData.push(inputData)
                    });
                    let exportFormInfo={}
                    let exportJSON={}
                    let formName=document.getElementById(`${that.componentFormObj.data.buildFormTitleID}`).innerHTML
                    exportFormInfo.form_name=formName;
                    exportJSON.formInfo=exportFormInfo
                    exportJSON.formData=exportFormData
                    new Clipboard('.btn', {
                        text:function(){//.btn 这个元素在就行，这里使用的是自定义复制文本内容，更多使用示例阅读官方文档：https://it.cha138.com/ios/show-45625.html
                            return JSON.stringify(exportJSON);
                        }
                    })
                    khcToastr.showSuccessMessage('内容已复制到剪切板。')
                    return
                }
                if(radioValue=='HTML'){
                    khcToastr.showWarningMessage('开发中')
                    return
                }
            })
            document.getElementById(`${showObjId}_exportButton`).addEventListener('click',function (){
                let eleObj=document.getElementsByName(`${showObjId}_radio`);
                let radioValue='';
                for (let i = 0; i < eleObj.length; i++) {
                    if (eleObj[i].checked == true) {
                        radioValue=eleObj[i].value;
                        break;
                    }
                }
                if(radioValue=='JSON'){
                    let exportFormData=[];
                    $(`#${that.formBuildObj.data.buildFormStartID}`).children().each(function () {
                        let inputData={};
                        inputData.data=that.formBuildObj.formDataMap.get($(this).attr('id')).getData().inputData;
                        inputData.data.field_show_type="createAndEditShow"
                        inputData.name=inputData.data.name
                        inputData.show_type=inputData.data.show_type
                        exportFormData.push(inputData)
                    });
                    let exportFormInfo={}
                    let exportJSON={}
                    let formName=document.getElementById(`${that.componentFormObj.data.buildFormTitleID}`).innerHTML
                    exportFormInfo.form_name=formName;
                    exportJSON.formInfo=exportFormInfo
                    exportJSON.formData=exportFormData
                    const blob = new Blob([JSON.stringify(exportJSON, null, 2)], { type: 'application/json' });
                    const link = document.createElement('a');  // 创建一个链接元素
                    link.href = URL.createObjectURL(blob);  // 将Blob转换为URL
                    const date = new Date();
                    const year = date.getFullYear();
                    const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，所以加1
                    const day = date.getDate().toString().padStart(2, '0');
                    link.download = `${formName}-${year}${month}${day}`+'.json';  // 设置下载文件的名称
                    link.click();  // 触发下载
                    khcToastr.showSuccessMessage('导出成功。')
                    return
                }
                if(radioValue=='HTML'){
                    khcToastr.showWarningMessage('开发中')
                    return
                }
            })
        })
        khcModalForForm.show();
    }
    rightPreview(){
        let that=this;
        let khcModalForForm = new khcModal({ modalAreaID: config.getConfigJson().modalAreaID });
        let exportFormData=[];
        $(`#${that.formBuildObj.data.buildFormStartID}`).children().each(function () {
            let inputData={};
            inputData.data=that.formBuildObj.formDataMap.get($(this).attr('id')).getData().inputData;
            inputData.data.field_show_type="createAndEditShow"
            inputData.name=inputData.data.name
            inputData.show_type=inputData.data.show_type
            exportFormData.push(inputData)
        });
        let formInfo={}
        let formData={}
        let formName=document.getElementById(`${that.componentFormObj.data.buildFormTitleID}`).innerHTML
        formInfo.form_name=formName;
        formData.formInfo=formInfo
        formData.formData=exportFormData
        khcModalForForm.render().then(() => {
            let formComponent = new form({ parentObjID: khcModalForForm.getEleID(), formData:formData});
            formComponent.khcModalForForm=khcModalForForm;
            khcModalForForm.formComponent=formComponent;
            khcModalForForm.formObjID=formComponent.getObjID()
            let khcModalForFormKey='khcModalForForm#'+formComponent.getObjID();
            pageInfoMap.push(khcModalForFormKey,khcModalForForm);
            formComponent.setFormShowType('modals')
            formComponent.setSaveBefore( ()=> {
                return false;
            })
            formComponent.render().then(() => {
                formComponent.renderThenFunc=()=> {
                    let eleMap = formComponent.getFormMap();
                    formComponent.formCreate();
                    khcModalForForm.show();
                }
                formComponent.renderThenFunc();
            });
        })
    }
    rightClean(){
        let that=this;
        if(that.formBuildObj.formDataMap.size==0){
            khcToastr.showWarningMessage('当前没有任何组件，无需清空！')
            return
        }
        let alertData = {};
        alertData.title = `确定要清空吗？`;
        alertData.preConfirm= async () => {
            return new Promise((resolve, reject) => {
                setTimeout(function (){
                    that.formBuildObj.formDataMap=new Map();
                    document.getElementById(that.formBuildObj.data.buildFormStartID).innerHTML='';
                    that.formBuildObj.data.componentFieldListObj.hideDiv();
                    resolve(true);
                },700)
            })
        }
        khcAlert.showConfirm(alertData, () => {})
    }
}
export { formHeaderButtonList }