<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="测量批次id" prop="measurementBatchId" label-width="90px">
        <el-input v-model="queryParams.measurementBatchId" placeholder="请输入测量批次id" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="发动机状态" prop="engineStatus" label-width="90px">
        <el-select v-model="queryParams.engineStatus" placeholder="请选择发动机状态" clearable>
          <el-option v-for="item in engineStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="角度" prop="angle">
        <el-select v-model="queryParams.angle" placeholder="请选择角度" clearable>
          <el-option v-for="item in angleOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="测试距离" prop="testDistance">
        <el-input v-model="queryParams.testDistance" placeholder="请输入测试距离" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="时间" prop="time">
        <el-date-picker clearable v-model="queryParams.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="queryParams.location" placeholder="请输入地点" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="大气压" prop="atmosPress">
        <el-input v-model="queryParams.atmosPress" placeholder="请输入大气压" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="温度" prop="temperature">
        <el-input v-model="queryParams.temperature" placeholder="请输入温度" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="风速" prop="windSpeed">
        <el-input v-model="queryParams.windSpeed" placeholder="请输入风速" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="湿度" prop="humidity">
        <el-input v-model="queryParams.humidity" placeholder="请输入湿度" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="CO₂浓度" prop="concentration">
        <el-input v-model="queryParams.concentration" placeholder="请输入CO₂浓度" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['meas:envData:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['meas:envData:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['meas:envData:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['meas:envData:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="envDataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="测量批次id" align="center" prop="measurementBatchId" />
      <el-table-column label="发动机状态" align="center" prop="engineStatus" />
      <el-table-column label="角度" align="center" prop="angle" />
      <el-table-column label="涡轮后温度" align="center" prop="turbinePostTemp" />
      <el-table-column label="测试距离" align="center" prop="testDistance" />
      <el-table-column label="时间" align="center" prop="time">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.time, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地点" align="center" prop="location" />
      <el-table-column label="大气压" align="center" prop="atmosPress" />
      <el-table-column label="温度" align="center" prop="temperature" />
      <el-table-column label="风速" align="center" prop="windSpeed" />
      <el-table-column label="湿度" align="center" prop="humidity" />
      <el-table-column label="CO₂浓度" align="center" prop="concentration" />
      <!-- <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['meas:envData:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['meas:envData:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改测量环境数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :model="engineForm" :rules="rules" size="mini" label-width="80px">
        <el-row type="flex" justify="space-around">
          <el-form-item label="发动机型号" prop="model" label-width="90px">
            <el-select v-model="engineForm.model" placeholder="请选择发动机型号">
              <el-option v-for="item in engineModelList" :key="item.id" :label="item.model" :value="item.id">
              </el-option>
              <el-option :value="undefined" disabled 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">
            <file-upload :fileSize="0" :limit="1" :fileType="['x_t', 'str']" v-model="engineForm.geometryFiles" />
          </el-form-item>
          <el-form-item label="" prop="geometryImage">
            <image-upload :fileSize="0" :limit="1" :fileType="['jpg']" v-model="engineForm.geometryImage"
              :isPicCard="false" />
          </el-form-item>
        </el-row>
      </el-form>
      <el-form ref="form" :model="form" :rules="rules" size="mini" label-width="80px">
        <el-form-item label="测量批次" prop="measurementBatch" style="margin-left: 5%">
          <el-select v-model="form.measurementBatchId" placeholder="请选择测量批次">
            <el-option v-for="item in measureBatchOptions" :key="item.id" :label="item.measurementBatch"
              :value="item.id">
              <span style="float: left">{{ item.id }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
      item.measurementBatch
    }}</span>
            </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>
      <div class="box">
        <span class="title">环境参数</span>
        <el-form ref="form" :model="form" size="mini" :rules="rules" label-width="80px">
          <el-row type="flex" justify="space-around">
            <el-form-item label="发动机状态" label-width="100px" prop="engineStatus">
              <el-select v-model="form.engineStatus" placeholder="请选择发动机状态">
                <el-option v-for="item in engineStatusOptions" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="角度" prop="angle">
              <el-select v-model="form.angle" placeholder="请输入角度">
                <el-option v-for="item in angleOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="涡轮后温度" prop="turbinePostTemp" label-width="90px">
              <file-upload :fileSize="0" :limit="1" :fileType="['txt']" v-model="form.turbinePostTemp" />
            </el-form-item>
          </el-row>
          <el-row type="flex" justify="space-around">
            <el-form-item label="测试距离" prop="testDistance">
              <el-input v-model="form.testDistance" placeholder="请输入测试距离" />
            </el-form-item>
            <el-form-item label="时间" prop="time">
              <el-date-picker clearable v-model="form.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="form.location" placeholder="请输入地点" />
            </el-form-item>
          </el-row>
          <el-row type="flex" justify="space-around">
            <el-form-item label="大气压" prop="atmosPress">
              <el-input v-model="form.atmosPress" placeholder="请输入大气压（单位：pa）" />
            </el-form-item>
            <el-form-item label="温度" prop="temperature">
              <el-input v-model="form.temperature" placeholder="请输入温度（单位：K）" />
            </el-form-item>
            <el-form-item label="风速" prop="windSpeed">
              <el-input v-model="form.windSpeed" placeholder="请输入风速（单位：m/s）" />
            </el-form-item>
          </el-row>
          <el-row type="flex" justify="space-around">
            <el-form-item label="湿度" prop="humidity">
              <el-input v-model="form.humidity" placeholder="请输入湿度（单位：%）" />
            </el-form-item>
            <el-form-item label="CO₂浓度" prop="concentration">
              <el-input v-model="form.concentration" placeholder="请输入浓度（单位：mol）" />
            </el-form-item>
            <el-col :span="7">
              <el-button type="primary" size="mini" @click="envDataSave">保 存</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="box">
        <span class="title">光谱辐射计测量数据</span>
        <el-form ref="radiationForm" size="mini" :model="radiationForm" :rules="rules" :disabled="disabled"
          label-width="80px">
          <el-row type="flex" justify="space-around">
            <el-form-item label="型号" prop="model">
              <el-input v-model="radiationForm.model" placeholder="请输入型号" />
            </el-form-item>
            <el-form-item label="镜头视场角" prop="lensFView" label-width="90px">
              <el-input v-model="radiationForm.lensFView" placeholder="请输入镜头视场角(单位：mrad)" />
            </el-form-item>
            <el-form-item label="增益" prop="gain">
              <el-input v-model.number="radiationForm.gain" placeholder="请输入增益(单位：x)" />
            </el-form-item>
          </el-row>
          <el-row type="flex" justify="space-around">
            <el-form-item label="背景数据" prop="backgroundData">
              <file-upload :fileSize="0" :limit="1" :fileType="['lgm']" v-model="radiationForm.backgroundData" />
            </el-form-item>
            <el-form-item label="标定温度" prop="calTemp">
              <el-input v-model="radiationForm.calTemp" placeholder="请输入标定温度" />
            </el-form-item>
            <el-form-item label="标定曲线" prop="calCurve">
              <file-upload :fileSize="0" :limit="5" :fileType="['txt']" :isShowViev="true"
                v-model="radiationForm.calCurve" v-on:fileView="fileView" />
            </el-form-item>
          </el-row>
        </el-form>
        <div class="box" style="margin-bottom: 15px">
          <span class="title">目标数据</span>
          <el-form ref="radiationForm" size="mini" :model="radiationForm" :disabled="disabled" :rules="rules"
            label-width="80px">
            <el-row type="flex" justify="space-around">
              <el-form-item label="原始数据" prop="rawData">
                <file-upload :fileSize="0" :limit="5" :fileType="['txt']" v-model="radiationForm.rawData" />
              </el-form-item>
              <el-form-item label="辐射亮度3~5μm" label-width="130px" prop="radiance1">
                <file-upload :fileSize="0" :limit="1" :fileType="['txt']" v-model="radiationForm.radiance1" :isShowViev="true" v-on:fileView="fileView" />
              </el-form-item>
              <el-form-item label="辐射亮度8~14μm" label-width="130px" prop="radiance2">
                <file-upload :fileSize="0" :limit="1" :fileType="['txt']" v-model="radiationForm.radiance2" />
              </el-form-item>
            </el-row>
          </el-form>
        </div>
      </div>
      <div class="box">
        <span class="title">热像仪测量数据</span>
        <el-form ref="TIForm" :model="TIForm" size="mini" :rules="rules" :disabled="disabled" label-width="80px">
          <el-row type="flex" justify="space-around">
            <el-form-item label="型号" prop="model">
              <el-input v-model="TIForm.model" placeholder="请输入型号" />
            </el-form-item>
            <el-form-item label="镜头视场角" label-width="90px" prop="lensFView">
              <el-select v-model="TIForm.lensFView" placeholder="请选择镜头视场角">
                <el-option v-for="item in lensFViewOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="滤镜编号" prop="filterNo">
              <el-select v-model="TIForm.filterNo" placeholder="请选择滤镜编号">
                <el-option v-for="item in filterNoOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row type="flex" justify="space-around">
            <el-form-item label="帧率" prop="fps">
              <el-select v-model="TIForm.fps" placeholder="请选择帧率">
                <el-option v-for="item in fpsOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select> </el-form-item><el-form-item label="波段" prop="spectralBand">
              <el-select v-model="TIForm.spectralBand" placeholder="请选择波段">
                <el-option v-for="item in spectralBandOptions" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="积分时间" prop="integrationTime">
              <el-input v-model.number="TIForm.integrationTime" placeholder="请输入积分时间(单位：s)" />
            </el-form-item>
          </el-row>
          <el-row type="flex" justify="space-around">
            <el-form-item label="温度标定" prop="tempCal">
              <file-upload :fileSize="0" :limit="1" :fileType="['txt']" v-model="TIForm.tempCal" />
            </el-form-item>
            <el-form-item label="辐射亮度" prop="radiance">
              <file-upload :fileSize="0" :limit="1" :fileType="['txt']" v-model="TIForm.radiance" :isShowViev="true"
                v-on:fileView="fileView2" />
            </el-form-item>
            <el-form-item label="辐射照度" prop="radIllumination">
              <file-upload :fileSize="0" :limit="1" :fileType="['txt']" v-model="TIForm.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 :fileSize="0" :limit="1" :fileType="['txt']" v-model="TIForm.radTemp" :isShowViev="true" v-on:fileView="fileView"/>
            </el-form-item>
            <el-col :span="7"></el-col>
            <el-col :span="7"></el-col>
          </el-row>
        </el-form>
      </div>
      <div class="box">
        <span class="title">透过率数据</span>
        <el-form ref="TransmittanceForm" :model="TransmittanceForm" :rules="rules" :disabled="disabled"
          label-width="80px">
          <el-row type="flex" justify="space-around">
            <el-form-item label="原始数据" prop="rawData">
              <file-upload :fileSize="0" :limit="1" :fileType="['txt']" v-model="TransmittanceForm.rawData" />
            </el-form-item>
            <el-form-item label="透过率曲线3~5μm" label-width="130px" prop="curve1">
              <file-upload :fileSize="0" :limit="1" :fileType="['txt']" :isShowViev="true" v-on:fileView="fileView" v-model="TransmittanceForm.curve1" />
            </el-form-item>
            <el-form-item label="透过率曲线8~14μm" label-width="135px" prop="curve2">
              <file-upload :fileSize="0" :limit="1" :fileType="['txt']" v-model="TransmittanceForm.curve2" :isShowViev="true" v-on:fileView="fileView"/>
            </el-form-item>
          </el-row>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="增加发动机型号" :visible.sync="addDialogVisible" width="400px" append-to-body>
      <el-input v-model="engineModel" placeholder="请输入发动机型号">
        <template slot="prepend">发动机型号</template>
      </el-input>
      <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 title="增加测量批次" :visible.sync="addMeasVisible" width="400px" append-to-body>
      <el-form ref="form" :model="addMeasBatchForm" :rules="rules" label-width="80px">
        <el-form-item label="发动机型号ID" label-width="110px" prop="engineId">
          <el-select v-model="addMeasBatchForm.engineId" placeholder="请选择发动机型号ID">
            <el-option v-for="item in engineModelList" :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 title="数据可视化" :visible.sync="fileVisible" width="70%" append-to-body>
      <ECharts :class="chartType === 'heatmap'?'heatmapChart':''" :chartData="chartData" :width="chartType === 'heatmap'?'400px':'100%'" />
    </el-dialog>
  </div>
</template>

<script>
import {
  listEnvData,
  getEnvData,
  delEnvData,
  addEnvData,
  updateEnvData,
} from "@/api/meas/envData";
import {
  listEngineModel,
  addEngineModel,
  getEngineModel,
  updateEngineModel,
} from "@/api/meas/engineModel";
import { listMeasBatch, addMeasBatch } from "@/api/meas/measBatch";
import {
  addRadiation,
  getRadiation,
  updateRadiation,
  listRadiation,
} from "@/api/meas/radiation";
import {
  addThermalImagerTesDdata,
  listThermalImagerTesDdata,
  updateThermalImagerTesDdata,
} from "@/api/meas/thermalImagerTesDdata";
import {
  addTransmissionRate,
  listTransmissionRate,
  updateTransmissionRate,
} from "@/api/meas/transmissionRate";
import ECharts from "./ECharts.vue";

export default {
  name: "EnvData",
  components: { ECharts},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 测量环境数据表格数据
      envDataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      addDialogVisible: false,
      addMeasVisible: false,
      fileVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        measurementBatchId: null,
        engineStatus: null,
        angle: null,
        turbinePostTemp: null,
        testDistance: null,
        time: null,
        location: null,
        atmosPress: null,
        temperature: null,
        windSpeed: null,
        humidity: null,
        concentration: null,
      },
      // engineQueryParams:{
      //   pageNum: 1,
      //   pageSize: 10,
      // },
      // 表单参数
      form: {},
      radiationForm: {},
      TIForm: {},
      TransmittanceForm: {},
      engineForm: {},
      // 表单校验和验证
      rules: {
        measurementBatchId: [
          { required: true, message: "测量批次id不能为空", trigger: "blur" },
        ],
        engineStatus: [
          { required: true, message: "发动机状态不能为空", trigger: "change" },
        ],
        angle: [{ required: true, message: "角度不能为空", trigger: "change" }],
        testDistance: [
          {
            pattern: /^(0(\.\d{1,2})?|[1-9]\d{0,2}(\.\d{1,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{1,2})?|1500(\.00?)?)$/,
            message: "请输入0.00-1500.00pa之间的数字,最多可保留两位小数",
            trigger: "blur",
          },
        ],
        temperature: [
          {
            pattern: /^(230|2[3-9]\d|30\d|31\d|320)(\.\d{2})?$/,
            message: "请输入230.00-320.00K之间的数字,最多可保留两位小数",
            trigger: "blur",
          },
        ],
        windSpeed: [
          {
            pattern: /^(0(\.\d{1,2})?|[1-9]\d{0,2}(\.\d{1,2})?|1000(\.00?)?)$/,
            message: "请输入0.00-1000.00m/s之间的数字,最多可保留两位小数",
            trigger: "blur",
          },
        ],
        humidity: [
          {
            pattern: /(^(\d|[1-9]\d)(\.\d{1,2})?$)|(^100$)/,
            message: "请输入0.00-100.00%之间的数字,最多可保留两位小数",
            trigger: "blur",
          },
        ],
        concentration: [
          {
            pattern: /^(0(\.\d{1,2})?|[1-9]\d{0,2}(\.\d{1,2})?|1000(\.00?)?)$/,
            message: "请输入0.00-1000.00mol之间的数字,最多可保留两位小数",
            trigger: "blur",
          },
        ],
      },
      // 发动机状态
      engineStatusOptions: [
        { label: "最大", value: 1 },
        { label: "连续", value: 2 },
        { label: "最小", value: 3 },
      ],
      // 角度状态
      angleOptions: [
        { label: "15°", value: 1 },
        { label: "20°", value: 2 },
        { label: "30°", value: 3 },
      ],
      // 热像仪测试
      lensFViewOptions: [],
      filterNoOptions: [],
      fpsOptions: [],
      spectralBandOptions: [],
      measureBatchOptions: [],
      engineModelList: [],
      engineModel: "",
      addMeasBatchForm: {
        engineId: null,
        measurementBatch: null,
      },
      fileShowData: [],
      disabled: false,
      chartData: {},
      chartType: "",
    };
  },
  created() {
    this.getList();
    this.getListEngineModel();
    this.getListMeasBatch();
  },
  methods: {
    /** 查询测量环境数据列表 */
    getList() {
      this.loading = true;
      listEnvData(this.queryParams).then((response) => {
        this.envDataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取发电机List
    getListEngineModel() {
      this.loading = true;
      const data = {};
      listEngineModel(data).then((response) => {
        this.engineModelList = response.rows;
        this.loading = false;
      });
    },
    // 获取测量批次List
    getListMeasBatch() {
      const data = {};
      this.loading = true;
      listMeasBatch(data).then((response) => {
        this.measureBatchOptions = response.rows;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 保存环境参数
    envDataSave() {
      // 保存环境参数，返回一个环境数据ID
      this.$refs["form"].validate((valid) => {
        console.log("11", valid, this.form);
        if (valid) {
          if (this.form.id != null) {
            updateEnvData(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.getList();
            });
          } else {
            addEnvData(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.getList();
            });
          }
        }
      });
    },
    // 点击增加按钮
    onClickBtn(type) {
      if (type === "engine") this.addDialogVisible = true;
      else if (type === "measBatch") this.addMeasVisible = true;
    },
    // 增加发动机型号
    addEngine() {
      this.loading = true;
      const form = {
        model: this.engineModel,
      };
      addEngineModel(form).then((response) => {
        this.$modal.msgSuccess("新增成功");
        this.addDialogVisible = false;
        this.getListEngineModel();
        this.engineModel = null;
      });
    },
    // 增加测量批次
    addMeas() {
      addMeasBatch(this.addMeasBatchForm).then((response) => {
        this.$modal.msgSuccess("新增成功");
        this.addMeasVisible = false;
        this.getListMeasBatch();
        this.addMeasBatchForm = {
          engineId: null,
          measurementBatch: null,
        };
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        measurementBatchId: null,
        engineStatus: null,
        angle: null,
        turbinePostTemp: null,
        testDistance: null,
        time: null,
        location: null,
        atmosPress: null,
        temperature: null,
        windSpeed: null,
        humidity: null,
        concentration: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.engineForm = {
        model: null,
        geometryFiles: null,
        geometryImage: null,
      };
      this.radiationForm = {
        model: null,
        lensFView: null,
        gain: null,
        backgroundData: null,
        calTemp: null,
        calCurve: null,
        rawData: null,
        radiance1: null,
        radiance2: null,
      };
      this.TIForm = {
        model: null,
        lensFView: null,
        filterNo: null,
        fps: null,
        spectralBand: null,
        integrationTime: null,
        tempCal: null,
        radiance: null,
        radIllumination: null,
        radTemp: null,
      };
      this.TransmittanceForm = {
        rawData: null,
        curve1: null,
        curve2: null,
      };
      this.resetForm("form");
      this.resetForm("engineForm");
      this.resetForm("radiationForm");
      this.resetForm("TIForm");
      this.resetForm("TransmittanceForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加测量环境数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const measId = {
        measurementBatchId: row.measurementBatchId,
      };
      console.log("measId", measId);
      const id = row.id || this.ids;
      // 通过measId来查找，不具有唯一性吧。一个测量批次可以绑定多个光谱辐射数据吧。。。。
      listEngineModel(measId).then((response) => {
        console.log("getEngineModelRes", response);
        this.engineForm = response.rows[0];
      });
      listRadiation(measId).then((response) => {
        this.radiationForm = response.rows[0];
      });
      listThermalImagerTesDdata(measId).then((response) => {
        this.TIForm = response.rows[0];
      });
      listTransmissionRate(measId).then((response) => {
        this.TransmittanceForm = response.rows[0];
      });
      getEnvData(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改测量环境数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.TIForm["measurementBatchId"] = this.form.measurementBatchId;
      this.TransmittanceForm["measurementBatchId"] =
        this.form.measurementBatchId;
      this.radiationForm["measurementBatchId"] = this.form.measurementBatchId;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateRadiation(this.radiationForm).then((response) => { });
            updateThermalImagerTesDdata(this.TIForm).then((response) => { });
            updateTransmissionRate(this.TransmittanceForm).then(
              (response) => { }
            );
            updateEnvData(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRadiation(this.radiationForm).then((response) => { });
            addThermalImagerTesDdata(this.TIForm).then((response) => { });
            addTransmissionRate(this.TransmittanceForm).then((response) => { });
            addEnvData(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除测量环境数据编号为"' + ids + '"的数据项？')
        .then(function () {
          return delEnvData(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "meas/envData/export",
        {
          ...this.queryParams,
        },
        `envData_${new Date().getTime()}.xlsx`
      );
    },
    // 查看文件可视化
    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]))
          }
        })
      }
      console.log("customName",customName);
      // 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]],
            },)
          }
      })
      console.log("11",Object.values(customName[0])[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";
      // console.log("data",data);
      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;
        }
      }
      console.log("dataSet", dataSet);
      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;
  }
}

.heatmapChart {
  transform: translateX(80%);
}

::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;
}
</style>
