<template>
    <div>
        <div id="app" >
            <div class="_fc-t-header">
                <img class="_fc-t-logo" :src="logo">
                <div class="_fc-t-name">{{ $t("reportDesigner.mainTitle") }}</div>
                <div class="_fc-t-menu">
                <el-button icon="el-icon-upload" @click="exportJson">{{ $t("reportDesigner.ExportJson") }}</el-button>
                <!-- <el-button type="primary" icon="el-icon-download" @click="importJson">导入JSON</el-button> -->
                <el-upload :auto-upload="false" action="" :show-file-list="false" style="margin:0px 12px 0px 12px;" :on-change="uploadChange" :before-upload="uploadBefore" >
                    <el-button type="primary" icon="el-icon-download">{{ $t("reportDesigner.ImportJson") }}</el-button>
                </el-upload>
                <el-button icon="sc-icon-language" @click="handleLanguage">{{ $t("reportDesigner.Language") }}</el-button>
                <el-button icon="el-icon-setting" @click="openPageSetting()">{{ $t("reportDesigner.TemplateSetting") }}</el-button>
                <el-button icon="sc-icon-ruler" @click="reportCalculation">{{ $t("reportDesigner.CustomizeCalculation") }}</el-button>
                <el-button icon="sc-icon-cN_EN_Transfer" @click="annotationAndTransfer">{{ $t("reportDesigner.CommentAndTranslation") }}</el-button>
                <el-button icon="sc-icon-config-two" @click="contentSetting">{{ $t("reportDesigner.ContentSetting") }}</el-button>
                </div>
            </div>
            <div style="height:60px;">
            </div>
            <sc-designer ref="scTemplateDesigner"/>
            <div style="height:30px;">
            </div>
            <el-footer class="_fc-copyright" height="30px">
            © {{$t('login.copyright')}}
            </el-footer>
        </div>
        <contentConfig-dialog v-if="dialog.contentConfig" ref="contentConfigDialog" @closed="dialog.contentConfig=false"></contentConfig-dialog>
        <annotationAndTransfer-dialog v-if="dialog.annotationAndTransfer" ref="annotationAndTransferDialog" @closed="dialog.annotationAndTransfer=false" @setlanguages="setLanguages">
        </annotationAndTransfer-dialog>
        <reportCalculation-dialog v-if="dialog.reportCalculation" ref="reportCalculationDialog" @closed="dialog.reportCalculation=false" @setCalculationItem="setCalculationItem">
        </reportCalculation-dialog>
    </div>
</template>


<script>
import contentConfigDialog from './reportTemplateContentConfig'
import annotationAndTransferDialog from './annotationAndTransfer'
import reportCalculationDialog from './reportCalculation'
import tool from '@/utils/tool';
import transfer from '@/utils/transfer';
import load from '@/utils/load';
import api from "@/api"
import { $t } from '../../locales'
import common from '@/utils/common';
import favicon from "@/config/designer/favicon";

