"use strict";
import { inputText } from '../../input/inputText.js';
import { inputDate } from '../../input/inputDate.js';
import { inputSelect } from '../../input/inputSelect.js';
import { inputRadio } from '../../input/inputRadio.js';
import { inputCheckBox } from '../../input/inputCheckBox.js';
import { vCutChar } from '../../input/vCutChar.js';
import { inputFile } from '../../input/inputFile.js';
import { inputTextArea } from '../../input/inputTextArea.js';
import { inputHidden } from '../../input/inputHidden.js';
import { inputTree } from '../../input/inputTree.js'
import { inputAutocomplete } from '../../input/inputAutocomplete.js'
import { formButtons } from './formButtons.js';
import { fullMap } from '../../../fullMap.js';
import { util } from '../../../util/util.js'
import { khcAlert } from '../../alert/khcAlert.js'
import {config} from "../../../config.js";
import {vChildPage} from "../../input/vChildPage.js";
import {vOpinion} from "../../input/vOpinion.js";
import {inputDualList} from "../../input/inputDualList.js";
import {khcToastr} from "../../alert/khcToastr.js";
import {inputTag} from "../../input/inputTag.js";
import {pageInfoMap} from "../../../pageInfoMap.js";
import {httpUtil} from "../../../util/httpUtil.js";
import {inputImage} from "../../input/inputImage.js";
import {inputEditor} from "../../input/inputEditor.js";
import {inputMarkdown} from "../../input/inputMarkdown.js";
import {vTabs} from "../../input/vTabs.js";
import {vCutCharFold} from "../../input/vCutCharFold.js";
import {formUtil} from "./formUtil.js";

class form {
    constructor(data) {
        this.formMap = new Map();
        this._objID = util.getUUID() + 'div';
        this.data = {};
        this.formShowType = 'page';//默认page
        this.code = data.code;
        this.parentObjID = data.parentObjID;
        this.formStructureData = {};//表单结构信息
        this.isShowButton = true;
        this.isTabs= false;//标识是否渲染了isTabs（页面选项卡）
        this.tabsMap = new Map();//存储已渲染的tabs对象
        this.cutStepsMap = new Map();//存储已渲染的cutSteps对象
        this.pageID = data.pageID;
        this.parentObj=fullMap.getObj(data.pageID);
        this.pkFieldName='';
        this.formValueArray = [];
        this.layoutFileUrl='';
        this.layoutHtml='';
        this.formData=data.formData
        fullMap.push(this.getObjID(),this);
        if(util.isNull(fullMap.getObj('isFirstNewForm'))){
            fullMap.getObj('mask').show('正在渲染表单...',1500)
            fullMap.push('isFirstNewForm',"false")
        }
    }
    closeButton() {
        this.isShowButton = false;
    }
    setFormShowType(formShowType) {
        this.formShowType = formShowType;
    }
    getFormShowType() {
        return this.formShowType;
    }
    getObjID() {
        return this._objID;
    }
    getFormMap() {
        return this.formMap;
    }
    getData() {
        return this.data;
    }
    //自定义布局模板
    renderByCustomLayout() {
        let that = this;
        return new Promise((resolve, reject) => {
            let htmlTemplate=`
            <div class="card mb-3">
            <h6 class="card-header">${that.formStructureData.formInfo.form_name}</h6>
            <div style="padding: 0.1rem;" class="" id="${that.getObjID()}">
            </div></div>`;
            document.getElementById(that.parentObjID).insertAdjacentHTML("beforeEnd", htmlTemplate);
            let layoutHtml = that.layoutHtml;//layoutHtml
            layoutHtml = layoutHtml.replace('${form_title}', that.formStructureData.formInfo.form_name);
            layoutHtml=`<div id="${that.parentObjID}layout">${layoutHtml}</div>
                        <div id="${that.parentObjID}default" style="display: none"></div>`
            document.getElementById(that.parentObjID).insertAdjacentHTML("beforeEnd", layoutHtml);
            that.eleParentObjID = that.parentObjID;
            //渲染按钮
            if (that.isShowButton) {
                that.formShowButtons = new formButtons(that.formStructureData.formInfo.buttonsInfo);
                that.formShowButtons.render();
                that.formMap.set('buttons', that.formShowButtons);
            }
            that.kind='custom';
            let fUtil=new formUtil(that);
            fUtil.renderInput().then(()=>{
                resolve();
            });
        })
    }
    init() {
        let that = this;
        if(!util.isNull(that.formData)){
            return new Promise((resolve, reject) => {
                that.formStructureData = that.formData;
                that.closeButton()
                resolve();
            })

        }
        let code = that.code;
        let obj={url:config.getConfigJson().metaUrl,params:code,isClientCache:true}
        obj.errorCallback= (response)=>{
            that.formStructureData=null;
        }
        return httpUtil.post(obj, (response)=>{
            that.formStructureData = response.data.data.form;
            that.buttons = response.data.data.form.formButton;
            that.pkFieldName = response.data.data.ds.ds_pk_id;
            let buttonsInfo = { buttons: that.buttons, parentObjID: that.getObjID(), formMap: that.formMap }
            that.formStructureData.formInfo['buttonsInfo'] = buttonsInfo;
            that.layoutFileUrl=response.data.data.form.formInfo.layout_info;
        });
    }
    render() {
        let that = this;
        return new Promise((resolve, reject) => {
            if(util.isNull(that.formData)&&that.code.formCode==''){
                that.renderThenFunc=function (){
                    khcToastr.showErrorMessage('未设置formCode，无法渲染表单。')
                }
                that.renderThenFunc();
                return ;
                resolve();
            }
            that.init().then(() => {
                if(util.isNull(that.formStructureData)){
                    return ;
                }
                that.loadScript(()=>{
                    if (that.layoutFileUrl != null && that.layoutFileUrl.length > 0) {
                        if (that.layoutFileUrl && that.layoutFileUrl.endsWith('.lay')) {
                            let request = new XMLHttpRequest();
                            request.open("get", that.layoutFileUrl);/*设置请求方法与路径*/
                            request.send(null);/*不发送数据到服务器*/
                            request.onload =  () =>{/*XHR对象获取到返回信息后执行*/
                                if (request.status == 200) {/*返回状态为200，即为数据获取成功*/
                                    that.layoutHtml = request.responseText;
                                }
                                if (that.layoutHtml != null && that.layoutHtml.length > 0) {
                                    that.renderByCustomLayout().then(() => {
                                        that.clearValue();//clear后 赋予默认值
                                        resolve();
                                    });
                                } else {
                                    resolve();
                                }
                            }
                        } else {
                            that.layoutHtml=util.toOldChar(that.layoutFileUrl);
                            if (that.layoutHtml != null && that.layoutHtml.length > 0) {
                                that.renderByCustomLayout().then(() => {
                                    that.clearValue();//clear后 赋予默认值
                                    resolve();
                                });
                            } else {
                                resolve();
                            }
                        }

                    } else {
                        that.renderDetail().then(() => {
                            that.clearValue();//clear后 赋予默认值
                            resolve();
                        });
                    }
                });
            });
        })
    }
    //渲染表单细节（不是查询详情表单和showDetail没关系，不要被命名误解了）
    renderDetail() {
        return new Promise((resolve, reject) => {
            let that=this;
            let titleFontSize=util.getFontSizeByLevel(6);
            let footerHtml=``
            if(that.khcModalForForm==null||that.khcModalForForm==undefined){//如果khcModalForForm为空则提前生成底部div
                footerHtml=`<div id="${that.parentObjID}_footer" class="card" style="display: none;"></div>`
            }
            let htmlTemplate=`
            <div class="card mb-3 pb-3">
            <h6 class="card-header pb-2 pt-2" id="${that.getObjID()}title" style="font-size: ${titleFontSize}">${that.formStructureData.formInfo.form_name}</h6>
            <div style="padding: 0.1px;" class="" id="${that.getObjID()}">
            </div>
            ${footerHtml}</div>`;
            document.getElementById(that.parentObjID).insertAdjacentHTML("beforeEnd", htmlTemplate);
            let buttonShowType=that.formStructureData.formInfo.form_button_show_type;
            if (that.isShowButton) {
                that.formShowButtons = new formButtons(that.formStructureData.formInfo.buttonsInfo);
                //渲染按钮
                if (that.isShowButton&&(buttonShowType=='header_show'||buttonShowType=='header_footer_show')) {
                    that.formShowButtons.render();
                    that.formMap.set('buttons', that.formShowButtons);
                }
            }
            that.eleParentObjID=that.getObjID();
            let fUtil=new formUtil(that);
            if(that.renderBeforeFunc!=undefined){
                that.renderBeforeFunc()
            }
            //渲染表单的各元素
            fUtil.renderInput().then(()=>{
                $('[data-toggle="tooltip"]').tooltip();//tooltip 插件
                $('[data-toggle="popover"]').popover({html:true});//popover 弹出框组件
                if(that.isShowButton&&(buttonShowType=='footer_show'||buttonShowType=='header_footer_show')){
                    that.formShowButtons.renderFooterButton();//渲染底部按钮
                    that.formMap.set('buttons', that.formShowButtons);
                }
                resolve();
            })
        })


    }
    setRenderBefore(callback){
        this.renderBeforeFunc = callback;
    }

