<template>
    <div>
      <!--  <Container @click="exportData(1)" class="saveDivs">
            保存模板和JSON
        </Container>
        &lt;!&ndash;<Container @click="saveData()" style="margin-right:30px;">
            保存
        </Container>&ndash;&gt;
        <Container @click="exportData(2)" class="saveDivs">
            预览
        </Container>
        <Container @click="deleteData()" class="saveDivs">
            删除
        </Container>
        <Container @click="gobackList()" class="saveDivs">
            返回列表
        </Container>
        <Modal v-model="modalpreview" fullscreen footer-hide title="页面预览" :styles="{backgroundColor:'#F5F7F9'}">
            <router-view/>
        </Modal>-->
    </div>
</template>

<script>
    import * as components from './style';
    import eventbus from '../../service/eventbus';
    import FileSaver from 'file-saver';
    import Service from "../../service/tool-service";
    import httpLoading from "../../utils/httpLoading";
    import mixUtil from './mixUtil'
    export default {
        components,
        position: 'navbarRight',
        mixins:[mixUtil],
        name: 'save',
        data(){
            return{
                isRerver:false,//note 判断是否被转换了
                jsonObj:{
                    page:{},
                    elements:[]
                },
                modalpreview:false,
                isShowModal:false
            }
        },
        computed: {
            viewportInstances () {
                //note 获取拖拽组件的属性
                let viewprotInstances = this.$store.state.viewport.instances;
                let obj = Object.create(null);
                for (let [k,v] of viewprotInstances) {
                    obj[k] = v;
                }
                return obj;
            },
            applicationState () {
                return this.$store.state.application;
            },
            viewportState () {
                return this.$store.state.viewport;
            },
            componentTree () {
                debugger;
                //note 获取组件树层级
                let _root = this.digui(this.viewportState.rootInstanceKey);
                return [_root][0].children;
            },
            instances () {
                return this.$store.state.viewport.instances;
            },
            formValidatorRules(){
                //note rules校验规则rules的抽取
                debugger;
                let result = _.pickBy(this.viewportInstances,(value)=>{
                    if(value.data.validateArr&&value.data.validateArr.length>0){
                        value.data.validateArr.forEach(function(v,k) {
                            console.log(v); //这样就会分别将name遍历出来,判断有没有校验联动
                            if(v.requireKeyValues&&v.requireKeyValues.length>0){
                                 //
                                v.requireKeyValues.forEach(function(v1,k) {
                                    console.log(v1); //这样就会分别将name遍历出来,判断有没有校验联动
                                    if(v1.values.indexOf(",")==-1){
                                        //note 没找到
                                    }else{
                                        v1.values=v1.values.split(",");
                                    }

                                });
                            }
                        });
                    }
                    return value.data.validateArr&&value.data.validateArr.length>0;
                });
                result = _.mapKeys(result,(value)=>{
                    return value.data.property.prop;
                });
                result = _.mapValues(result,(value)=>{
                    let validateArr = value.data.validateArr.map((value)=>{
                        return _.pickBy(value,(value)=>{
                            return value;
                        })
                    });
                    return validateArr;
                });
                return result;
            }
        },
        methods: {
            randomString(len) {
                len = len || 10;
                var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
                var maxPos = $chars.length;
                var pwd = '';
                for (i = 0; i < len; i++) {
                    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
                }
                return pwd;
            },
            gobackList(){
                this.$router.push({name: 'selectTemplate'})
            },
            async previewData () {
                if(localStorage.getItem("page")&&localStorage.getItem("page")!=null){

                }else{
                    this.$Modal.success({
                        title: "友情提示",
                        content: "请先全局设置！"
                    });
                    return;
                }
                debugger;
                this.isShowModal = true;
                console.log(this.viewportInstances);
                console.log(this.componentTree);
                let pageObj= eval('(' + localStorage.getItem("page") + ')');//JSON.parse(localStorage.getItem("page"));
                console.log(pageObj);
               // if(!pageObj.title)return;
                if(pageObj.title=="上传附件"){
                    let fullModelData = await this.getbusinessData("2-business");
                    pageObj.fullModel = fullModelData.data;
                }else if(pageObj.title=="提交审核"||pageObj.title=="已办结"){
                    let fullModelData = await this.getbusinessData("3-business");
                    pageObj.fullModel.infoAttachment = fullModelData.data.infoAttachment;
                    pageObj.fullModel.timeLineData = fullModelData.data.timeLineData;
                }
                this.jsonObj.page = pageObj;
                this.jsonObj.elements = [];
               /* if(this.isRerver){

                }else{
                    this.componentTree.forEach((item1)=>{
                        if(item1.children){
                            //note 如果存在，继续遍历 最多5级
                            item1.children.forEach((item2)=>{
                                if(item2.children){
                                    //note 如果存在，继续遍历 最多5级
                                    item2.children.forEach((item3)=>{
                                        if(item3.children){
                                            //note 如果存在，继续遍历 最多5级
                                            item3.children.forEach((item4)=>{
                                                if(item4.children){
                                                    //note 如果存在，继续遍历 最多5级
                                                    item4.children.forEach((item5)=>{
                                                        if(item5.children){
                                                            //note 如果存在，继续遍历 最多5级
                                                            item5.children.reverse();
                                                        }
                                                    });
                                                    item4.children.reverse();
                                                }
                                            });
                                            item3.children.reverse();
                                        }
                                    });
                                    item2.children.reverse();
                                }
                            });
                            item1.children.reverse();
                        }
                    });
                    this.componentTree.reverse();
                    this.isRerver=true;
                }*/

                console.log(this.componentTree);

                this.componentTreeFactory(this.componentTree,this.jsonObj.elements);

                console.log(this.jsonObj);
                console.log(JSON.stringify(this.jsonObj));
                if(this.isShowModal){
                    this.modalpreview = true;
                  //  this.jsonObj={"page":{"fullModel":{"templateCache":{"validators":[],"tableArr":[],"selectArr":[],"targetData":["applyName","applyName","sex","sex","nationalDesc","nationalDesc","telPhone","telPhone","graduatedSchool","graduatedSchool","education","education","professionalName","professionalName","marriageAndChildbearingStatus","marriageAndChildbearingStatus","workUnit","workUnit","fileReceivingUnit","fileReceivingUnit","registrationTime","registrationTime","applyCardNumber","applyCardNumber"]},"applyName":"","sex":"","nationalDesc":"","telPhone":"","graduatedSchool":"","education":"","professionalName":"","marriageAndChildbearingStatus":"","workUnit":"","fileReceivingUnit":"","registrationTime":"","applyCardNumber":"","timeLineData":[],"leaderMsg":[],"infoAttachment":[],"state":"","isOut":0,"datetime":[],"address":"","remark":"","accessoryGroupId":"","legalMan":"","legalManTelPhone":"","contactMan":"","setAddress":"","setContent":"","material":""},"title":"null","maxSteps":null},"elements":[{"type":"btns-oprator","data":{"buttons":[{"type":"primary","label":"下一步","click":"nextStepClick"},{"type":"success","label":"办事指南","click":"guideClick"}]}},{"type":"box","data":[{"type":"form-table","data":{"model":"leaderMsg","validator":false,"minRows":1,"width":1000,"disableDelRows":1,"btnMsg":"","placeholder":"","busiId":"","title":"","align":"center","type":"select","columns":[{"type":"select","title":"专职/兼职","label":"","busiId":"","itemsProp":"","width":200,"extend":{"itemWidth":320,"placeholder":"","eventType":""},"itemOptions":[{"label":"兼职","value":"1","extend":{"size":"","disabled":false}},{"label":"专职","value":"2","extend":{"size":"","disabled":false}}]},{"type":"input","title":"资格证书编号","align":"center","placeholder":"","busiId":"","width":200,"rules":{"required":false,"message":"","type":"","trigger":""}},{"type":"input","title":"身份证编号","align":"center","placeholder":"","busiId":"","width":200,"rules":{"required":false,"message":"","type":"","trigger":""}},{"type":"input","title":"从事燃气专业工作年限(年)","align":"center","placeholder":"","busiId":"","width":200,"rules":{"required":false,"message":"","type":"","trigger":""}},{"type":"input","title":"职务及岗位","align":"center","placeholder":"","busiId":"","width":200,"rules":{"required":false,"message":"","type":"","trigger":""}},{"type":"select","title":"文化程度","label":"","busiId":"","itemsProp":"","width":200,"extend":{"itemWidth":320,"placeholder":"","eventType":""},"itemOptions":[{"label":"研究生及以上","value":"1","extend":{"size":"","disabled":false}},{"label":"大学本科","value":"2","extend":{"size":"","disabled":false}},{"label":"大学专科","value":"3","extend":{"size":"","disabled":false}},{"label":"中专","value":"4","extend":{"size":"","disabled":false}},{"label":"高中","value":"5","extend":{"size":"","disabled":false}},{"label":"初中","value":"6","extend":{"size":"","disabled":false}},{"label":"小学","value":"7","extend":{"size":"","disabled":false}},{"label":"其他","value":"8","extend":{"size":"","disabled":false}}]},{"type":"select","title":"性别","label":"","busiId":"","itemsProp":"","width":200,"extend":{"itemWidth":320,"placeholder":"","eventType":""},"itemOptions":[{"label":"男","value":"1","extend":{"size":"","disabled":false}},{"label":"女","value":"2","extend":{"size":"","disabled":false}}]},{"type":"input","title":"姓名","align":"center","placeholder":"","busiId":"","width":200,"rules":{"required":false,"message":"","type":"","trigger":""}}]}},{"type":"form","data":{"validator":false,"rules":{},"extend":{"span":17,"labelWidth":222,"itemWidth":320,"placeholder":"","maxlength":"220","eventType":"","rows":0},"items":[{"type":"input","label":"联系电话/申请人手机","busiId":9,"extend":{"itemWidth":320,"placeholder":"","eventType":"","maxlength":"220"}},{"type":"input","label":"联系人","busiId":18,"extend":{"itemWidth":320,"placeholder":"","eventType":"","maxlength":"220"}},{"type":"input","label":"证件号码","busiId":17,"extend":{"itemWidth":320,"placeholder":"","eventType":"","maxlength":"220"}},{"type":"input","label":"证件类型中文描述","busiId":33,"extend":{"itemWidth":320,"placeholder":"","eventType":"","maxlength":"220"}},{"type":"input","label":"证件类型","busiId":25,"extend":{"itemWidth":320,"placeholder":"","eventType":"","maxlength":"220"}},{"type":"input","label":"姓名/企业名称","busiId":6,"extend":{"itemWidth":320,"placeholder":"","eventType":"","maxlength":"220"}}]}}]}]};
                        let strJson=JSON.stringify(this.jsonObj);
                    console.log("strJson:"+strJson);
                    debugger;
                    this.$store.commit('viewport/setPagePriviewData', this.jsonObj);
                    this.$router.push({name: 'pagePreview'})
                }
            },
            saveData(){
                let pageObj= JSON.parse(localStorage.getItem("page"));
                this.jsonObj.page = pageObj;
                this.jsonObj.elements = [];
                this.componentTreeFactory(this.componentTree,this.jsonObj.elements);
                console.log(this.jsonObj);
                console.log(JSON.stringify(this.jsonObj));
            },
            //note 提示保存全局设置
            sendBusSaveAllInfo(){
                eventbus.$emit("saveAllInfo",{});
            },
            exportData(marker){
                debugger;
               alert(111);
           /*    if(localStorage.getItem("page")&&localStorage.getItem("page")!=null){

                }else{
                    this.$Modal.success({
                        title: "友情提示",
                        content: "请先全局设置！"
                    });
                    return;
                }*/
                debugger;
                console.log(this.componentTree);
               // let pageObj= JSON.parse(localStorage.getItem("page"));
                configPageIde.page.fullModel.templateCache.validators=[];
                this.jsonObj.page = configPageIde.page;
                this.jsonObj.elements = [];
                this.componentTreeFactory(this.componentTree,this.jsonObj.elements);
                let exportJson = {
                    code:0,
                    message:"",
                    data:{

                    }
                };
                let copyObj={
                    data:this.jsonObj
                }
                Object.assign(exportJson, copyObj);
                const data1 = JSON.stringify(exportJson);
                console.log(data1);
                //note 保存模板和json
                let params = {
                    itemNo:localStorage.itemNo,
                    itemStep:localStorage.itemStep
                };
                httpLoading.showLoading("正在提交...");
                //note 这里面要做一个修改，给每一个form 里面添加字段属性，然后把字段的属性放到校验里面去
                let jsonArr2=[];
                let propArr=[];
                let targetArr=[];
                for(let i=0;i<exportJson.data.elements.length;i++) {
                    for (var j = 0; j < exportJson.data.elements[i].data.length; j++) {
                        //判断添加的数组是否为空了
                        if (exportJson.data.elements[i].data[j].type == "form") {
                            let jsonArr = exportJson.data.elements[i].data[j].data.items;
                            let ruleArr = exportJson.data.elements[i].data[j].data.rules;
                            for (let k = 0; k < propArr.length; k++) {
                                for (let m = 0; m < jsonArr.length; m++) {
                                    //判断添加的数组是否为空了
                                    if (propArr[k]["busiId"] === jsonArr[m]["busiId"]) {
                                        jsonArr[m]["prop"] = propArr[k]["busiName"];
                                        delete jsonArr[m]["rules"];
                                    }
                                }
                                for (let n in ruleArr) {
                                    //note 将校验里面的id替换成属性
                                    if (propArr[k]["busiId"] == n) {
                                        ruleArr[propArr[k]["busiName"]] = ruleArr[n];
                                        delete ruleArr[n];
                                    }
                                }
                            }
                        }
                    }
                }
                if(marker==1){
                    //note 保存
                    const data = JSON.stringify(exportJson);
                    const myStr = JSON.stringify(data);
                    console.log("-->"+myStr);
                    let toServerParams = {
                        itemNo:localStorage.itemNo,
                        itemStep:localStorage.itemStep,
                        jsonType:2,
                        jsonStr:data
                    };
                    Service.saveTemplateOrJsonToServer(toServerParams).then((res) => {
                        //note 刚才保存完了json，现在要保持模板
                        this.$store.commit('viewport/saveLocalInstances', {
                        });
                    })
                }else {
                    this.$store.commit('viewport/saveLocalInstances', {
                    });

                    httpLoading.closeLoading();
                    //note 预览
                    this.isShowModal = true;
                    this.modalpreview = true;
                    //  this.jsonObj={"page":{"fullModel":{"templateCache":{"validators":[],"tableArr":[],"selectArr":[],"targetData":["applyName","applyName","sex","sex","nationalDesc","nationalDesc","telPhone","telPhone","graduatedSchool","graduatedSchool","education","education","professionalName","professionalName","marriageAndChildbearingStatus","marriageAndChildbearingStatus","workUnit","workUnit","fileReceivingUnit","fileReceivingUnit","registrationTime","registrationTime","applyCardNumber","applyCardNumber"]},"applyName":"","sex":"","nationalDesc":"","telPhone":"","graduatedSchool":"","education":"","professionalName":"","marriageAndChildbearingStatus":"","workUnit":"","fileReceivingUnit":"","registrationTime":"","applyCardNumber":"","timeLineData":[],"leaderMsg":[],"infoAttachment":[],"state":"","isOut":0,"datetime":[],"address":"","remark":"","accessoryGroupId":"","legalMan":"","legalManTelPhone":"","contactMan":"","setAddress":"","setContent":"","material":""},"title":"null","maxSteps":null},"elements":[{"type":"btns-oprator","data":{"buttons":[{"type":"primary","label":"下一步","click":"nextStepClick"},{"type":"success","label":"办事指南","click":"guideClick"}]}},{"type":"box","data":[{"type":"form-table","data":{"model":"leaderMsg","validator":false,"minRows":1,"width":1000,"disableDelRows":1,"btnMsg":"","placeholder":"","busiId":"","title":"","align":"center","type":"select","columns":[{"type":"select","title":"专职/兼职","label":"","busiId":"","itemsProp":"","width":200,"extend":{"itemWidth":320,"placeholder":"","eventType":""},"itemOptions":[{"label":"兼职","value":"1","extend":{"size":"","disabled":false}},{"label":"专职","value":"2","extend":{"size":"","disabled":false}}]},{"type":"input","title":"资格证书编号","align":"center","placeholder":"","busiId":"","width":200,"rules":{"required":false,"message":"","type":"","trigger":""}},{"type":"input","title":"身份证编号","align":"center","placeholder":"","busiId":"","width":200,"rules":{"required":false,"message":"","type":"","trigger":""}},{"type":"input","title":"从事燃气专业工作年限(年)","align":"center","placeholder":"","busiId":"","width":200,"rules":{"required":false,"message":"","type":"","trigger":""}},{"type":"input","title":"职务及岗位","align":"center","placeholder":"","busiId":"","width":200,"rules":{"required":false,"message":"","type":"","trigger":""}},{"type":"select","title":"文化程度","label":"","busiId":"","itemsProp":"","width":200,"extend":{"itemWidth":320,"placeholder":"","eventType":""},"itemOptions":[{"label":"研究生及以上","value":"1","extend":{"size":"","disabled":false}},{"label":"大学本科","value":"2","extend":{"size":"","disabled":false}},{"label":"大学专科","value":"3","extend":{"size":"","disabled":false}},{"label":"中专","value":"4","extend":{"size":"","disabled":false}},{"label":"高中","value":"5","extend":{"size":"","disabled":false}},{"label":"初中","value":"6","extend":{"size":"","disabled":false}},{"label":"小学","value":"7","extend":{"size":"","disabled":false}},{"label":"其他","value":"8","extend":{"size":"","disabled":false}}]},{"type":"select","title":"性别","label":"","busiId":"","itemsProp":"","width":200,"extend":{"itemWidth":320,"placeholder":"","eventType":""},"itemOptions":[{"label":"男","value":"1","extend":{"size":"","disabled":false}},{"label":"女","value":"2","extend":{"size":"","disabled":false}}]},{"type":"input","title":"姓名","align":"center","placeholder":"","busiId":"","width":200,"rules":{"required":false,"message":"","type":"","trigger":""}}]}},{"type":"form","data":{"validator":false,"rules":{},"extend":{"span":17,"labelWidth":222,"itemWidth":320,"placeholder":"","maxlength":"220","eventType":"","rows":0},"items":[{"type":"input","label":"联系电话/申请人手机","busiId":9,"extend":{"itemWidth":320,"placeholder":"","eventType":"","maxlength":"220"}},{"type":"input","label":"联系人","busiId":18,"extend":{"itemWidth":320,"placeholder":"","eventType":"","maxlength":"220"}},{"type":"input","label":"证件号码","busiId":17,"extend":{"itemWidth":320,"placeholder":"","eventType":"","maxlength":"220"}},{"type":"input","label":"证件类型中文描述","busiId":33,"extend":{"itemWidth":320,"placeholder":"","eventType":"","maxlength":"220"}},{"type":"input","label":"证件类型","busiId":25,"extend":{"itemWidth":320,"placeholder":"","eventType":"","maxlength":"220"}},{"type":"input","label":"姓名/企业名称","busiId":6,"extend":{"itemWidth":320,"placeholder":"","eventType":"","maxlength":"220"}}]}}]}]};
                    let strJson=JSON.stringify(this.jsonObj);
                    console.log("strJson:"+strJson);
                    this.$store.commit('viewport/setPagePriviewData', this.jsonObj);
                    this.$router.push({name: 'pagePreview'})
                }


            },
            getbusinessData(fileName){
                return this.$http.get('/static/data/page-ide/'+fileName+'.json');
            },
            deleteData(){
                let state=this.$store.state;

                this.$store.commit('viewport/deleteData',state.viewport.currentEditInstanceKey);
            }
        },
        create(){
            eventbus.$on("exportData",(num)=>{
                alert(num);
                this.exportData(num);
            });
        }
    };
</script>

<style>
    .saveDivs{
        padding:0px 10px;
        height: 100%;
        line-height: 40px;
        min-width:56px;
        text-align: center;
    }
    .saveDivs:hover{
        background-color: white;
        color: #333;
    }
</style>