export default {
    name: 'userList',
    components: {
        contentConfigDialog,
        annotationAndTransferDialog,
        reportCalculationDialog
    },
    data() {
        return {
            dialog: {
                contentConfig: false,
                annotationAndTransfer: false,
                reportCalculation: false
            },
            queryInfo: this.$route.query,
            form: {
            },
            logo: favicon.icon,
            isLoading: false,
            languagesTableData:[],
            calculationData:[],
            customCalcutationData: [],
            calculationJsonData: {},
            CustomizeCalculations:[],
            curLanguage: this.$TOOL.data.get("APP_LANG"),
            unitOptions:[
                    {
                        name: "%",
                        value: "percent",
                    }, {
                        name: "°",
                        value: "degree",
                    }, {
                        name: "1/MPa",
                        value: "d1mpa",
                    }, {
                        name: "bpm",
                        value: "HR",
                    }, {
                        name: "circ/s",
                        value: "circs",
                    }, {
                        name: "cm",
                        value: "cm",
                    }, {
                        name: "cm/m²",
                        value: "cmm2",
                    }, {
                        name: "cm/s",
                        value: "cms",
                    }, {
                        name: "cm/s²",
                        value: "cms2",
                    }, {
                        name: "cm²",
                        value: "cm2",
                    }, {
                        name: "cm²/m²",
                        value: "cm2m2",
                    }, {
                        name: "cm³",
                        value: "cm3",
                    }, {
                        name: "cm³/m²",
                        value: "cm3m2",
                    }, {
                        name: "cm³/min.m²",
                        value: "cm3minm2",
                    }, {
                        name: "cm³/s",
                        value: "cm3s",
                    }, {
                        name: "cm³/s.m²",
                        value: "cm3sm2",
                    }, {
                        name: "Days",
                        value: "day",
                    }, {
                        name: "ft",
                        value: "ft",
                    }, {
                        name: "g",
                        value: "g",
                    }, {
                        name: "g/cm³",
                        value: "gcm3",
                    }, {
                        name: "g/m²",
                        value: "gm2",
                    }, {
                        name: "g/ml",
                        value: "gml",
                    }, {
                        name: "h",
                        value: "hour",
                    }, {
                        name: "Hz",
                        value: "Hz",
                    }, {
                        name: "in",
                        value: "inch",
                    }, {
                        name: "kg",
                        value: "kg",
                    }, {
                        name: "kHz",
                        value: "KHz",
                    }, {
                        name: "kPa",
                        value: "kpa",
                    }, {
                        name: "L",
                        value: "L",
                    }, {
                        name: "L/min",
                        value: "Lmin",
                    }, {
                        name: "L/min.m²",
                        value: "Lminm2",
                    }, {
                        name: "lb",
                        value: "lb",
                    }, {
                        name: "lboz",
                        value: "lb_oz",
                    }, {
                        name: "m/s",
                        value: "ms",
                    }, {
                        name: "ml/s.m²",
                        value: "mlsm2",
                    }, {
                        name: "mm",
                        value: "mm",
                    }, {
                        name: "mm/m²",
                        value: "mmm2",
                    }, {
                        name: "mm/s",
                        value: "mms",
                    }, {
                        name: "mm/s²",
                        value: "mms2",
                    }, {
                        name: "mm²",
                        value: "mm2",
                    }, {
                        name: "mm²/Pa",
                        value: "mm2pa",
                    }, {
                        name: "mm³",
                        value: "mm3",
                    }, {
                        name: "mmHg",
                        value: "mmHg",
                    }, {
                        name: "mmHg/s",
                        value: "mmHgs",
                    }, {
                        name: "ms",
                        value: "msec",
                    }, {
                        name: "mV",
                        value: "mV",
                    }, {
                        name: "ng",
                        value: "ng",
                    }, {
                        name: "ng/ml",
                        value: "ngml",
                    }, {
                        name: "oz",
                        value: "oz",
                    }, {
                        name: "rad",
                        value: "radian",
                    }, {
                        name: "s",
                        value: "s",
                    }, {
                        name: "Wks",
                        value: "week_day",
                    },
                    {
                        name: "无单位",
                        value: "None",
                    }
            ]
        };
    },
    created() {
        window.addEventListener('keydown', this.keyOperateClick, false);
        window.addEventListener('mousewheel', this.mousewheelClick, { passive: false });
        window.addEventListener('DOMMouseScroll', this.DOMMouseScrollClick, { passive: false });
    },
    unmounted() {
        window.removeEventListener('keydown', this.keyOperateClick, false);
        window.removeEventListener('mousewheel', this.mousewheelClick, { passive: false });
        window.removeEventListener('DOMMouseScroll', this.DOMMouseScrollClick, { passive: false });
    },
    mounted() {
        this.initXmlData();
    },
    methods: {
        mousewheelClick(event) {
            if (event.ctrlKey === true || event.metaKey) {
              event.preventDefault();
            }
        },
        DOMMouseScrollClick(event) {
            if (event.ctrlKey === true || event.metaKey) {
                event.preventDefault();
            }
        },
        keyOperateClick(event) {
            if ((event.ctrlKey === true || event.metaKey === true)
            && (event.which === 61 || event.which === 107
            || event.which === 173 || event.which === 109
            || event.which === 187  || event.which === 189))
            {
                event.preventDefault();
            }
            if(event.keyCode === 122) {
                event.returnValue=false;
            }
        },
        async initXmlData() {
            api.template.getContentConfigFromStorgae.post();
            var params = {
                "ReportTemplateCode": this.queryInfo.id
            };
            var res = null;
            if (this.queryInfo.category === 0 || this.queryInfo.category === "0") {
                res = await api.template.getReportTemplateAsync.post(params);
            }
            var jsonData = this.readJsonFile();
            this.calculationJsonData = jsonData;
            this.unitOptions.forEach(c=>{
                if (c.value === "None") {
                    c.name = this.$t("reportDesigner.NoUnit");
                }
            });
            this.$refs.scTemplateDesigner.setDefaultParam(this.queryInfo, res, this.calculationJsonData, this.unitOptions);
        },
        //添加自定义计算项到总的数据源中
        AddCustomCalcutationData() {
            if (this.calculationData && this.calculationData.length > 0) {
                //Common
                var modeId = common.guid();
                var model = [{"Id": modeId,"Key":"CustomizeCalculation","Value":"自定义计算项","PId":2,"Type":2}];
                var measureItem = [];
                var measureMethod = [];
                var output = [];
                var type = [];
                var unit = [];
                this.CustomizeCalculations = [];
                this.calculationData.some(c => {
                    if (c.formula && c.formula.length > 0) {
                        var measureItemId = common.guid();
                        var measureMethodId = common.guid();
                        var outputId = common.guid();
                        var typeId = common.guid();
                        var unitId = common.guid();
                        //添加测量项
                        measureItem.push(
                            {"Id":measureItemId,"Key":c.title,"Value":c.title,"PId":modeId,"Type":2, "Formula":c.formula}
                        );
                        //添加测量方法
                        measureMethod.push(
                            {"Id":measureMethodId,"Key":"","Value":"","PId":measureItemId,"Type":2, "Formula":c.formula}
                        );
                        //输出
                        output.push(
                            {"Id":outputId,"Key":c.title,"Value":c.title,"PId":measureMethodId,"Type":2, "Formula":c.formula}
                        );
                        //自定测量项名称
                        type.push(
                            {"Id":typeId,"Key":c.title,"Value":c.title,"PId":unitId,"Type":2, "Formula":c.formula}
                        );
                        var unitItem = {};
                        if (c.additionUnitType && c.additionUnitType.name && c.additionUnitType.name.length > 0) {
                            //单位
                            unitItem = {"Id":unitId,"Key":c.additionUnitType.value,"Value":c.additionUnitType.name,"PId":outputId,"Type":2, "Formula":c.formula};
                        }
                        else {
                            var unitOption = {};
                            //单位
                            this.unitOptions.some(c => {
                                if (c.value === "None") {
                                    unitOption = c;
                                    return true;
                                }
                            });
                            unitItem = {"Id":unitId,"Key":"None","Value":unitOption.name,"PId":outputId,"Type":2, "Formula":c.formula};
                        }

                        unit.push(unitItem);
                        this.CustomizeCalculations.push(
                            {
                                Formula: c.formula,
                                Id: c.title,
                                Unit: unitItem.Key
                            },
                        )
                    }
                });
            }
            return { measureItem, measureMethod, model, output, type, unit };
        },
        //读取计算项文件信息
        readJsonFile() {
            var caculateItem = null;
            var category = null;
            var measureItem = null;
            var measureMethod = null;
            var model = null;
            var output = null;
            var type = null;
            var unit = null;
            if (this.curLanguage === null || this.curLanguage.length <= 0) {
                this.curLanguage = "zh-CN";
            }
            caculateItem = JSON.parse(tool.readFile("json/" + this.curLanguage + "/RDCaculateItem.json"));
            category = JSON.parse(tool.readFile("json/" + this.curLanguage + "/RDCategory.json"));
            measureItem = JSON.parse(tool.readFile("json/" + this.curLanguage + "/RDMeasureItem.json"));
            measureMethod = JSON.parse(tool.readFile("json/" + this.curLanguage + "/RDMeasureMethod.json"));
            model = JSON.parse(tool.readFile("json/" + this.curLanguage + "/RDModel.json"));
            output = JSON.parse(tool.readFile("json/" + this.curLanguage + "/RDOutput.json"));
            type = JSON.parse(tool.readFile("json/" + this.curLanguage + "/RDType.json"));
            unit = JSON.parse(tool.readFile("json/" + this.curLanguage + "/RDUnit.json"));
            //console.log("readJsonFile.model:", model);
            return { caculateItem, category, measureItem, measureMethod, model, output, type, unit }
        },
        //打开模板设置
        openPageSetting() {
            this.$refs.scTemplateDesigner.openPageSetting();
        },
        //导出
        exportJson() {
            var result = this.$refs.scTemplateDesigner.loadSaveTemplateData();
            if (result) {
                var templateContent = tool.data.get("CurrentTemplateContent");
                if (templateContent && templateContent.currentModuelList && templateContent.currentModuelList.length > 0) {
                    var filename = templateContent.currentPageInfo.name + ".json";
                    var data = transfer.saveOldJson(this.languagesTableData, templateContent.currentPageInfo,
                    templateContent.currentHeaderModuelList, templateContent.currentModuelList,
					templateContent.currentFooterModuelList, this.CustomizeCalculations);
                    if (typeof data === "object") {
                        data = JSON.stringify(data["templateJson"], undefined, 4);
                    }
                    var blob = new Blob([data], { type: "text/json" }),
                    e = document.createEvent("MouseEvents"),
                    a = document.createElement("a");
                    a.download = filename;
                    a.href = window.URL.createObjectURL(blob);
                    a.dataset.downloadurl = ["text/json", a.download, a.href].join(":");
                    e.initMouseEvent(
                        "click",
                        true,
                        false,
                        window,
                        0,
                        0,
                        0,
                        0,
                        0,
                        false,
                        false,
                        false,
                        false,
                        0,
                        null
                    );
                    a.dispatchEvent(e);
                }
                else {
                    alert(this.$t("reportDesigner.CommitTip1"));
                }
            }
        },
        contentSetting() {
            this.dialog.contentConfig = true
            this.$nextTick(() => {
                this.$refs.contentConfigDialog.open();
            })
        },
        annotationAndTransfer(){
            this.dialog.annotationAndTransfer = true
            this.$nextTick(() => {
                var list = this.$refs.scTemplateDesigner.getLabelContentList();
                this.$refs.annotationAndTransferDialog.open(list);
            })
        },
        reportCalculation(){
            this.dialog.reportCalculation = true
            this.$nextTick(() => {
                if (!this.customCalcutationData || !this.customCalcutationData.model || !this.customCalcutationData.model.length <= 0) {
                    var tempEntity = this.$refs.scTemplateDesigner.getCustomCalcutationData();
                    this.customCalcutationData = tempEntity.customCalcutationData;
                    this.CustomizeCalculations = tempEntity.CustomizeCalculations;
                    //转成测量页面的数据结构
                    if (this.CustomizeCalculations && this.CustomizeCalculations.length > 0) {
                        this.calculationData = [];
                        this.CustomizeCalculations.some((m,index) => {
                            var activeValue = false;
                            if (index === 0) {
                                activeValue = true;
                            }
                            var unitItems = this.unitOptions.filter(n => n.value === m.Unit);
                            this.calculationData.push({
                                id: common.guid(),
                                active: activeValue,
                                title: m.Id,
                                formula: m.Formula,
                                additionUnitTypeText: "",
                                bindContentItem: {
                                    UnitTypeItem: {},
                                    MeasureCalculation: {},
                                    OutputItem: {},
                                    MeasureWay: {},
                                    MeasureItem: {},
                                    MeasureCategory: {},
                                    ScanMode: {},
                                    UserDefineName: {},
                                },
                                additionUnitType: unitItems[0],
                                generalContentItem: {}
                            });
                        });
                        this.$TOOL.data.set("CustomCalculationData", this.calculationData);
                    }
                }
                this.$refs.reportCalculationDialog.open(this.calculationJsonData, this.calculationData, this.unitOptions);
            })
        },
        //转成测量页面的数据结构
        transferCustomCalcutationData() {
            if (this.CustomizeCalculations && this.CustomizeCalculations.length > 0) {
                this.calculationData = [];
                this.CustomizeCalculations.some(d => {
                    var unitItem = {};
                    this.unitOptions.some(c => {
                        if (c.value === d.Unit) {
                            unitItem = c;
                            return true;
                        }
                    });
                    this.calculationData.push(
                        {
                            id: common.guid(),
                            active: false,
                            title: d.Id,
                            formula: d.Formula,
                            additionUnitTypeText: d.Unit,
                            bindContentItem: {
                                UnitTypeItem: {},
                                MeasureCalculation: {},
                                OutputItem: {},
                                MeasureWay: {},
                                MeasureItem: {},
                                MeasureCategory: {},
                                ScanMode: {},
                                UserDefineName: {},
                            },
                            additionUnitType: unitItem,
                            generalContentItem: {}
                        }
                    );
                });
            }
        },
        setLanguages(data)
        {
            this.languagesTableData = data;
            this.$refs.scTemplateDesigner.getLabelContentList(this.languagesTableData);
        },
        //设置自定义项
        setCalculationItem(data)
        {
            this.calculationData = data;
            this.$TOOL.data.set("CustomCalculationData", data);
            this.customCalcutationData = this.AddCustomCalcutationData();
            this.$refs.scTemplateDesigner.setCustomCalculationData(this.customCalcutationData, this.CustomizeCalculations);
        },
        //上传处理
        uploadChange(file){
            var reader = new FileReader();
            reader.readAsText(file.raw); //调用自带方法进行转换
            reader.onload = (e) => {
                var fileContent = JSON.parse(e.target.result);
                var templateContent = load.oldJsonTransferNewJson(fileContent);
                this.$refs.scTemplateDesigner.loadJsonData(templateContent);
            };
        },
        //上传前处理
        uploadBefore(file){
            const maxSize = file.size / 1024 / 1024 < this.maxSize;
            if (!maxSize) {
                this.$message.warning($t("reportDesigner.MaxSizeTip") + ` ${this.maxSize}MB!`);
                return false;
            }
        },
        //语言切换
        handleLanguage() {
            if(this.curLanguage == "en-US"){
                this.$i18n.locale = "zh-CN";
                this.$TOOL.data.set("APP_LANG", "zh-CN");
                this.curLanguage= "zh-CN";
            }
            else if(this.curLanguage == "zh-CN"){
                this.$i18n.locale = "en-US";
                this.$TOOL.data.set("APP_LANG", "en-US");
                this.curLanguage= "en-US";
            }
            this.unitOptions.forEach(c=>{
                if (c.value === "None") {
                    c.name = this.$t("reportDesigner.NoUnit");
                }
            });
        },
    },
};
</script>