    setSaveBefore(callback) {//saveBeforeFunc必须要有返回值{boolean}true则继续，false则终止
        this.saveBeforeFunc = callback;
    }
    setSaveAfter(callback) {
        this.saveAfterFunc = callback;
    }
    //保存后执行一些默认的操作，比如菜单或部门保存后自动刷新左侧树
    runDefaultFunc(){
        let that=this;
        let pageObj=fullMap.getObj(that.pageID);//获取page对象。如果是模态框，则page对象为空
        if(pageObj!=null){
            let queryComponent=pageObj.queryComponent
            if(queryComponent!=undefined&&queryComponent.treeView!=null){
                let code={ version: '1.0.0', dsCode: queryComponent.code.dsCode, formCode: queryComponent.code.formCode,queryCode: queryComponent.code.queryCode };
                let responseKey=JSON.stringify(code)
                //删除缓存的组件数据，因为tree字典是和组件信息放一起的，刷新会重新去缓存取出渲染，所以要清除，刷新时取不到值则会走api请求最新
                fullMap.push(responseKey,undefined);
                let oldNodes=queryComponent.treeView.getSelectedNodes();
                queryComponent.treeView.refreshTreeValue(oldNodes);
            }
        }
    }
    runSaveAfter() {
        if(this.saveAfterFunc!=undefined){
            this.saveAfterFunc();
        }
    }
    setNewData(content) {
        this.content = content;
    }
    getNewData() {
        return this.content;
    }
    getFormValue(){
        let that=this;
        let formValue = {};
        if(that.formMap.size==0)return formValue;
        for (let i = 0; i < that.formStructureData.formData.length; i++) {
            let objData = that.formStructureData.formData[i];
            if(that.formMap.get(objData.name).isValue){
                if (objData.show_type != 'file'&&objData.show_type == 'textarea') {//这个后续也改为配置的，暂时硬编码
                    formValue[objData.name] = util.toSafe(that.formMap.get(objData.name).getValue())
                } else {
                    formValue[objData.name] = that.formMap.get(objData.name).getValue()
                }
            }
        }
        return formValue;
    }
    saveData(isShowMask=true) {
        let that=this;
        let code = that.code;
        let formShowType = that.getFormShowType();
        let formValue = {};
        let isPass = true;
        let toTopObj=null;//滚到第一个元素
        for (let i = 0; i < that.formStructureData.formData.length; i++) {
            let objdata = that.formStructureData.formData[i];
            //去掉虚拟字段
            if (that.formMap.get(objdata.name).isValue) {
                if (objdata.show_type!='hidden'&&that.formMap.get(objdata.name).validate() == false) {
                    isPass = false;
                    if(toTopObj==null){
                        toTopObj=that.formMap.get(objdata.name);
                    }
                    //如果是自定义模板判断第一个不符合条件就退出
                    if(objdata.data.kind=='custom'){
                        break;
                    }
                }
                if (objdata.show_type != 'file'&&objdata.show_type == 'textarea') {
                    formValue[objdata.name] = util.toSafe(that.formMap.get(objdata.name).getValue())
                } else {
                    formValue[objdata.name] = that.formMap.get(objdata.name).getValue()
                }
            }else if(objdata.show_type =='childPage'){
                if (that.formMap.get(objdata.name).validate() == false) {//子表空校验
                    if(toTopObj==null){
                        toTopObj=that.formMap.get(objdata.name);
                    }
                    isPass = false;
                    khcToastr.showErrorMessage({msg:objdata.data.label_name+' 子表不能为空'});
                }
                let tableViewComponent=that.formMap.get(objdata.name).pageObj.queryComponent.tableView;
                if ((tableViewComponent.tUtil!=null&&tableViewComponent.isEditTableData())) {//子表列表编辑时数据修改了提示修改信息。
                    if(toTopObj==null){
                        toTopObj=that.formMap.get(objdata.name);
                    }
                    isPass = false;
                    khcToastr.showErrorMessage({msg:'子表：'+objdata.data.label_name+' 数据有改动，请先保存'});
                }
            }
        }
        if (isPass) {
            if(that.saveBeforeFunc!=undefined){
                let isSave=that.saveBeforeFunc();
                if(typeof isSave=='boolean'){
                    if(!isSave)return ;
                }else{
                    khcAlert.showSystemError('saveBeforeFunc未设置返回指定类型（boolean）')
                    return ;
                }
            }
            if(isShowMask)fullMap.getObj('mask').show('正在保存...')
            let params = that.getSaveParams(formValue);
            let obj={url:config.getConfigJson().saveUrl,params:params}
            httpUtil.post(obj, (response)=>{
                if(response.data.hasOwnProperty('data')&&!util.isNull(response.data.data)){
                    that.saveOneData=response.data.data.saveData[0];
                }
                if(isShowMask)fullMap.getObj('mask').hide();
                if(isShowMask)khcAlert.showSuccessMessage('保存成功')
                that.oldEditData=JSON.parse(JSON.stringify(that.getFormValue()));
                that.runDefaultFunc();
                that.runSaveAfter();
            })
        } else {
            if(that.layoutFileUrl=='null'||that.layoutFileUrl.length==0){
                khcToastr.showErrorMessage({msg:'请按提示填写内容'});
            }
            if(toTopObj!=null && toTopObj.eleId!=''&&that.formShowType=='page'){//对象不为空，并且formShowType值是page
                let componentObj=that.tabsMap.get(toTopObj.data.renderParentObjID)
                if(!util.isNull(componentObj)){//上级对象是tabs，如果有多个tabs需要切回当前的tabs
                    componentObj.activeShow();
                    util.toTops({id:toTopObj.eleID,isFocus:true})
                }else{
                    util.toTops({id:toTopObj.eleID,isFocus:true})
                }

            }
        }
    }
    /**
     * 渲染value
     * @param content 数据体
     */
    renderValue(content) {
        return new Promise((resolve, reject)=>{
            let that=this;
            let eleMap = that.getFormMap();
            let renderValueSource=that.formStructureData.formInfo.render_value_source
            if(renderValueSource=='1'&&!util.isNull(content[that.pkFieldName])){
                let params=util.clone(that.code);
                params.pkId = content[that.pkFieldName];
                let obj={url:config.getConfigJson().queryOneUrl,params:params}
                httpUtil.post(obj,(response)=>{
                    if (response.data.status == 'ok') {
                        let content = response.data.data;
                        for (let key in content) {
                            if(util.isNull(eleMap.get(key))){
                                if(config.getConfigJson().logLevel=='debug') console.log('（警告）字段名：'+key+' 未在表单组件同步配置')
                                continue
                            };
                            eleMap.get(key).setValue(content[key])
                        }
                    }
                    resolve();
                })
            }else{
                for (let key in content) {
                    if(util.isNull(eleMap.get(key))){
                        if(config.getConfigJson().logLevel=='debug') console.log('（警告）字段名：'+key+' 未在表单组件同步配置')
                        continue
                    };
                    eleMap.get(key).setValue(content[key])
                }
                resolve();
            }
        })
    }
    clearValue() {
        let that=this;
        let js_file=that.formStructureData.formInfo.js_file;
        let jsClearValue=that.formStructureData.formInfo.js_clear_value;
        if(!util.isNull(js_file)&&(!util.isNull(jsClearValue))&&jsClearValue=='clearValue'){
            fullMap.push(that.getObjID(),that);
            let jsonConfig={objID:that.getObjID(),button_method:'clearValue'}
            util.import2023(js_file,jsonConfig);
        }else{
            for (let key of that.formMap.keys()) {
                let eleObj = that.formMap.get(key)
                let defaultValue=eleObj.data.default_value;
                if (eleObj.type == 'file'&&util.isNull(defaultValue)) {
                    eleObj.setValue([]);
                } else {
                    eleObj.setValue(defaultValue);
                }
            }
            //clear后需判断是否为子表，如果是需把page_parent_uuid set回去。
            if(!util.isNull(that.code)){
                if(pageInfoMap.getObj(that.code.queryCode)!=undefined&&that.getFormMap().get('page_parent_uuid')!=undefined){
                    that.getFormMap().get('page_parent_uuid').setValue(pageInfoMap.getObj(that.code.queryCode).page_parent_uuid)
                }
            }
        }
        fullMap.push(that.getObjID(), that);//将最新的对象防至fullMap里
    }
    initValidateText(){//重置提示信息，（在测试时发现，新增选择保存后会提示相应的不符合条件信息，此时取消表单，编辑其他数据时，表单还会存在新增时的不符合信息所以要重置一下）
        let that=this;
        for (let key of that.formMap.keys()) {
            let eleObj = that.formMap.get(key)
            if(eleObj.isValue){//重置提示
                eleObj.validateText({isShow:false,type:eleObj.data.kind});
            }
        }
    }
    /**
     * 新增时表单的调整（如仅编辑展示，或一些需要提前录入的字段）
     */
    formCreate() {
        let that=this;
        that.initValidateText();
        let eleMap = that.getFormMap();
        that.initEleMapForm('create');
        eleMap.forEach( (obj,key)=>{
            let timeout=0;
            if(obj.pageObj==null){//如果子表对象为空是因为子表还没渲染就调用formEdit,设置一个延迟时间
                timeout=2000
            }
            if(obj.type=='childPage'){
                let uuid=eleMap.get('uuid').getValue();
                if(util.isNull(uuid)){
                    uuid=util.getUUID();
                }
                eleMap.get('uuid').setValue(uuid);//因为是新增，表单数据还是空的，需要生成一个uuid
                setTimeout( ()=>{//如果是子表需要将主表的uuid传给子表当父uuid
                    pageInfoMap.push(obj.pageObj.queryCode.code.queryCode,{"page_parent_uuid":uuid,"pageCode":obj.pageObj.pageCode});
                    obj.pageObj.queryComponent.getTableObj().refresh();
                },timeout)
            }
            if(obj.type=='page'||obj.type=='childPage'||obj.type=='selectPage'){
                setTimeout( ()=>{
                    document.getElementById(obj.pageObj.queryComponent.getTableObj().getObjID()).setAttribute("style","border: 0px;");
                },timeout)
            }
        })
        if(that.layoutFileUrl.length==0){//自定义布局不控制，如果使用自定义布局，有隐藏的元素需要重新展示请在扩展js控制
            eleMap.forEach( (obj,key)=>{
                if(obj.data.field_show_type=='editShow'||obj.data.field_show_type=='createAndEditHide'){
                    if(obj.data.show_type!='hidden'){
                        obj.hide();
                    }
                }else if(obj.data.field_show_type=='createAndEditShow'){
                    if(obj.data.show_type!='hidden'){
                        obj.show();
                    }
                }
                //表单含tree类型的则不予弹出不然会和弹出框冲突。
                if(obj.type=='tree'&&!util.isNull(that.pageID)){
                    let pId=that.pageID;
                    let formPage=fullMap.getObj(pId);
                    if(formPage.queryComponent!=undefined){//如果是pageForm则没有queryComponent
                        let queryMap=formPage.queryComponent.getQueryMap();
                        let queryTree=queryMap.get(obj.data.name)
                        if(queryTree!=undefined){//tree类型做自动填充（不等于undefined说明生成了tree）
                            obj.setValue(queryTree.getValue())
                        }
                    }
                }
            })
        }
        //自动填充用户信息
        let user=that.formStructureData.user;
        for (let key in user) {
            if(eleMap.get(key)!=null){
                eleMap.get(key).setValue(user[key])
            }
        }
        let buttons=eleMap.get('buttons');
        let buttonShowType=that.formStructureData.formInfo.form_button_show_type;
        if(!util.isNull(buttons)){
            for (let i = 0; i < buttons.data.buttons.length; i++) {
                let buttonEle;
                if (that.isShowButton&&(buttonShowType=='header_show'||buttonShowType=='header_footer_show')) {
                    buttonEle=document.getElementById(buttons.objID+'_header_button').querySelector('button[name="' + buttons.data.buttons[i].button_name + '"]');
                }
                if(that.isShowButton&&(buttonShowType=='footer_show'||buttonShowType=='header_footer_show')){
                    buttonEle=document.getElementById(buttons.objID+'_footer_button').querySelector('button[name="' + buttons.data.buttons[i].button_name + '"]');
                }
                if(buttons.data.buttons[i].button_show_type.indexOf('create_show')==-1){
                    buttonEle.style.display='none';//隐藏
                }else{
                    buttonEle.style.display='';//展示
                }
                //todo footer_button也需要校验
            }
            //如果是新增表单，则隐藏所有工作流按钮
            for (let i = 0; i < buttons.bpmButtonNameArray.length; i++) {
                let buttonEle=document.getElementById(buttons.objID+'_header_button').querySelector('button[name="' + buttons.bpmButtonNameArray[i] + '"]');
                buttonEle.style.display='none';//隐藏
                //todo footer_button也需要校验
            }
        }
        /*if( buttons.data.buttons.length==0){
            khcToastr.showErrorMessage('未生成表单按钮，请前往form组件，按钮维护入口进入生成')
        }*/
        if(that.formStructureData.formInfo.is_bpm_model=='Y'){
            window.onscroll= ()=>{
                let buttonsHtmlObj=document.getElementById(buttons.objID);
                if(buttonsHtmlObj!=null){
                    if(buttons.data.buttons.length>0){
                        //滚动条高度+视窗高度 = 可见区域底部高度
                        let visibleBottom = window.scrollY + document.documentElement.clientHeight;
                        //可见区域顶部高度
                        let visibleTop = window.scrollY;
                        let buttonEle=document.getElementById(buttons.objID+'_header_button').querySelector('button[name="' + buttons.data.buttons[0].button_name + '"]');
                        let centerY = buttonEle.offsetTop+(buttonEle.offsetHeight/2)+120;//加120高度
                        if(centerY>visibleTop&&centerY<visibleBottom){
                            for (let i = 0; i < buttons.data.buttons.length; i++) {
                                let buttonEle=document.getElementById(buttons.objID+'_header_button').querySelector('button[name="' + buttons.data.buttons[i].button_name + '"]');
                                if(buttonEle.style.display==''){
                                    buttonEle.style.position='';
                                    buttonEle.style.top='';
                                    buttonEle.style.zIndex='';
                                }
                            }
                        }else{
                            let auto=1
                            for (let i = 0; i < buttons.data.buttons.length; i++) {
                                let buttonEle=document.getElementById(buttons.objID+'_header_button').querySelector('button[name="' + buttons.data.buttons[i].button_name + '"]');
                                if(buttonEle.style.display==''){
                                    let buttonTop=10+auto*45;
                                    auto++;
                                    buttonEle.style.position='fixed';
                                    buttonEle.style.top=buttonTop+'px';
                                    buttonEle.style.left='88%';
                                    buttonEle.style.zIndex=99;
                                }
                            }
                        }
                    }
                }
            }
        }
        let jsPath=that.formStructureData.formInfo.js_file;
        if(!util.isNull(jsPath)){
            let formEditMethodName=that.formStructureData.formInfo.form_create;
            if(util.isNull(formEditMethodName))formEditMethodName='fCreate';
            /*util.import(jsPath,that.getObjID(),formEditMethodName)*/
            let jsonConfig={objID:that.getObjID(),button_method:formEditMethodName,"formType":"create"}
            util.import2023(jsPath,jsonConfig);
        }
    }
    formEdit() {
        let that=this;
        that.initValidateText();
        let eleMap = that.getFormMap();
        that.initEleMapForm('edit');
        eleMap.forEach( (obj,key)=>{
            let timeout=0;
            if(obj.pageObj==null){//如果子表对象为空是因为子表还没渲染就调用formEdit,设置一个延迟时间
                timeout=2000
            }
            if(obj.type=='childPage'){
                let uuid=eleMap.get('uuid').getValue();
                if(util.isNull(uuid)){
                    uuid=util.getUUID();
                }
                eleMap.get('uuid').setValue(uuid);//一般编辑时肯定会有uuid了，但在toEditPage时可能没有，这里校验一下，没有赋值一个新的uuid
                setTimeout( ()=>{
                    pageInfoMap.push(obj.pageObj.queryCode.code.queryCode,{"page_parent_uuid":uuid,"pageCode":obj.pageObj.pageCode});
                    obj.pageObj.queryComponent.getTableObj().refresh();
                    /*
                    //隐藏分页信息
                    obj.pageObj.queryComponent.getTableObj().hidePageInfoWithPage();
                    obj.pageObj.queryComponent.getTableObj().hidePageInfoOfSize();
                    obj.pageObj.queryComponent.getTableObj().hideChangePageSizeDiv();*/
                },timeout);
            }
            if(obj.type=='page'||obj.type=='childPage'||obj.type=='selectPage'){
                setTimeout( ()=>{
                    document.getElementById(obj.pageObj.queryComponent.getTableObj().getObjID()).setAttribute("style","border: 0px;");
                },timeout);
            }
        })
        if(that.layoutFileUrl.length==0){//自定义布局不控制，如果使用自定义布局，有隐藏的元素需要重新展示请在扩展js控制
            eleMap.forEach( (obj,key)=>{
                if(obj.data.field_show_type=='editHide'){
                    if(obj.data.show_type!='hidden'){
                        obj.hide();
                    }
                }else if(obj.data.field_show_type=='editShow'||obj.data.field_show_type=='createAndEditShow'){
                    if(obj.data.show_type!='hidden'){
                        obj.show();
                    }
                }
            })
        }
        let buttons=eleMap.get('buttons');
        let buttonShowType=that.formStructureData.formInfo.form_button_show_type;
        if(buttons!=undefined){
            for (let i = 0; i < buttons.data.buttons.length; i++) {
                let button=buttons.data.buttons[i]
                let headerButtonEle;
                let footerButtonEle;
                if (that.isShowButton&&(buttonShowType=='header_show'||buttonShowType=='header_footer_show')) {
                    headerButtonEle=document.getElementById(buttons.objID+'_header_button').querySelector('button[name="' + buttons.data.buttons[i].button_name + '"]');
                }
                if(that.isShowButton&&(buttonShowType=='footer_show'||buttonShowType=='header_footer_show')){
                    footerButtonEle=document.getElementById(buttons.objID+'_footer_button').querySelector('button[name="' + buttons.data.buttons[i].button_name + '"]');
                }
                if(!util.isNull(button.row_button_show_func)){
                    let content=that.getFormValue()
                    let myselfFuncStr=util.toOldChar(button.row_button_show_func);
                    content.util=util;
                    if (!util.executeDynamicCode(myselfFuncStr,content)){//自定义校验不通过，不渲染按钮
                        if(headerButtonEle)headerButtonEle.style.display='none';//隐藏
                        if(footerButtonEle)footerButtonEle.style.display='none';//隐藏
                        continue;
                    }
                }
                if(buttons.data.buttons[i].button_show_type.indexOf('edit_show')==-1){
                    if(headerButtonEle)headerButtonEle.style.display='none';//隐藏
                    if(footerButtonEle)footerButtonEle.style.display='none';//隐藏
                }else{
                    if(headerButtonEle)headerButtonEle.style.display='';//展示
                    if(footerButtonEle)footerButtonEle.style.display='';//展示
                }
            }
        }
        let jsPath=that.formStructureData.formInfo.js_file;
        if(!util.isNull(jsPath)){
            let formEditMethodName=that.formStructureData.formInfo.form_edit;
            if(util.isNull(formEditMethodName))formEditMethodName='fEdit';
            /*util.import(jsPath,that.getObjID(),formEditMethodName)*/
            let jsonConfig={objID:that.getObjID(),button_method:formEditMethodName,"formType":"edit"}
            util.import2023(jsPath,jsonConfig);
        }
    }
    formDetail() {
        let that=this;
        that.initValidateText();
        let eleMap = that.getFormMap();
        that.initEleMapForm('detail');
        eleMap.forEach( (obj,key)=>{
            let timeout=0;
            if(obj.pageObj==null){//如果子表对象为空是因为子表还没渲染就调用formEdit,设置一个延迟时间
                timeout=2000
            }
            if(obj.type=='childPage'){
                let uuid=eleMap.get('uuid').getValue();
                if(util.isNull(uuid)){
                    uuid=util.getUUID();
                }
                eleMap.get('uuid').setValue(uuid);//一般编辑时肯定会有uuid了，但在toEditPage时可能没有，这里校验一下，没有赋值一个新的uuid
                setTimeout( ()=>{
                    pageInfoMap.push(obj.pageObj.queryCode.code.queryCode,{"page_parent_uuid":uuid,"pageCode":obj.pageObj.pageCode});
                    obj.pageObj.queryComponent.getTableObj().refresh();
                    /*
                    //隐藏分页信息
                    obj.pageObj.queryComponent.getTableObj().hidePageInfoWithPage();
                    obj.pageObj.queryComponent.getTableObj().hidePageInfoOfSize();
                    obj.pageObj.queryComponent.getTableObj().hideChangePageSizeDiv();*/
                },timeout);
            }
            if(obj.type=='page'||obj.type=='childPage'||obj.type=='selectPage'){
                setTimeout( ()=>{
                    document.getElementById(obj.pageObj.queryComponent.getTableObj().getObjID()).setAttribute("style","border: 0px;");
                },timeout);
            }
        })
        if(that.layoutFileUrl.length==0){//自定义布局不控制，如果使用自定义布局，有隐藏的元素需要重新展示请在扩展js控制
            eleMap.forEach( (obj,key)=>{
                if(obj.data.field_show_type=='editHide'){
                    if(obj.data.show_type!='hidden'){
                        obj.hide();
                    }
                }else if(obj.data.field_show_type=='editShow'||obj.data.field_show_type=='createAndEditShow'){
                    if(obj.data.show_type!='hidden'){
                        obj.show();
                    }
                }
            })
        }
        let buttons=eleMap.get('buttons');
        let buttonShowType=that.formStructureData.formInfo.form_button_show_type;
        if(buttons!=undefined){
            for (let i = 0; i < buttons.data.buttons.length; i++) {
                let button=buttons.data.buttons[i]
                if(!util.isNull(button.row_button_show_func)){
                    let content=that.getFormValue()
                    let myselfFuncStr=util.toOldChar(button.row_button_show_func);
                    content.util=util;
                    if (!util.executeDynamicCode(myselfFuncStr,content)){//自定义校验不通过，不渲染按钮
                        continue;
                    }
                }
                let buttonEle;
                if (that.isShowButton&&(buttonShowType=='header_show'||buttonShowType=='header_footer_show')) {
                    buttonEle=document.getElementById(buttons.objID+'_header_button').querySelector('button[name="' + buttons.data.buttons[i].button_name + '"]');
                }
                if(that.isShowButton&&(buttonShowType=='footer_show'||buttonShowType=='header_footer_show')){
                    buttonEle=document.getElementById(buttons.objID+'_footer_button').querySelector('button[name="' + buttons.data.buttons[i].button_name + '"]');
                }
                if(buttons.data.buttons[i].button_show_type.indexOf('create_show')==-1){
                    buttonEle.style.display='none';//隐藏
                }else{
                    buttonEle.style.display='';//展示
                }
                //todo footer_button也需要校验
            }
        }
        let jsPath=that.formStructureData.formInfo.js_file;
        if(!util.isNull(jsPath)){
            let formEditMethodName=that.formStructureData.formInfo.form_detail;
            if(util.isNull(formEditMethodName))formEditMethodName='fDetail';
            /*util.import(jsPath,that.getObjID(),formEditMethodName)*/
            let jsonConfig={objID:that.getObjID(),button_method:formEditMethodName,"formType":"detail"}
            util.import2023(jsPath,jsonConfig);
        }
        if(that.renderAfterFunc!=undefined){
            that.renderAfterFunc()
        }
    }
    //表单渲染后执行的一些操作。
    initEleMapForm(type){
        let that=this;
        let eleMap = that.getFormMap();
        let searchFieldNameArray = [];
        if(type=='create'&&that.parentObj!=null) {
            let searchFieldArray = that.parentObj['searchFieldArray'];
            if(searchFieldArray!=undefined){
                for (let i = 0; i < searchFieldArray.length; i++) {
                    searchFieldNameArray.push(searchFieldArray[i]['childFieldName'])
                }
            }
        }
        eleMap.forEach((obj,key)=>{
            if(key!='buttons'&&key!='work_order_opinion'){
                let func='';
                if(type=='create'){
                    func=obj.data.f_create_func;
                }
                if(type=='edit'){
                    func=obj.data.f_edit_func;
                }
                if(type=='detail'){
                    func=obj.data.f_detail_func;
                }
                if(!util.isNull(func)){
                    let myselfFuncStr=util.toOldChar(func);
                    util.executeDynamicCode(myselfFuncStr,{eleObj:obj})
                }
            }
            let autoTemplate=obj.data['auto_create_value_template'];
            if(type=='create'&&obj.data['is_auto_create_value']=='Y'&&!util.isNull(autoTemplate)){
                let currentDate = new Date();
                let year = currentDate.getFullYear();
                let lastTwoDigitsOfYear = year.toString().slice(-2);// 获取年份的后两位数字
                let month = currentDate.getMonth() + 1; // 月份是从0开始的，所以需要加1
                month=month < 10 ? '0' + month : month; //1~9补0
                let day = currentDate.getDate();
                day=day < 10 ? '0' + day : day; //1~9补0
                let hours = currentDate.getHours();
                hours=hours < 10 ? '0' + hours : hours; //1~9补0
                let minutes = currentDate.getMinutes();
                minutes=minutes < 10 ? '0' + minutes : minutes; //1~9补0
                let random1 = util.getRandomInt(0,9);
                let random2 = util.getRandomInt(10,99);
                let random3 = util.getRandomInt(100,999);
                let random4 = util.getRandomInt(1000,9999);
                let random5 = util.getRandomInt(10000,99999);
                autoTemplate = autoTemplate.replace(/\${yyyy}/g, year);
                autoTemplate = autoTemplate.replace(/\${yy}/g, lastTwoDigitsOfYear);
                autoTemplate = autoTemplate.replace(/\${MM}/g, month);
                autoTemplate = autoTemplate.replace(/\${dd}/g, day);
                autoTemplate = autoTemplate.replace(/\${HH}/g, hours);
                autoTemplate = autoTemplate.replace(/\${mm}/g, minutes);
                autoTemplate = autoTemplate.replace(/\${random1}/g, random1);
                autoTemplate = autoTemplate.replace(/\${random2}/g, random2);
                autoTemplate = autoTemplate.replace(/\${random3}/g, random3);
                autoTemplate = autoTemplate.replace(/\${random4}/g, random4);
                autoTemplate = autoTemplate.replace(/\${random5}/g, random5);
                obj.setValue(autoTemplate)
            }
            if(searchFieldNameArray.length>0&&searchFieldNameArray.includes(obj.data['name'])){
                let fieldName=obj.data['name'];
                let queryFieldNameObj=that.parentObj.queryComponent.queryMap.get(fieldName)
                if(util.isNull(queryFieldNameObj)){
                    khcAlert.showSystemError('检测到'+fieldName+'关联字段未设置为查询，请前往查询组件设置')
                    return ;
                }
                if(!util.isNull(queryFieldNameObj.getValue())){
                    obj.setValue(queryFieldNameObj.getValue());
                }else{
                    pageInfoMap.getObj(that.code.queryCode)
                }
            }
        })
    }
    //初始化表单，每次新增和编辑结束后就初始化表单
    initForm(){
        let that=this;
        //如果主键值不为空，那么当前的值应该是编辑模式残留的值，所以清空form里的值
        if(!util.isNull(that.getFormValue()[that.pkFieldName])){
            that.clearValue();
        }
        //初始化表单属性
        that.formMap.forEach((obj,key)=>{
            obj.init();
        })
    }
    //按钮信息，用于请求时后端校验身份标识
    setButtonParams(params){
        let that=this;
        that.buttonParams=params;
    }
    //获取请求Params参数，也可直接用code但code参数太多了，所以单独写一个方法，只获取用到的参数即可
    getSaveParams(formValue){
        let that=this;
        let code = that.code;
        let formCode = code.formCode;
        let queryCode = code.queryCode;
        let dsCode = code.dsCode;
        let actionParams = code.actionParams;
        let version = code.version;
        that.formValueArray=[];
        that.formValueArray.push(formValue)
        let params = { "version": version, "dsCode": dsCode, "formCode": formCode,"queryCode": queryCode, "saveData": that.formValueArray ,"actionParams": actionParams}
        //这里可以合并button参数
        if(!util.isNull(that.buttonParams)){
            params=util.mergeObject(that.buttonParams,params);
        }
        let pageObj=fullMap.getObj(that.pageID);//获取page对象。如果是模态框，则page对象为空
        if(pageObj==null||pageObj==undefined)return params;
        let parentFormObj=fullMap.getObj(pageObj.parentFormObjID);//如果是表单里套page页面的则set page_parent_uuid,以便后端进行一些特殊处理
        if(parentFormObj!=null){
            let formValue=parentFormObj.getFormValue()
            params.page_parent_uuid=formValue.page_parent_uuid;
            console.log(params)
        }
        return params;
    }
    /**
     * 对已渲染的组件更新配置
     * @param obj.fieldArray 不能为空 数组 需要更新配置的组件
     * @param obj.isDisabled 可以为空 是否只读
     * @param obj.isClearValue 可以为空 是否清空值
     * @param obj.isShowDiv 可以为空 是否展示组件的div
     * @param obj.isCanNull 可以为空 是否必填
     */
    initEleConfig(obj){
        let eleMap=this.getFormMap()
        for (let i = 0; i < obj.fieldArray.length; i++) {
            if(obj.isDisabled==undefined||obj.isDisabled){
                eleMap.get(obj.fieldArray[i]).setDisabled();
            }else{
                eleMap.get(obj.fieldArray[i]).removeDisabled();
            }
            if(obj.isClearValue){
                eleMap.get(obj.fieldArray[i]).setValue('');
            }
            if(obj.isShowDiv!=undefined){
                if(obj.isShowDiv){
                    eleMap.get(obj.fieldArray[i]).showDiv();
                }else{
                    eleMap.get(obj.fieldArray[i]).hideDiv();
                }
            }
            if(obj.isCanNull!=undefined){
                if(obj.isCanNull){
                    eleMap.get(obj.fieldArray[i]).data.can_null='Y';
                    eleMap.get(obj.fieldArray[i]).refreshCanNull();
                }else{
                    eleMap.get(obj.fieldArray[i]).data.can_null='N';
                    eleMap.get(obj.fieldArray[i]).refreshCanNull();
                }
            }
        }
    }
    initStepsFunc(){
        let that=this;
        let formId=that.getObjID();
        let $form = $('#'+formId+'_cut_steps');
        let $btnFinish = $(`<button id="${formId}-btn-finish" class="btn-finish btn btn-primary d-none mr-2" type="button">完成</button>`);
        // Initialize wizard Docs URL：https://github.com/mstratman/jQuery-Smart-Wizard
        $form.smartWizard({
            autoAdjustHeight: false,
            backButtonSupport: false,
            useURLhash: false,
            showStepURLhash: false,
            keyNavigation: false,
            toolbarSettings: {
                toolbarExtraButtons: [$btnFinish]
            },
        }).on('leaveStep', function(e, anchorObject, stepNumber, stepDirection) {
            // stepDirection === 'forward' :- this condition allows to do the form validation
            // only on forward navigation, that makes easy navigation on backwards still do the validation when going next
            let thatStepNumber=-1;
            let isPass=true;
            for (let i = 0; i < that.formStructureData.formData.length; i++) {
                let objdata = that.formStructureData.formData[i];
                if (objdata.show_type == 'cutSteps') {
                    thatStepNumber++;
                    if(thatStepNumber>stepNumber){
                        break;
                    }
                }
                if(stepNumber==thatStepNumber){
                    let toTopObj=that.formMap.get(objdata.name)
                    if (objdata.show_type!='hidden'&&toTopObj.validate() == false) {
                        isPass=false
                        //如果是自定义模板判断第一个不符合条件就退出
                        if(objdata.data.kind=='custom'){
                            break;
                        }
                    }
                }
            }
            if(!isPass) khcToastr.showErrorMessage({msg:'请按提示填写内容'});
            return isPass;
        }).on('showStep', function(e, anchorObject, stepNumber, stepDirection) {
            let $btn = $form.find(`#${formId}-btn-finish`);

            // Enable finish button only on last step
            if (stepNumber === (that.cutStepsMap.size-1)) {
                $btn.removeClass('d-none');
            } else {
                $btn.addClass('d-none');
            }
        });
        // Click on finish button
        $form.find(`#${formId}-btn-finish`).on('click', function(){
            that.saveData();
            return false;
        });
    }
    //loadJquery
    loadScript(callback){
        let that=this;
        let isMiniColor=false,isQuill=false,isKV=false;
        for (let i = 0; i < that.formStructureData.formData.length; i++) {
            let objData = that.formStructureData.formData[i];
            if (objData.show_type == 'color') isMiniColor=true
            if (objData.show_type == 'editor') isQuill=true
            if (objData.show_type == 'kv') isKV=true
        }
        //防重复加载
        let isLoadFormScriptMiniColor=fullMap.getObj('isLoadFormScript-minicolor');
        let isLoadFormScriptQuill=fullMap.getObj('isLoadFormScript-quill');
        let isLoadFormScriptSortable=fullMap.getObj('isLoadFormScript-sortable');
        util.loadCss('../css/css/segmentedProgressBar.css')
        if(!isMiniColor&&!isQuill&&!isKV){
            callback();
        }else{
            /*if(isMiniColor&&(util.isNull(isLoadFormScriptMiniColor)||isLoadFormScriptMiniColor=='N')){//是否启用取色器组件-minicolor
                util.loadCss('../css/vendor/libs/minicolors/minicolors.css')
                util.loadScript('../css/vendor/libs/minicolors/minicolors.js','text/javaScript',function (){
                    that.loadScript(callback)
                })
                fullMap.push('isLoadFormScript-minicolor','Y');
                return
            }*/
            if(isKV&&(util.isNull(isLoadFormScriptSortable)||isLoadFormScriptSortable=='N')){//是否启用KV键值组件-sortable
                util.loadScript('../css/vendor/libs/sortablejs/sortable.js','text/javaScript',function (){
                    that.loadScript(callback)
                })
                fullMap.push('isLoadFormScript-sortable','Y');
                return
            }
            if(isQuill&&(util.isNull(isLoadFormScriptQuill)||isLoadFormScriptQuill=='N')){//是否启用富文本-quill
                util.loadCss('../css/vendor/libs/quill/css/v2/quill.snow.css')
                util.loadCss('../css/vendor/libs/quill/css/v2/quill-better-table.css')
                util.loadScript('../css/vendor/libs/quill/js/lodash.js','text/javaScript',function (){})
                util.loadScript('../css/vendor/libs/quill/js/lodash.min.js','text/javaScript',function (){
                    util.loadScript('../css/vendor/libs/quill/js/v2/quill.min.js','text/javaScript',function (){
                        util.loadScript('../css/vendor/libs/quill/js/v2/quill-better-table.min.js','text/javaScript',function (){
                            util.loadScript('../css/vendor/libs/quill/js/v2/link/Link.js','module',function (){
                                util.loadScript('../css/vendor/libs/quill/js/v2/image-upload/ImageQuillWatch.js','module',function (){
                                    util.loadScript('../css/vendor/libs/quill/js/v2/file-upload/FileQuillWatch.js','module',function (){
                                        util.loadScript('../css/vendor/libs/quill/js/v2/image-upload/ImageExtend.js','module',function (){
                                            util.loadScript('../css/vendor/libs/quill/js/v2/file-upload/FileExtend.js','module',function (){
                                                util.loadScript('../css/vendor/libs/quill/js/v2/image-resize/image-resize.js','module',function (){
                                                    fullMap.push('isLoadFormScript-quill','Y');
                                                    callback();
                                                })
                                            })
                                        })
                                    })
                                })

                            })
                        })
                    })
                })
            }else{
                callback();
            }
        }
    }

}
export { form }



