<template>
  <div>
    <el-form ref="headFormRef" :rules="headFormRules" :model="formData" size="mini" :disabled="checkShow || !addBtn"
      label-width="80px">
      <el-row type="flex" justify="space-around">
        <el-form-item label="发动机型号" prop="engineModel" label-width="95px">
          <el-select filterable v-model="formData.engineModel" placeholder="请选择发动机型号" @change="changeEngine">
            <el-option v-for="item in engineOptions" :key="item.id" :label="item.model" :value="item.id">
            </el-option>
            <el-option :value="undefined" style="cursor: pointer">
              <el-button type="text" @click="onClickBtn('engine')"><i class="el-icon-plus"></i> 增加发动机型号</el-button>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="几何模型" prop="geometryFiles">
          <div style="width: 200px;">
            <el-link :disabled="formData.geometryFiles ? false : true"
              :type="formData.geometryFiles ? 'primary' : 'warning'" :href="`${baseUrl}${formData.geometryFiles}`"
              target="_blank">{{
      formData.geometryFiles ? getFileName(formData.geometryFiles) : '暂无几何模型文件' }}</el-link>
          </div>
        </el-form-item>
        <el-form-item label="几何图片" prop="geometryImage">
          <div style="width: 200px;">
            <ImagePreview :src="formData.geometryImage" :width="80" :height="80" />
          </div>
        </el-form-item>
      </el-row>
      <el-row type="flex" justify="space-around">
        <el-form-item label="测量批次" prop="measurementBatchId">
          <el-select filterable v-model="formData.measurementBatchId" placeholder="请选择测量批次">
            <el-option v-for="item in batchOption" :key="item.id" :label="item.measurementBatch" :value="item.id">
            </el-option>
            <el-option :value="undefined" disabled style="cursor: pointer">
              <el-button type="text" @click="onClickBtn('measBatch')"><i class="el-icon-plus"></i> 增加测量批次</el-button>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <div style="width: 200px;"></div>
        </el-form-item>
        <el-form-item>
          <div style="width: 200px;"></div>
        </el-form-item>
      </el-row>
    </el-form>
    <!-- <el-form ref="formData" :disabled="checkShow" :model="formData" :rules="formRules" size="mini" label-width="80px">
      
    </el-form> -->
    <div class="box">
      <span class="title">环境参数</span>
      <el-form :disabled="checkShow" :rules="formRules" @submit-form="submitForm" :inline-message="true" :form="form"
        @cancel="cancel" ref="formRef" :model="formData" size="mini" label-width="80px"
        :validate-on-rule-change="false">
        <el-row type="flex" justify="space-around">
          <el-form-item label="发动机状态" label-width="95px" prop="engineStatus">
            <el-select filterable v-model="formData.engineStatus" placeholder="请选择发动机状态">
              <el-option v-for="item in engineStatusOptions" :key="item" :label="item" :value="item">
              </el-option>
              <el-option :value="undefined" disabled style="cursor: pointer">
                <el-button type="text" @click="onClickBtn('engineStatus')"><i class="el-icon-plus"></i>
                  增加发动机状态</el-button>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角度" prop="angle">
            <el-select filterable v-model="formData.angle" placeholder="请输入角度">
              <el-option v-for="item in angleOptions" :key="item" :label="item" :value="item">
              </el-option>
              <el-option :value="undefined" disabled style="cursor: pointer">
                <el-button type="text" @click="onClickBtn('engineAngle')"><i class="el-icon-plus"></i>
                  增加发动机角度</el-button>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="涡轮后温度" prop="turbinePostTemp" label-width="90px">
            <file-upload :isCheck="isCheck" :fileSize="0" :limit="1" :fileType="['txt']"
              v-model="formData.turbinePostTemp" />
          </el-form-item>
        </el-row>
        <el-row type="flex" justify="space-around">
          <el-form-item label="测试距离" prop="testDistance">
            <el-input v-model="formData.testDistance" placeholder="请输入测试距离"><template
                slot="append">m</template></el-input>
          </el-form-item>
          <el-form-item label="时间" prop="time">
            <el-date-picker clearable v-model="formData.time" type="datetime" value-format="yyyy-MM-dd HH:mm"
              format="yyyy-MM-dd HH:mm" placeholder="请选择时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="地点" prop="location">
            <el-input v-model="formData.location" placeholder="请输入地点" />
          </el-form-item>
        </el-row>
        <el-row type="flex" justify="space-around">
          <el-form-item label="大气压" prop="atmosPress">
            <el-input v-model="formData.atmosPress" placeholder="请输入大气压"><template
                slot="append">pa</template></el-input>
          </el-form-item>
          <el-form-item label="温度" prop="temperature">
            <el-input v-model="formData.temperature" placeholder="请输入温度"><template slot="append">K</template></el-input>
          </el-form-item>
          <el-form-item label="风速" prop="windSpeed">
            <el-input v-model="formData.windSpeed" placeholder="请输入风速"><template slot="append">m/s</template></el-input>
          </el-form-item>
        </el-row>
        <el-row type="flex" justify="space-around">
          <el-form-item label="湿度" prop="humidity">
            <el-input v-model="formData.humidity" placeholder="请输入湿度"><template slot="append">%</template></el-input>
          </el-form-item>
          <el-form-item label="CO₂浓度" prop="concentration">
            <el-input v-model="formData.concentration" placeholder="请输入浓度"><template
                slot="append">mol</template></el-input>
          </el-form-item>
          <el-form-item>
            <div style="width: 200px;">
              <el-button v-if="addBtn" type="primary" size="mini" @click="envDataSave">保 存</el-button>
            </div>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div class="box" v-if="radiationData && Object.keys(radiationData).length > 0">
      <span class="title">光谱辐射测量数据</span>
      <el-form :rules="radiationRules" :inline-message="true" :key="radiationData.createTime"
        :disabled="checkShow || addBtn" :validate-on-rule-change="false" ref="radiationRef" size="mini"
        :model="radiationData" label-width="80px">
        <el-row type="flex" justify="space-around">
          <el-form-item label="型号" prop="model">
            <el-input v-model="radiationData.model" placeholder="请输入型号" />
          </el-form-item>
          <el-form-item label="镜头视场角" prop="lensFView" label-width="95px">
            <el-input v-model="radiationData.lensFView" placeholder="请输入镜头视场角"><template
                slot="append">mrad</template></el-input>
          </el-form-item>
          <el-form-item label="增益" prop="gain">
            <el-input v-model.number="radiationData.gain" placeholder="请输入增益"><template
                slot="append">x</template></el-input>
          </el-form-item>
        </el-row>
        <el-row type="flex" justify="space-around">
          <el-form-item label="背景数据" prop="backgroundData">
            <file-upload :isCheck="isCheck" :fileSize="0" :limit="1" :fileType="['lgm']"
              v-model="radiationData.backgroundData" />
          </el-form-item>
          <el-form-item label="标定曲线" prop="calCurve">
            <file-upload :isCheck="isCheck" :fileSize="0" :limit="5" :fileType="['txt']" :isShowViev="true"
              v-model="radiationData.calCurve" v-on:fileView="fileView" />
          </el-form-item>
          <el-form-item>
            <div style="width: 200px;"></div>
          </el-form-item>
        </el-row>
        <el-row style="margin-left: 2%;" class="calTempTabel" type="flex">
          <el-form-item label="标定温度" prop="calTemp">
            <el-table :data="calTempData" size="mini" border style="width: 600px">
              <el-table-column prop="temp" label="温度" width="100px" align="center">
              </el-table-column>
              <el-table-column prop="calTempFile" label="文件" align="center">
                <template slot-scope="scope">
                  <el-link @click="$download.resource(scope.row.calTempFile,false)"  :underline="false">
                    <span class="el-icon-document"> {{ getFileName(scope.row.calTempFile) }} </span>
                  </el-link>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100px" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="delCalTemp(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="" label-width="10px">
            <i style="font-size: 1.5rem;margin-top: 10px;" class="el-icon-circle-plus-outline" @click="addCalTemp"
              v-if="!(checkShow || addBtn)"></i>
          </el-form-item>
        </el-row>
      </el-form>
      <div class="box" style="margin-bottom: 15px">
        <span class="title">目标数据</span>
        <el-form ref="radiationRef" :disabled="checkShow || addBtn" size="mini" :rules="radiationRules"
          :validate-on-rule-change="false" :model="radiationData" label-width="80px">
          <el-row type="flex" justify="space-around">
            <el-form-item label="原始数据" prop="rawData">
              <file-upload :isCheck="isCheck" :fileSize="0" :limit="5" :fileType="['txt']"
                v-model="radiationData.rawData" />
            </el-form-item>
            <el-form-item label="辐射亮度3~5μm" label-width="130px" prop="radiance1">
              <file-upload :isCheck="isCheck" :fileSize="0" :limit="1" :fileType="['txt']"
                v-model="radiationData.radiance1" :isShowViev="true" v-on:fileView="fileView" />
            </el-form-item>
            <el-form-item label="辐射亮度8~14μm" label-width="130px" prop="radiance2">
              <file-upload :isCheck="isCheck" :fileSize="0" :limit="1" :fileType="['txt']"
                v-model="radiationData.radiance2" :isShowViev="true" v-on:fileView="fileView" />
            </el-form-item>
          </el-row>
        </el-form>
      </div>
    </div>
    <div class="box" v-if="TIData && Object.keys(TIData).length > 0">
      <span class="title">热像仪测量数据</span>
      <el-form ref="TIRef" :disabled="checkShow || addBtn" :inline-message="true" :rules="TIRules"
        :key="TIData.createTime" :model="TIData" size="mini" label-width="80px" :validate-on-rule-change="false">
        <el-row type="flex" justify="space-around">
          <el-form-item label="型号" prop="model">
            <el-input v-model="TIData.model" placeholder="请输入型号" />
          </el-form-item>
          <el-form-item label="镜头视场角" label-width="95px" prop="lensFView">
            <el-input v-model="TIData.lensFView" placeholder="请输入镜头视场角"><template
                slot="append">mrad</template></el-input>
          </el-form-item>
          <el-form-item label="滤镜编号" prop="filterNo">
            <el-input v-model="TIData.filterNo" placeholder="请选择滤镜编号" />
          </el-form-item>
        </el-row>
        <el-row type="flex" justify="space-around">
          <el-form-item label="帧率" prop="fps">
            <el-input v-model="TIData.fps" placeholder="请选择帧率" />
          </el-form-item>
          <el-form-item label="波段" prop="spectralBand">
            <el-input v-model="TIData.spectralBand" placeholder="请选择波段" />
          </el-form-item>
          <el-form-item label="积分时间" prop="integrationTime">
            <el-input v-model.number="TIData.integrationTime" placeholder="请输入积分时间"><template
                slot="append">s</template></el-input>
          </el-form-item>
        </el-row>
        <el-row type="flex" justify="space-around">
          <el-form-item label="温度标定" prop="tempCal">
            <file-upload :isCheck="isCheck" :fileSize="0" :limit="1" :fileType="['txt']" v-model="TIData.tempCal" />
          </el-form-item>
          <el-form-item label="辐射亮度" prop="radiance">
            <file-upload :isCheck="isCheck" :fileSize="0" :limit="1" :fileType="['txt']" v-model="TIData.radiance"
              :isShowViev="true" v-on:fileView="fileView2" />
          </el-form-item>
          <el-form-item label="辐射照度" prop="radIllumination">
            <file-upload :isCheck="isCheck" :fileSize="0" :limit="1" :fileType="['txt']"
              v-model="TIData.radIllumination" :isShowViev="true" v-on:fileView="fileView" />
          </el-form-item>
        </el-row>
        <el-row type="flex" justify="space-around">
          <el-form-item label="辐射温度" prop="radTemp">
            <file-upload :isCheck="isCheck" :fileSize="0" :limit="1" :fileType="['txt']" v-model="TIData.radTemp"
              :isShowViev="true" v-on:fileView="fileView" />
          </el-form-item>
          <el-form-item>
            <div style="width: 200px;"></div>
          </el-form-item>
          <el-form-item>
            <div style="width: 200px;"></div>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div class="box" v-if="TransmittanceData">
      <span class="title">透过率数据</span>
      <el-form :disabled="checkShow || addBtn" ref="TransmittanceRef" :model="TransmittanceData" label-width="80px"
        :validate-on-rule-change="false">
        <el-row type="flex" justify="space-around">
          <el-form-item label="原始数据" prop="rawData">
            <file-upload :fileSize="0" :limit="1" :isCheck="isCheck" :fileType="['txt']"
              v-model="TransmittanceData.rawData" />
          </el-form-item>
          <el-form-item label="透过率曲线3~5μm" label-width="130px" prop="curve1">
            <file-upload :fileSize="0" :limit="1" :isCheck="isCheck" :fileType="['txt']" :isShowViev="true"
              v-on:fileView="fileView" v-model="TransmittanceData.curve1" />
          </el-form-item>
          <el-form-item label="透过率曲线8~14μm" label-width="135px" prop="curve2">
            <file-upload :fileSize="0" :isCheck="isCheck" :limit="1" :fileType="['txt']"
              v-model="TransmittanceData.curve2" :isShowViev="true" v-on:fileView="fileView" />
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <el-row type="flex" justify="space-around" v-if="resultData && Object.keys(resultData).length > 0">
      <el-button size="mini" type="success" style="margin-top: 20px">计算数据</el-button>
    </el-row>
    <div class="box" v-if="resultData && Object.keys(resultData).length > 0">
      <span class="title">计算结果</span>
      <el-form ref="resultRef" :disabled="checkShow" :model="resultData" :inline-message="true" size="mini"
        label-width="150px" :rules="resultRules">
        <el-row type="flex" justify="space-around">
          <el-form-item label="光谱辐射强度3~5μm" prop="specIrr1">
            <file-upload :fileSize="0" :limit="1" :fileType="['txt']" v-model="resultData.specIrr1" :isCheck="isCheck"
              :isShowViev="true" v-on:fileView="fileView" />
          </el-form-item>
          <el-form-item label="光谱辐射强度8~14μm" prop="specIrr2">
            <file-upload :fileSize="0" :limit="1" :fileType="['txt']" v-model="resultData.specIrr2" :isCheck="isCheck"
              :isShowViev="true" v-on:fileView="fileView" />
          </el-form-item>
        </el-row>
        <el-row type="flex" justify="space-around">
          <el-form-item label="波段辐射强度3~5μm" prop="specBandIrr1">
            <el-input v-model="resultData.specBandIrr1" placeholder="请输入波段辐射强度3~5μm" />
          </el-form-item>
          <el-form-item label="波段辐射强度8~14μm" prop="specBandIrr2">
            <el-input v-model="resultData.specBandIrr2" placeholder="请输入波段辐射强度8~14μm" />
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div v-if="footShow" slot="footer" class="footerBtn">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel" style="margin-left: 40px;">取 消</el-button>
    </div>
    <el-dialog :close-on-click-modal="false" title="增加标定温度" :visible.sync="addCalTempVisible" width="500px"
      append-to-body>
      <el-form ref="calTempFormRef" :model="calTempForm" label-width="60px">
        <el-form-item label="温度" prop="temp">
          <el-input type="number" v-model.number="calTempForm.temp" placeholder="请输入温度(只能输入数字)" />
        </el-form-item>
        <el-form-item label="文件" prop="calTempFile">
          <file-upload :fileSize="0" :limit="1" :isCheck="isCheck" :fileType="['txt']"
            v-model="calTempForm.calTempFile" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCalTemp">确 定</el-button>
        <el-button @click="cancelCalTemp">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="增加发动机型号" :visible.sync="addDialogVisible" width="400px"
      append-to-body>
      <el-form ref="addEngineFormRef" :model="addEngineForm" :disabled="isCheck" :rules="rules" label-width="100px">
        <el-form-item label="发动机型号" prop="model">
          <el-input v-model="addEngineForm.model" placeholder="请输入发动机型号" />
        </el-form-item>
        <el-form-item label="几何模型文件" prop="geometryFiles">
          <file-upload :fileSize="0" :limit="1" :fileType="['x_t', 'str']" v-model="addEngineForm.geometryFiles" />
        </el-form-item>
        <el-form-item label="几何模型图片" prop="geometryImage">
          <image-upload :fileSize="0" :limit="1" :fileType="['jpg']" v-model="addEngineForm.geometryImage" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addEngine()">确 定</el-button>
        <el-button @click="addDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="增加测量批次" :visible.sync="addMeasVisible" width="400px" append-to-body>
      <el-form ref="addMeasBatchformRef" :model="addMeasBatchForm" :rules="rules" label-width="90px">
        <el-form-item label="发动机型号" prop="engineId">
          <el-select filterable v-model="addMeasBatchForm.engineId" placeholder="请选择发动机型号" @change="engineChange">
            <el-option v-for="item in engineOptions" :key="item.id" :label="item.model" :value="item.id">
              <span style="float: left">{{ item.id }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.model }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="测量批次" prop="measurementBatch">
          <el-input v-model="addMeasBatchForm.measurementBatch" placeholder="请输入测量批次（测量年月日+发动机型号）" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addMeas()">确 定</el-button>
        <el-button @click="addMeasVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="增加发动机状态" :visible.sync="addStatusVisible" width="400px"
      append-to-body>
      <el-form ref="addStatusFormRef" :model="addStatusForm" :rules="rules" label-width="80px">
        <el-form-item label="状态" prop="status">
          <el-input v-model="addStatusForm.status" placeholder="请输入状态" />
        </el-form-item>
        <el-form-item label="排序" prop="index">
          <el-input v-model="addStatusForm.index" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addStatus()">确 定</el-button>
        <el-button @click="addStatusVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="增加发动机角度" :visible.sync="addAngleVisible" width="400px"
      append-to-body>
      <el-form ref="addAngleFormRef" :model="addAngleForm" :rules="rules" label-width="80px">
        <el-form-item label="角度" prop="angle">
          <el-input v-model="addAngleForm.angle" placeholder="请输入角度" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addAngle()">确 定</el-button>
        <el-button @click="addAngleVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="数据可视化" :visible.sync="fileVisible" width="70%" append-to-body>
      <ECharts class="chartShow" :chartData="chartData" :width="chartType === 'heatmap' ? '400px' :'100%'" />
    </el-dialog>
  </div>
</template>

<script>
import { listEngineModel, addEngineModel } from "@/api/meas/engineModel";
import { angleOption, addAngle } from "@/api/meas/angle";
import { statusOption, addStatus } from "@/api/meas/status";
import { listMeasBatch, addMeasBatch } from "@/api/meas/measBatch";
import ECharts from "@/views/meas/envData/ECharts.vue";
export default {
  name: "dialogContent",
  components: { ECharts },
  props: {
    form: {
      type: Object,
      default: null,
    },
    radiationForm: {
      type: Object,
      default: null,
    },
    TIForm: {
      type: Object,
      default: null,
    },
    TransmittanceForm: {
      type: Object,
      default: null,
    },
    resultForm: {
      type: Object,
      default: null,
    },
    envSaveBtn: {
      type: Boolean,
      default: false,
    },
    isCheck: {
      type: Boolean,
      default: false,
    },
    addFlag: {
      type: Boolean,
      default: false,
    },
    footShow: {
      type: Boolean,
      default: true,
    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 热像仪测试
      lensFViewOptions: [],
      filterNoOptions: [],
      fpsOptions: [],
      spectralBandOptions: [],
      rules: {},
      // 表单校验和验证
      headFormRules: {
        engineModel: [
          { required: true, message: "发动机型号不能为空", trigger: "change" },
        ],
        measurementBatchId: [
          { required: true, message: "测量批次id不能为空", trigger: "change" },
        ],
      },
      formRules: {
        engineStatus: [
          { required: true, message: "发动机状态不能为空", trigger: "change" },
        ],
        angle: [{ required: true, message: "角度不能为空", trigger: "change" }],
        testDistance: [
          {
            pattern: /^(0(\.\d{1,2})?|[1-9]\d{0,2}(\.\d{0,2})?|1000(\.00?)?)$/,
            message: "请输入0.00-1000.00之间的数字,可保留两位小数",
            trigger: "blur",
          },
        ],
        time: [{ required: true, message: "时间不能为空", trigger: "change" }],
        location: [
          { required: true, message: "地点不能为空", trigger: "blur" },
          {
            min: 0,
            max: 50,
            message: "长度在 0 到 50 个字符",
            trigger: "blur",
          },
        ],
        atmosPress: [
          {
            pattern:
              /^(0(\.\d{1,2})?|[1-9]\d{0,2}(\.\d{1,2})?|1[0-4]\d{2}(\.\d{0,2})?|1500(\.00?)?)$/,
            message: "请输入0.00-1500.00之间的数字,最多可保留两位小数",
            trigger: "blur",
          },
        ],
        temperature: [
          {
            pattern: /^(230|2[3-9]\d|30\d|31\d|320)(\.\d{0,2})?$/,
            message: "请输入230.00-320.00之间的数字,最多可保留两位小数",
            trigger: "blur",
          },
        ],
        windSpeed: [
          {
            pattern: /^(0(\.\d{1,2})?|[1-9]\d{0,2}(\.\d{0,2})?|1000(\.00?)?)$/,
            message: "请输入0.00-1000.00之间的数字,最多可保留两位小数",
            trigger: "blur",
          },
        ],
        humidity: [
          {
            pattern: /(^(\d|[1-9]\d)(\.\d{0,2})?$)|(^100$)/,
            message: "请输入0.00-100.00之间的数字,最多可保留两位小数",
            trigger: "blur",
          },
        ],
        concentration: [
          {
            pattern: /^(0(\.\d{1,2})?|[1-9]\d{0,2}(\.\d{0,2})?|1000(\.00?)?)$/,
            message: "请输入0.00-1000.00之间的数字,最多可保留两位小数",
            trigger: "blur",
          },
        ],
      },
      radiationRules: {
        model: [
          { required: true, message: "型号不能为空", trigger: "blur" },
          { min: 0, max: 50, message: '长度在 0 到 50 个字符', trigger: 'blur' }
        ],
        lensFView: [
          { required: true, message: "镜头视场角不能为空" },
          { required: true, pattern: /^(0|[1-8]?[0-9]|90)(\.\d{0,2})?$/, message: '请输入0.00-90.00之间的数字,最多可保留两位小数', trigger: 'blur' }
        ],
        gain: [
          { required: true, message: '增益不能为空' },
          { type: 'number', min: 1, max: 10, message: '请输入1-10之间的数字', trigger: 'blur' }
        ],

      },
      TIRules: {
        model: [
          { required: true, message: "型号不能为空", trigger: "blur" },
          { min: 0, max: 50, message: '长度在 0 到 50 个字符', trigger: 'blur' }
        ],
        // lensFView:[
        //   { required: true, message: "镜头视场角不能为空", trigger: "change" },
        // ],
        integrationTime: [
          { type: 'number', min: 1, max: 100, message: '请输入1-100之间的数字', trigger: 'blur' }
        ]
      },
      resultRules: {
        specBandIrr1: [
          {
            pattern: /^(0(\.\d{1,2})?|[1-9]\d{0,2}(\.\d{1,2})?|1000(\.00?)?)$/,
            message: "请输入0.00-1000.00之间的数字,最多可保留两位小数",
            trigger: "blur",
          },
        ],
        specBandIrr2: [
          {
            pattern: /^(0(\.\d{1,2})?|[1-9]\d{0,2}(\.\d{1,2})?|1000(\.00?)?)$/,
            message: "请输入0.00-1000.00之间的数字,最多可保留两位小数",
            trigger: "blur",
          },
        ],
      },
      formData: this.form,
      radiationData: this.radiationForm,
      TIData: this.TIForm,
      TransmittanceData: this.TransmittanceForm,
      resultData: this.resultForm,
      checkShow: this.isCheck,
      addBtn: this.addFlag,
      // 过滤后的measureBatchOption
      batchOption: [],
      addCalTempVisible: false,
      calTempData: [],
      calTempForm: {
        temp: null,
        calTempFile: null,
      },
      changeFlag: [],
      chartType: "",
      fileVisible: false,
      chartData: {},
      addMeasBatchForm: {
        engineId: null,
        measurementBatch: null,
      },
      addEngineForm: {
        model: null,
        geometryFiles: null,
        geometryImage: null
      },
      addStatusForm: {
        status: null,
        index: null
      },
      addAngleForm: {
        angle: null
      },
      engineOptions: [],
      measureBatchOptions: [],
      engineStatusOptions: [],
      angleOptions: [],
      addDialogVisible: false,
      addMeasVisible: false,
      addStatusVisible: false,
      addAngleVisible: false,
    };
  },
  created() {
    this.getListEngineModel();
    this.getListMeasBatch();
    this.getAngleOption();
    this.getStatusOption();
  },
  watch: {
    form: {
      handler(newVal, oldVal) {
        this.formData = newVal;
        if (newVal && oldVal && newVal.engineModel !== oldVal.engineModel) {
          this.batchOption = this.measureBatchOptions.filter(item => { return item.engineModel === newVal.engineModel })
        }
      },
      immediate: true,
      deep: true
    },
    radiationForm: {
      handler(newVal) {
        this.radiationData = newVal;
      },
      immediate: true,
      deep: true
    },
    TIForm: {
      handler(newVal) {
        this.TIData = newVal;
      },
      immediate: true,
      deep: true
    },
    TransmittanceForm: {
      handler(newVal) {
        this.TransmittanceData = newVal;
      },
      immediate: true,
      deep: true
    },
    resultForm: {
      handler(newVal) {
        this.resultData = newVal;
      },
      immediate: true,
      deep: true
    },
    isCheck: {
      handler(newVal) {
        this.checkShow = newVal;
      },
      immediate: true
    },
    addFlag: {
      handler(newVal) {
        this.addBtn = newVal;
      },
      immediate: true
    },
    footShow: {
      handler(newVal) {
        this.footShow = newVal;
      },
      immediate: true
    },
  },
  methods: {
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        const newName = name.slice(name.lastIndexOf("/") + 1)
        const names = newName.split(".")
        if ((names.size = 2) && (names[0].length > 19)) {
          return newName.substring(0, names[0].length - 19) + '.' + names[1]
        } else {
          return newName
        }
      } else {
        return "";
      }
    },
    // downloadFile(url){
    //   const name=this.getFileName(url)
    //   // this.download(
    //   //   "meas/calTempFile/export",
    //   //   `${name}_${new Date().getTime()}`
    //   // );
    // },
    addEngine() {
      this.loading = true;
      addEngineModel(this.addEngineForm).then((response) => {
        this.$modal.msgSuccess("新增成功");
        this.addDialogVisible = false;
        this.getListEngineModel();
        this.addEngineForm = {
          model: null,
          geometryFiles: null,
          geometryImage: null
        };
      });
    },
    // 增加测量批次
    addMeas() {
      addMeasBatch(this.addMeasBatchForm).then((response) => {
        this.$modal.msgSuccess("新增成功");
        this.addMeasVisible = false;
        this.getListMeasBatch();
        this.addMeasBatchForm = {
          engineId: null,
          measurementBatch: null,
        };
      });
    },
    // 增加状态
    addStatus() {
      addStatus(this.addStatusForm).then((response) => {
        this.$modal.msgSuccess("新增成功");
        this.addStatusVisible = false;
        this.getStatusOption();
        this.addStatusForm = {
          status: null,
          index: null
        }
      });
    },
    // 增加角度
    addAngle() {
      addAngle(this.addAngleForm).then((response) => {
        this.$modal.msgSuccess("新增成功");
        this.getAngleOption();
        this.addAngleVisible = false;
        this.addAngleForm = {
          angle: null
        }
      });
    },
    // 获取发电机List
    getListEngineModel() {
      this.loading = true;
      const data = { pageNum: 1, pageSize: 10000 };
      listEngineModel(data).then((response) => {
        this.engineOptions = response.rows;
        this.loading = false;
      });
    },
    // 获取测量批次List
    getListMeasBatch() {
      const data = { pageNum: 1, pageSize: 10000 };
      this.loading = true;
      listMeasBatch(data).then((response) => {
        this.measureBatchOptions = response.rows;
        if (this.form.engineModel) {
          this.batchOption = this.measureBatchOptions.filter(item => { return item.engineId === this.form.engineModel });
        }
        this.loading = false;
      });
    },
    // 获取角度Option
    getAngleOption() {
      this.loading = true;
      angleOption().then((response) => {
        this.angleOptions = response.data;
        this.loading = false;
      });
    },
    // 获取状态Option
    getStatusOption() {
      this.loading = true;
      statusOption().then((response) => {
        this.engineStatusOptions = response.data;
        this.loading = false;
      });
    },
    handleCloseBefore() {
      this.calTempData = []
    },
    getcalTempData(val) {
      if (val) {
        this.calTempData = JSON.parse(val)
      } else {
        this.calTempData = []
      }
    },
    onClickBtn(type) {
      if (type === "engine") this.addDialogVisible = true;
      else if (type === "measBatch") {
        if (this.form.engineModel) {
          let obj = {};
          obj = this.engineOptions.find((item) => {
            return item.id === this.form.engineModel;
          });
          // debugger
          this.addMeasBatchForm.engineId = obj.id
          this.engineChange(obj.id)
        }
        this.addMeasVisible = true;
      }
      else if (type === "engineStatus") this.addStatusVisible = true;
      else if (type === "engineAngle") this.addAngleVisible = true;
    },
    engineChange(val) {
      let obj = {};
      obj = this.engineOptions.find((item) => {
        return item.id === val;
      });
      this.addMeasBatchForm.measurementBatch = this.getTime() + '-' + obj?.model
    },
    getTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = ('0' + (now.getMonth() + 1)).slice(-2);
      const day = ('0' + now.getDate()).slice(-2);
      const hour = ('0' + now.getHours()).slice(-2);
      const minute = ('0' + now.getMinutes()).slice(-2);
      const second = ('0' + now.getSeconds()).slice(-2);
      const time = year + month + day + hour + minute + second;
      return time;
    },
    changeEngine(val) {
      let obj = {};
      obj = this.engineOptions.find((item) => {
        return item.id === val;
      });
      this.form.geometryFiles = obj?.geometryFiles
      this.form.geometryImage = obj?.geometryImage
      this.batchOption = this.measureBatchOptions.filter(item => { return item.engineId === val })
    },
    addCalTemp() {
      this.resetCalTempForm()
      this.addCalTempVisible = true
    },
    submitCalTemp() {
      console.log("this.calTempData", this.calTempData);
      this.calTempData.push(this.calTempForm)
      this.addCalTempVisible = false
      this.resetCalTempForm()
    },
    cancelCalTemp() {
      this.addCalTempVisible = false
      this.resetCalTempForm()
    },
    resetCalTempForm() {
      this.calTempForm = {
        temp: null,
        calTempFile: null,
      }
    },
    delCalTemp(row) {
      this.calTempData = this.calTempData.filter(item => {
        return item !== row
      });
    },
    // 环境参数保存
    envDataSave() {
      this.validateAll()
        .then(() => {
          this.$emit('env-data-save')
        })
        .catch((err) => {
          console.log("err", err);
          this.$message.error(`错误信息`, err);
        });

    },
    validateAll() {
      return Promise.all([
        this.$refs.headFormRef?.validate(),
        this.$refs.formRef?.validate(),
        this.$refs.radiationRef?.validate(),
        this.$refs.TIRef?.validate(),
        this.$refs.TransmittanceRef?.validate(),
        this.$refs.resultRef?.validate(),
      ]);
    },
    submitForm() {
      this.validateAll()
        .then(() => {
          if (this.radiationForm) {
            this.radiationForm.calTemp = this.calTempData.length > 0 ? JSON.stringify(this.calTempData) : null;
            this.calTempData = []
          }
          this.$emit('submit-form');
        })
        .catch((err) => {
          console.log("err", err);
          this.$message.error(`错误信息`, err);
        });
    },
    isObjectEqual(obj1, obj2) {
      if (obj1 === obj2) return true;
      if (typeof obj1 !== 'object' || obj1 === null || typeof obj2 !== 'object' || obj2 === null) {
        return false;
      }
      const keys1 = Object.keys(obj1);
      for (let key of keys1) {
        if (obj1[key] && typeof obj1[key] === 'object') {
          // 如果 obj1 的属性是对象，则递归比较
          if (!partialEqual(obj1[key], obj2[key])) {
            return false;
          }
        } else {
          // 否则，直接比较属性值
          if (obj1[key] !== obj2[key]) {
            return false;
          }
        }
      }
      return true;
    },
    cancel() {
      this.$emit('cancel')
    },
    // 查看文件可视化
    fileView(url1) {
      const url = `${process.env.VUE_APP_BASE_API}${url1}`;
      this.fetchLogFile(url)
        .then((text) => {
          this.fileShowData = text.split("\r\n");
          this.handleLineChart(this.fileShowData);
          this.fileVisible = true;
        })
        .catch((error) => {
          console.error("Failed to fetch the log file:", error);
          this.$modal.msgSuccess("文件读取错误");
        });
    },
    fileView2(url1) {
      const url = `${process.env.VUE_APP_BASE_API}${url1}`;
      this.fetchLogFile(url)
        .then((text) => {
          this.fileShowData = text.split("\r\n");
          this.handleHeatmapChart(this.fileShowData);
          this.fileVisible = true;
        })
        .catch((error) => {
          console.error("Failed to fetch the log file:", error);
          this.$modal.msgSuccess("文件读取错误");
        });
    },
    // 读取文件内容
    async fetchLogFile(url) {
      try {
        const response = await fetch(url, { method: "GET" });
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return await response.text();
      } catch (error) {
        throw error;
      }
    },
    // echarts数据
    handleLineChart(data) {
      this.chartType = "line";
      const data1 = data[0].replace(/\s+/g, " ").split(" ");
      const customName = data1.map(label => ({ [label + 'Data']: [] }))
      let yAxis = [], series = []
      for (let i = 1; i < data.length; i++) {
        let row = data[i].split("\t");
        customName.forEach((item, index) => {
          for (let key in item) {
            item[key].push(parseFloat(row[index]))
          }
        })
      }
      // delete data1[Object.keys(data1)[0]]
      customName.forEach((item, index) => {
        if (index === 0) return
        else {
          yAxis.push({
            type: "value",
            name: data1[index],
            position: index === 1 ? 'left' : 'right',
            alignTicks: true,
            axisLine: {
              show: true,
            },
          })
          series.push({
            name: data1[index],
            type: "line",
            data: item[Object.keys(item)[0]],
          },)
        }
      })
      const chartData = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
        },
        xAxis: [
          {
            type: "category",
            name: data1[0],
            axisTick: {
              alignWithLabel: true,
            },
            axisLine: {
              show: true,
            },

            data: Object.values(customName[0])[0],
          },
        ],
        yAxis: yAxis,
        series: series,
      };
      this.chartData = JSON.parse(JSON.stringify(chartData))
    },
    handleHeatmapChart(data) {
      this.chartType = "heatmap";
      let dataSet = [],
        xData = [],
        yData = [];
      let min = Infinity; // 初始化最小值为无穷大
      let max = -Infinity; // 初始化最大值为负无穷大
      const num = Math.ceil(Math.sqrt(data.length));
      for (let i = 0; i < num; i++) {
        xData.push(i);
      }
      let x = 0,
        y = 0;
      for (let i = 15; i < data.length; i++) {
        let row = parseFloat(data[i].split(","));
        dataSet.push([y++, x, parseFloat(row)]);
        if (row > max) max = row;
        if (row < min) min = row;
        if (y === num) {
          yData.push(x);
          x++;
          y = 0;
        }
      }
      const chartData = {
        tooltip: {},
        xAxis: {
          type: "category",
          data: xData,
        },
        yAxis: {
          type: "category",
          data: yData,
        },
        visualMap: {
          min: min,
          max: max,
          calculable: true,
          precision: 4,
          inRange: {
            color: ["#FFFFFF", "#000000"],
          },
        },
        series: [
          {
            name: "辐射亮度",
            type: "heatmap",
            data: dataSet,
            emphasis: {
              itemStyle: {
                borderColor: "#333",
                borderWidth: 1,
              },
            },
            progressive: 1000,
            animation: false,
          },
        ],
      };
      this.chartData = JSON.parse(JSON.stringify(chartData))
    },
  },
};
</script>
<style scoped lang="scss">
.box {
  border: 1px solid #dcdfe6;
  border-radius: 10px;
  padding: 20px 15px 0px 15px;
  margin-top: 20px;
  position: relative;

  .title {
    padding: 10px;
    background-color: white;
    position: absolute;
    top: -20px;
    font-weight: 700;
    font-size: 1rem;
  }
}

::v-deep .el-upload--picture-card {
  width: 80px;
  height: 80px;
  line-height: 86px
}

::v-deep .el-upload-list--picture-card .el-upload-list__item {
  width: 80px;
  height: 80px;
}

::v-deep .el-form-item__content {
  max-width: 200px;
}

::v-deep .el-form-item__error {
  width: 190px;
}

::v-deep .calTempTabel .el-form-item__content {
  max-width: 600px;
}

::v-deep .el-input-group__append {
  padding: 0 10px;
}

.chartShow {
  margin: 0 auto;
}

.footerBtn {
  transform: translateX(40%);
  margin-top: 20px;
}

::v-deep .el-form-item .el-select {
  width: 200px;
}

::v-deep .el-form-item .el-input {
  width: 200px;
}

::v-deep .el-form-item .upload-file {
  width: 200px;
}

::v-deep .ele-upload-list__item-content-action {
  width: 60px;
}
</style>