<style>
    ._fc-t-header {
        margin: 0px;
        position: fixed;
        display: flex;
        align-items: center;
        cursor: default;
		background-color: white;
		padding: 0 20px;
        height: 60px;
        width: 100%;
        z-index: 2000;
        top: 0px;
        border-bottom: 1px solid rgb(230, 230, 230);
    }

    ._fc-t-logo {
        height: 26px;
    }

    ._fc-t-name {
        display: inline-block;
        color: rgba(0, 0, 0, 0.8);
        font-size: 20px;
        font-weight: 600;
        margin-left: 5px;
    }

    ._fc-t-menu {
        position: absolute;
        right: 20px;
        display: flex;
    }

    ._fc-t-menu i {
        font-size: 12px;
    }

    body {
        min-height: 100vh;
        padding: 0;
        margin: 0;
        display: flex !important;
        flex-direction: column !important;
    }

    #app {
        display: flex;
        flex-direction: column;
        flex: 1;
    }

    ._fc-copyright {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding: 0 20px;
        font-size: 12px;
        border-top: 1px solid #ECECEC;
        background-color: #fff;
		color:#303133;
		font-weight: bold;
        position: fixed;
        bottom: 0px;
        width: 100%;
        z-index: 2000;
    }

    ._fc-t-dialog .CodeMirror {
        height: 450px;
    }

    ._fc-t-dialog .CodeMirror-line {
        line-height: 16px !important;
        font-size: 13px !important;
    }

    .CodeMirror-lint-tooltip {
        z-index: 2021 !important;
    }

    ._fc-t-dialog .el-dialog__body {
        padding: 0px 20px;
    }
    ._fc-b-item{
      display: flex;
    }


.aminui::-webkit-scrollbar {
  /*滚动条整体样式*/
  width : 10px;  /*高宽分别对应横竖滚动条的尺寸*/
  height: 1px;
  }
.aminui::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius   : 10px;
  background-color: skyblue;
  background-image: -webkit-linear-gradient(
      45deg,
      rgba(255, 255, 255, 0.2) 25%,
      transparent 25%,
      transparent 50%,
      rgba(255, 255, 255, 0.2) 50%,
      rgba(255, 255, 255, 0.2) 75%,
      transparent 75%,
      transparent
  );
  }
.aminui::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    box-shadow   : inset 0 0 5px rgba(0, 0, 0, 0.2);
    background   : #ededed;
    border-radius: 10px;
}

.el-dialog__title {
    font-size: 17px;
    font-weight: bold;
    padding-bottom: 11px;
    border-bottom: solid 2px #409eff;
    z-index: 1;
    color: #409eff;
    position: relative;
}
.el-dialog__header {
  padding: var(--el-dialog-padding-primary);
  padding-bottom: 10px;
  border-bottom: 2px solid rgba(0, 0, 0, 0.06);
}
.el-dialog__body {
  padding: calc(var(--el-dialog-padding-primary) + 10px)
    var(--el-dialog-padding-primary);
  color: var(--el-text-color-regular);
  font-size: var(--el-dialog-content-font-size);
  word-break: break-all;
  padding-top: 10px;
  padding-bottom: 10px;
}
.el-dialog__footer {
  padding: var(--el-dialog-padding-primary);
  padding-top: 10px;
  text-align: right;
  box-sizing: border-box;
  border-top: 2px solid rgba(0, 0, 0, 0.06);
}
.el-form-item__label {
  font-weight: bold;
  line-height: 32px;
}
</style>
