<template>
  <div>
    <el-container>
      <el-header class="el-header">
        <el-form ref="queryFormRef" class="el-form" :model="queryParams" :inline="true" @keyup.enter.native="queryList">
          <el-form-item label="设备SN">
            <el-input v-model="queryParams.deviceSn" placeholder="设备SN" width="120px" maxlength="11" clearable
              show-word-limit />
          </el-form-item>
          <el-form-item label="遥测站编码">
            <el-input v-model="queryParams.stationCode" placeholder="遥测站编码" width="120px" maxlength="10" show clearable
              show-word-limit />
          </el-form-item>
          <el-form-item label="站点名称">
            <el-autocomplete v-model="state.search_StationName" style="width:220px" clearable
              :fetch-suggestions="querySearchAsync" :trigger-on-focus="false" placeholder="输入关键字或拼音码"
              @select="handleSelect" @keyup.enter="handleKeyup"
              @input="changeStyle('block', '.el-autocomplete-suggestion')"
              @keyup="changeStyle('block', '.el-autocomplete-suggestion')" />
          </el-form-item>
          <el-form-item label="时间范围">
            <el-config-provider :locale="locale">
              <el-date-picker v-model="state.defaultTime" type="daterange" start-placeholder="开始时间" style="width: 230px;"
                end-placeholder="结束时间" :default-time="state.defaultTime" value-format="YYYY-MM-DDTHH:mm:ss" />
            </el-config-provider>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="button" :disabled="state.search_disabled" @click="queryList">
              查 询
            </el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <el-main class="el-main">
        <el-tabs type="border-card" class="el-tabs" @tab-click="handleClick">
          <el-tab-pane label="列表">

            <el-table v-loading="loading" :data="state.tableData" border stripe style="width: 100%" ref="my_table"
              :height="tableHeight" highlight-current-row @current-change="handleCurrentRowChange"
              @cell-dblclick="celldblclick" :header-cell-style="{ background: '#FF000000', color: '#000000' }">

              <el-table-column fixed type="index" width="50" align="center" />
              <!-- 先改成和工作数据一样的列了,内部方便看数据(后面一样是内部看详细,客户看简要) 2022-07-08 guozhao -->
              <el-table-column fixed prop="deviceSn" label="设备" header-align="center" width="200">
                <template #default="scope">
                  <el-space direction="vertical" alignment="start">
                    <span :title="scope.row.stationName" style="color: black;display: inline-block;font-size: 0.95em;">{{
                      scope.row.stationName
                    }}</span>
                    <div style="display: flex;align-items: center;">
                      <span title="点击查看设备配置" @click="showDevCfg(scope.row)"
                        style="color: blue;display: inline-block;font-size: 0.95em;cursor:pointer;text-decoration: underline;text-underline-offset: 3px;">{{
                          'SN:&nbsp' + scope.row.deviceSn
                        }}</span>
                      <el-icon style="margin-left: 8px;cursor: pointer;" title="点击快速添加远程配置任务" v-if="userType === '0'"
                        @click="openRemoteCfg(scope.row)">
                        <Tools />
                      </el-icon>
                    </div>
                    <span style="color: black;font-size: 0.95em;">{{
                      'ID&nbsp&nbsp:&nbsp' + scope.row.stationCode
                    }}</span>
                  </el-space>
                </template>
              </el-table-column>

              <!-- <el-table-column fixed prop="deviceSn" label="设备SN" header-align="center" width="120" /> -->
              <el-table-column label="图片" header-align="center" width="150" resizable="false">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <el-image :src="scope.row.src" :preview-src-list="scope.row.srcList" :hide-on-click-modal="true"
                      :close-on-press-escape="true" slot="error" :title="global.getImageNameTip(scope.row.src)"
                      :style="!tool.stringIsNullOrEmpty(scope.row.src) && scope.row.src.includes('bmp') ? 'border:1.5px solid #F00;' : ''">
                      <template #error>
                        <div slot="error" class="image-slot">
                          <!-- <el-icon><icon-picture /></el-icon> -->
                          <i class="el-icon-picture-outline"
                            style="font-size: 30px;text-align: center;display: block;width: 120px;"></i>
                          <span style="color: red;text-align: center;display: block;"
                            v-if="scope.row.funCode === '52'">补发报(无图)</span>
                          <span style="color: red;display:inline-block;width:120px;text-align:center;"
                            v-if="scope.row.funCode !== '52'">图片异常</span>
                        </div>
                      </template>
                    </el-image>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="读数信息" header-align="center" width="135">
                <template #default="scope">
                  <el-space direction="vertical" alignment="start">
                    <el-tag size="small">结果：<span style="color: blue">{{ global.formatDecimal(userType ===
                      '0' ? scope.row.identValue : scope.row.resultValue, scope.row.decimalDigits)
                    }}</span><span v-if="scope.row.deviceType === '2'">&nbsp;{{ scope.row.deviceUnitName }}</span>
                    </el-tag>
                    <el-tag size="small" v-if="userType === '0' && scope.row.deviceType !== '2'">原始：<span
                        style="color: green">{{
                          global.formatDecimal(scope.row.rawValue, scope.row.decimalDigits)
                        }}</span>
                    </el-tag>
                    <el-tag size="small"
                      v-if="userType === '0' && scope.row.serverReadModel !== null && scope.row.serverReadModel.goodFlag !== '4' && scope.row.deviceType !== '2'">服务：<span
                        style="color: red;cursor:pointer;" @click="openServerImage(scope.row)">{{
                          global.getGoodFlagContent(scope.row.serverReadModel, scope.row.decimalDigits)
                        }}</span>
                    </el-tag>

                    <!-- 下面是内部用户发现服务侧识别显示没有配置时可快速创建召测配置 -->
                    <el-tag size="small"
                      v-if="userType === '0' && scope.row.serverReadModel !== null && scope.row.serverReadModel.goodFlag === '4' && scope.row.deviceType !== '2'">服务：<span
                        @click="createTaskDown(scope.row)"
                        style="color: red;cursor:pointer;text-decoration: underline;font-size: 15px;text-underline-offset: 3px;font-weight: bold;">{{
                          global.getGoodFlagContent(scope.row.serverReadModel, scope.row.decimalDigits)
                        }}</span>
                    </el-tag>
                  </el-space>
                </template>
              </el-table-column>
              <el-table-column label="时间" header-align="center" width="186">
                <template #default="scope">
                  <el-space direction="vertical" alignment="start">
                    <!-- <el-tag size="small" style="font-weight: bold;width: 158px">采样：<span
                                            style="color: blue;font-weight: bold;">{{
                                                    tool.dateFormatYMDHm(scope.row.sampleTime)
                                            }}</span></el-tag>
                                    <el-tag size="small" v-if="userType === '0'">发报：<span style="color: green">{{
                                            tool.dateFormat(scope.row.rptTime)
                                    }}</span>
                                    </el-tag>
                                    <el-tag size="small" v-if="userType === '0'">接收：<span style="color: red">{{
                                            tool.dateFormat(scope.row.revTime)
                                    }}</span>
                                    </el-tag> -->
                    <span style="color: blue;font-weight: normal;font-size: 0.95em;">{{
                      "采样：" + tool.dateFormatYMDHm(scope.row.sampleTime, 'YYYYMMDDHHmmss', 'YY-MM-DD HH:mm:ss')
                    }}<span v-if="scope.row.ip1SendStatus"
                        :style="scope.row.ip1SendStatus == 1 ? 'color:limegreen' : 'color:red'"
                        :title="global.getIp1SendStatusTip(scope.row.ip1SendStatus)">&nbsp●</span></span>
                    <span style="color: green;font-size: 0.95em;">{{
                      "发报：" + tool.dateFormat(scope.row.rptTime, 'YYYYMMDDHHmmss', 'YY-MM-DD HH:mm:ss')
                    }}</span>
                    <span style="color: #000000;font-size: 0.95em;">{{
                      "接收：" + tool.dateFormat(scope.row.revTime, 'YYYYMMDDHHmmss', 'YY-MM-DD HH:mm:ss')
                    }}</span>
                  </el-space>
                </template>
              </el-table-column>
              <el-table-column label="工作参数" header-align="center" width="120">
                <template #default="scope">
                  <el-space direction="vertical" alignment="start">
                    <!-- <el-tag size="small">信号：<span style="color: blue">{{ scope.row.rsrp }}</span>
                                    </el-tag>
                                    <el-tag size="small">电压：<span style="color: green">{{ scope.row.voltage }}</span>
                                    </el-tag>
                                    <el-tag size="small" v-if="userType === '0'">信噪比：<span style="color: red">{{
                                            scope.row.snr
                                    }}</span>
                                    </el-tag> -->
                    <span style="color: blue;font-size: 0.95em;" :title="`NB位置信息:${scope.row.nbRegLocation}`">{{
                      "信号&nbsp&nbsp&nbsp&nbsp：" +
                      scope.row.rsrp

                    }}</span>
                    <span style="color: green;font-size: 0.95em;" :title="`电池运行时间:${scope.row.batRumTime}`">{{
                      "电压&nbsp&nbsp&nbsp&nbsp：" +
                      scope.row.voltage

                    }}</span>
                    <span v-if="userType === '0'" style="color: black;font-size: 0.95em;">信噪比&nbsp：{{
                      scope.row.snr
                    }}</span>
                  </el-space>
                </template>
              </el-table-column>

              <el-table-column label="工作情况" header-align="center" width="120" v-if="userType === '0'">
                <template #default="scope">
                  <el-space direction="vertical" alignment="start">
                    <span style="color: blue;font-size: 0.95em;">{{ "工作时长:" +
                      tool.getValueFormat(scope.row.intervalMinutes, 's')
                    }}</span>
                    <span style="color: green;font-size: 0.95em;">{{ "传输时长:" +
                      tool.getValueFormat(scope.row.tranDuration, 's')
                    }}</span>
                    <span
                      :style="scope.row.loseFlag === '1' ? 'color: Red;font-size: 0.95em;font-weight: bold' : 'color: black;font-size: 0.95em;'">{{
                        "计次:" +
                        tool.getValueFormat(scope.row.mcuRunNum, '')
                      }}</span>
                  </el-space>
                </template>
              </el-table-column>

              <el-table-column label="设备版本" header-align="center" width="180">
                <template #default="scope">
                  <el-space direction="vertical" alignment="start">
                    <el-tag size="small">MCU：<span style="color: blue" :title="`MCU运行次数:${scope.row.mcuRunNum}`">{{
                      scope.row.softVer
                    }}</span></el-tag>
                    <el-tag size="small">AI&nbsp&nbsp&nbsp&nbsp：<span style="color: green">{{
                      scope.row.aiVersion
                    }}</span></el-tag>
                    <el-row v-if="userType === '0'">
                      <el-col :span="13">
                        <el-tag size="small">CPU：<span style="color: red">{{ scope.row.hardVersion
                        }}</span></el-tag>
                      </el-col>
                      <el-col :span="11">
                        <el-tag size="small" style="width: 75px;">NB：<span style="color: red">{{
                          scope.row.nbVersion
                        }}</span></el-tag>
                      </el-col>
                    </el-row>
                  </el-space>
                </template>
              </el-table-column>
              <el-table-column fit label="调试信息" header-align="center" width="410" v-if="userType === '0'">
                <template #default="scope">
                  <el-row>
                    <el-col>
                      <span style="font-size:12px;" v-for="(item, i) in scope.row.alist">{{
                        global.debugInfoFormat(item, i)
                      }}</span>
                    </el-col>
                  </el-row>

                  <el-row>
                    <el-col>
                      <span style="font-size:12px;" v-for="(item, i) in scope.row.blist">{{
                        global.debugInfoFormat(item, i)
                      }}</span>
                    </el-col>
                  </el-row>

                  <el-row v-if="scope.row.serverAList">
                    <el-divider style="margin-top: -2px;margin-bottom: -5px;height: 1px;" />
                  </el-row>
                  <el-row v-if="scope.row.serverAList">
                    <el-col>
                      <span style="font-size:12px;" v-for="(item, i) in scope.row.serverAList">{{
                        global.debugInfoFormat(item, i)
                      }}</span>
                    </el-col>
                  </el-row>

                  <el-row v-if="scope.row.serverAList">
                    <el-col>
                      <span style="font-size:12px;" v-for="(item, i) in scope.row.serverBList">{{
                        global.debugInfoFormat(item, i)
                      }}</span>
                    </el-col>
                  </el-row>
                  <!-- <el-descriptions direction="vertical" :column="12" :size='10'>
                    <div v-for="(item, index) in scope.row.alist" :key="index">
                      <el-descriptions-item :label=item label-align="center" align=center>{{
                      scope.row.blist[index]
                      }}
                      </el-descriptions-item>
                    </div>
                  </el-descriptions> -->
                </template>
              </el-table-column>
            </el-table>

            <el-config-provider :locale="locale">
              <el-pagination v-model:currentPage="queryParams.page" v-model:page-size="queryParams.rows"
                :page-sizes="[10, 15, 20, 50, 100]" :small="state.small" :disabled="state.disabled"
                :default-page-size="queryParams.rows" :background="state.background"
                layout="total, sizes, prev, pager, next, jumper" :total="state.total"
                style="text-align: center; margin-top: 10px; height: 30px" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
            </el-config-provider>
          </el-tab-pane>
          <el-tab-pane label="图表">
            <div ref="currentchart" class="div"></div>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>

    <el-dialog :title="cfgdialog.title" v-model="cfgdialog.visible" width="1100px" center>
      <!-- <div slot="title">
        <vue-qr text="https://blog.csdn.net/weixin_42601136" :size="100"></vue-qr>
    </div> -->
      <!-- <div slot="title">
        <span style="text-align:center;">设备参数预览[{{state.cfgData.deviceSn}}]</span>
          <vue-qr text="https://blog.csdn.net/weixin_42601136" :size="80"></vue-qr>
      </div> -->
      <DevCfgDialog :stationCode="state.cfgData.stationCode" :deviceSn="state.cfgData.deviceSn" v-if="cfgdialog.visible">
      </DevCfgDialog>
    </el-dialog>
    <el-dialog width="1300px" :title="CfgFormDialog.title" v-model="CfgFormDialog.visible" center>
      <CfgForm :device-sn="state.cfgData.deviceSn" @change="childMethod" v-if="CfgFormDialog.visible" />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, toRef, ref, onMounted } from "vue";
import { ElForm, ElMessage, ElMessageBox, ElSwitch } from "element-plus";
import tool from "@/until/tool"
import Moment from "moment";
import TAireadAction from "@/api/tairead"
import * as echarts from "echarts";
import { TAireadModel, TAireadQueryParam, Dialog, PageResult, TTaskDown, LinkItem, StationAccQueryParam, StationAccModel, TAicnnModel } from "@/types";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import global from "@/until/global";
import TTaskDownAction from "@/api/downlinktask/ttaskdown";
import DevCfgDialog from "@/components/devcfg/index.vue";
import StationAccAction from "@/api/station/stationacc";
import CfgForm from '@/components/remotecfg/index.vue';

let locale = ref(zhCn);
const loading = ref(false);
const defaultDate = new Date();
const currentchart = ref();
let pageSize = localStorage.getItem("PageSize") == null ? 10 as number : localStorage.getItem("PageSize") as unknown as number;
let userType = localStorage.getItem("UserType") + '';
const my_table = ref();

const state = reactive({
  queryParams: { page: 1, rows: pageSize * 1 } as TAireadQueryParam,
  echarts_queryParams: { page: 1, rows: 999 } as TAireadQueryParam,

  currentTabIndex: "0",
  total: 0,
  small: false,
  background: true,
  disabled: false,
  search_disabled: false,
  tableData: [] as TAireadModel[],
  echartsData: [] as TAireadModel[],
  defaultTime: [Moment(defaultDate.getTime() - 1000 * 3600 * 24 * 30).format("YYYY-MM-DD 00:00:00"), Moment(defaultDate).format("YYYY-MM-DD 23:59:59"),],
  myChart: {} as echarts.ECharts,
  cfgdialog: {} as Dialog,
  cfgData: {} as TAireadModel,
  links: [] as LinkItem[],
  search_selStations: [] as string[],
  search_stationsParam: { page: 1, rows: pageSize } as StationAccQueryParam,
  dynamicTags: [] as string[],
  search_StationName: '',
  CfgFormDialog: {} as Dialog,
});

const {
  queryParams,
  echarts_queryParams,
  total,
  tableData,
  echartsData,
  defaultTime,
  cfgdialog,
  links,
  dynamicTags,
  search_StationName,
  CfgFormDialog,
} = toRefs(state);

const tableHeight = ref(document.documentElement.clientHeight - 250);

const currentRow = ref();

const handleCurrentRowChange = (val: TAireadModel | undefined) => {
  currentRow.value = val;
};

const handleSizeChange = (val: number) => {
  queryParams.value.rows = val;
  queryList();
  localStorage.setItem("PageSize", val.toString());
};

const handleCurrentChange = (val: number) => {
  queryParams.value.page = val;
  queryList();
  if (Object.keys(my_table).length > 0) { if (my_table.value != null) { (my_table.value as any).$refs.bodyWrapper.scrollTop = 0; } }
};

const queryList = () => {
  state.search_disabled = true;
  if (!state.defaultTime) {
    ElMessage.warning("请输入要查询的时间范围！！！");
    state.search_disabled = false;
    return;
  }

  state.queryParams.stationName = state.search_StationName;
  state.echarts_queryParams.stationName = state.search_StationName;

  if (state.currentTabIndex === "0") {
    state.queryParams.startTime = tool.dateFormat(state.defaultTime[0].toString(), "YYYY-MM-DD HH:mm:ss", "YYYYMMDDHHmmss");
    state.queryParams.endTime = tool.dateFormat(state.defaultTime[1].toString(), "YYYY-MM-DD HH:mm:ss", "YYYYMMDDHHmmss");
    if (!state.queryParams.deviceSn && !state.queryParams.stationCode && !state.search_StationName) {
      ElMessage.warning("请输入查询条件！！！");
      state.search_disabled = false;
    }
    else {
      if (state.queryParams.stationCode) {
        state.queryParams.stationCode = state.queryParams.stationCode.padStart(10, '0');     //不足10位前面自动补0
      }
      if (state.queryParams.deviceSn) {
        state.queryParams.deviceSn = state.queryParams.deviceSn.padStart(11, '0');     //不足10位前面自动补0
      }
      QueryTableData();
    }
  } else {
    state.echartsData = [] as TAireadModel[];
    state.echarts_queryParams.deviceSn = state.queryParams.deviceSn;
    state.echarts_queryParams.stationCode = state.queryParams.stationCode;
    state.echarts_queryParams.startTime = tool.dateFormat(state.defaultTime[0].toString(), "YYYY-MM-DD HH:mm:ss", "YYYYMMDDHHmmss");
    state.echarts_queryParams.endTime = tool.dateFormat(state.defaultTime[1].toString(), "YYYY-MM-DD HH:mm:ss", "YYYYMMDDHHmmss");

    if (!state.queryParams.deviceSn && !state.queryParams.stationCode && !state.search_StationName) {
      ElMessage.warning("请输入查询条件！！！");
      state.search_disabled = false;
    }
    else {
      QueryEchartsData();
    }
  }
};

const QueryTableData = () => {
  loading.value = true;
  TAireadAction.QueryTAireadByCondition(state.queryParams)
    .then((result) => {
      if (result.status === 200) {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          const pageData = res as PageResult<TAireadModel[]>;
          pageData.list.forEach(element => {
            element.srcList = [];
            element.alist = [];
            element.blist = [];
            if (element.szsbz) {
              let alist = element.szsbz.split(",");
              element.alist = alist;
            }

            if (element.szsbgl) {
              let blist = element.szsbgl.split(",");
              element.blist = blist;
            }

            if (element.smallJpgUrl) {
              element.src = element.smallJpgUrl;
              element.srcList.push(element.smallJpgUrl);

              //把BMP图加到预览列表 2022-11-09 guozhao
              // if (element.picType && element.picType === 1) {
              //   element.srcList.push(element.smallJpgUrl.replace('.jpg', '.bmp'));
              // }
            }

            if (element.bigJpgUrl) {
              element.src = element.bigJpgUrl;
              element.srcList.push(element.bigJpgUrl);
            }

            if (element.serverReadModel) {
              // if (!tool.stringIsNullOrEmpty(element.serverReadModel.jpgUrl)) {
              //   element.srcList.push(element.serverReadModel.jpgUrl);   
              // }
              // if (!tool.stringIsNullOrEmpty(element.serverReadModel.smallJpgUrl)) {
              //   element.srcList.push(element.serverReadModel.smallJpgUrl);
              // }
              if (element.serverReadModel.szsbz) {
                element.serverAList = element.serverReadModel.szsbz.split(",");
              }
              if (element.serverReadModel.szsbgl) {
                element.serverBList = element.serverReadModel.szsbgl.split(",");
              }
            }
          });

          state.tableData = pageData.list;
          state.total = pageData.total;
          loading.value = false;
          state.search_disabled = false;
        } else {
          ElMessage.warning(error);
          loading.value = false;
          state.search_disabled = false;
        }
      }
    })
    .catch((error) => {
      //请求失败时的操作
      ElMessage.error(error || "未知异常...");
      loading.value = false;
      state.search_disabled = false;
    });
}

const QueryEchartsData = () => {
  TAireadAction.QueryTAireadByCondition(state.echarts_queryParams)
    .then((result) => {
      if (result.status === 200) {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          const pageData = res as PageResult<TAireadModel[]>;

          pageData.list.forEach(element => {
            element.srcList = [];
            element.alist = [];
            element.blist = [];
            if (element.smallJpgUrl) {
              element.src = element.smallJpgUrl;
              element.srcList.push(element.smallJpgUrl);
            }

            if (element.bigJpgUrl) {
              element.src = element.bigJpgUrl;
              element.srcList.push(element.bigJpgUrl);
            }

            if (element.szsbz) {
              let alist = element.szsbz.split(",");
              element.alist = alist;
            }

            if (element.szsbgl) {
              let blist = element.szsbgl.split(",");
              element.blist = blist;
            }
          });

          state.echartsData = pageData.list;
          state.search_disabled = false;
          init();
        } else {
          ElMessage.warning(error);
          state.search_disabled = false;
        }
      }
    })
    .catch((error) => {
      //请求失败时的操作
      ElMessage.error(error || "未知异常...");
      state.search_disabled = false;
    });
}
const handleClick = (tab: any) => {
  state.currentTabIndex = tab.index;
  queryList();
};

const init = () => {
  let ret = state.echartsData;
  let currendata = [];
  let originalvaluedata = [];
  let signaldata = [];
  let voltagedata = [];
  let differencedata = [];
  let differencedata1 = [];

  if (ret) {
    for (let i = 0; i < ret.length; i++) {
      let record = ret[i];
      let now = tool.dateFormat(record.sampleTime, "YYYYMMDDHHmmss", "YYYY-MM-DD HH:mm:ss");
      let current = record.identValue;
      let originalvalue = record.rawValue;
      let pic = record.smallJpgUrl;
      let signal = record.rsrp;
      let voltage = record.voltage;
      let difference = record.identValue;//Math.floor(parseFloat(record.identValue)) - record.identValue;
      let difference1 = record.rawValue;//Math.floor(record.rawValue) - record.identValue;

      currendata.push([now, current, pic]);
      originalvaluedata.push([now, originalvalue, pic]);
      voltagedata.push([now, voltage, pic]);
      signaldata.push([now, signal, pic]);
      differencedata.push([now, difference, pic]);
      differencedata1.push([now, difference1, pic]);
    }

    const currentoption = {
      //提示框
      tooltip: {
        trigger: "axis",
        textStyle: {
          align: "left",
        },
        position: function (pt: any) {
          return [pt[0], "10%"];
        },

        formatter: function (params: any) {
          let paramsnow = "";
          let paramscurrent = "";
          let paramsoriginalvalue = "";
          let paramspic = "";
          let paramssignal = "";
          let paramsvoltage = "";
          let paramsdifference = "";
          let paramsdifference1 = "";

          params.forEach(function (item: any) {
            paramsnow = item.data[0];
            paramspic = item.data[2];
            if (item.seriesName == "当前读数") {
              paramscurrent = item.data[1];
            } else if (item.seriesName == "信号强度") {
              paramssignal = item.data[1];
            } else if (item.seriesName == "设备电压") {
              paramsvoltage = item.data[1];
            } else if (item.seriesName == "标准差值") {
              paramsdifference = item.data[1];
            } else if (item.seriesName == "原始差值") {
              paramsdifference1 = item.data[1];
            } else if (item.seriesName == "原始读数") {
              paramsoriginalvalue = item.data[1];
            }
          });

          let result =
            "<div><font size='4'>数据日期：" + paramsnow + "</font></div>";
          result =
            result +
            "<div ><font size='4'>当前读数：</font><font size='4' color='#00FFFF'>" +
            paramscurrent +
            "</font></div>";
          result =
            result +
            "<div ><font size='4'>原始读数：</font><font size='4' color='#f47920'>" +
            paramsoriginalvalue +
            "</font></div>";
          result =
            result +
            "<div ><font size='4'>信号强度：</font><font size='4' color='#009900'>" +
            paramssignal +
            "</font></div>";
          result =
            result +
            "<div ><font size='4'>设备电压：</font><font size='4' color='#FF00FF'>" +
            paramsvoltage +
            "</font></div>";
          result =
            result +
            "<div ><font size='4'>标准差值：</font><font size='4' color='#3366FF'>" +
            paramsdifference +
            "</font></div>";
          result =
            result +
            "<div ><font size='4'>原始差值：</font><font size='4' color='#ef5b9c'>" +
            paramsdifference1 +
            "</font></div>";
          result =
            result + "<div ><font size='4'>拍照图片：</font>" + "</div>";
          result = result + "<div><img src='" + paramspic + "'></div>";
          return result;
        },
      },
      //标题
      title: {
        left: "center",
        text:
          "",
      },
      //工具栏
      toolbox: {
        feature: {
          dataZoom: {
            yAxisIndex: "none",
          },
          restore: {},
          saveAsImage: {},
        },
      },
      //设置区分（哪条线属于什么）
      legend: {
        data: ["当前读数", "原始读数", "信号强度", "设备电压", "标准差值", "原始差值"],
        left: "right",
        top: "center",
        orient: "vertical",
      },
      //设置区分（每条线是什么颜色，和 legend 一一对应）
      color: ["#00FFFF", "#f47920", "#009900", "#FF00FF", "#3366FF", "#ef5b9c"],
      //X轴
      xAxis: {
        type: "time",
        // boundaryGap: false,
      },
      yAxis: {
        type: "value",
        // boundaryGap: [0, "100%"],
      },
      //缩放区域
      dataZoom: [
        {
          type: "slider",
          show: true,
          xAxisIndex: [0],
          start: 70,
          end: 100,
        },
        {
          type: "slider",
          show: true,
          yAxisIndex: [0],
          left: "90%",
          start: 0,
          end: 100,
        },
        {
          type: "inside",
          xAxisIndex: [0],
          start: 0,
          end: 100,
        },
        {
          type: "inside",
          yAxisIndex: [0],
          start: 0,
          end: 100,
        },
      ],
      series: [
        {
          name: "当前读数",
          type: "line",
          // smooth: false,
          //stack: "Total",
          // symbol: "none",
          data: currendata,
        },
        {
          name: "原始读数",
          type: "line",
          // smooth: false,
          //stack: "Total",
          // symbol: "none",1211200090
          data: originalvaluedata,
        },
        {
          name: "信号强度",
          type: "line",
          // smooth: false,
          //stack: "Total",
          // symbol: "none",
          data: signaldata,
        },
        {
          name: "设备电压",
          type: "line",
          // smooth: false,
          //stack: "Total",
          // symbol: "none",
          data: voltagedata,
        },
        {
          name: "标准差值",
          type: "line",
          // smooth: false,
          //stack: "Total",
          // symbol: "none",
          data: differencedata,
        },
        {
          name: "原始差值",
          type: "line",
          // smooth: false,
          //stack: "Total",
          // symbol: "none",
          data: differencedata1,
        }
      ],
    };

    if (currentchart.value != null && currentchart.value != undefined) {
      echarts.dispose(currentchart.value);
    }

    let current = echarts.init(currentchart.value);
    current.setOption(currentoption);
    //state.myChart = current;
  }
};

onMounted(() => {
  window.onresize = function () {
    tableHeight.value = document.documentElement.clientHeight - 250;
    //state.myChart.resize();
  };
});

//创建召测配置的下行任务
const createTaskDown = (row: any) => {
  let model = row as TAireadModel;
  ElMessageBox.confirm(
    ' 是否快速创建[' + model.stationName + ']的召测配置任务? ',
    '提示',
    {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
      center: true,
    }
  ).then(() => {
    let addModel = {} as TTaskDown;
    addModel.createMan = localStorage.getItem("UserName") + "";
    addModel.deviceSn = model.deviceSn;
    addModel.stationCode = model.stationCode;
    addModel.taskType = '3';
    addModel.finishedFlag = '0';
    addModel.taskLevel = 2;
    TTaskDownAction.AddTTaskDown(addModel).then((result) => {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        ElMessage.success("新增召测配置任务成功");
      }
      else {
        ElMessage.warning(error);
      }
    });
  })
    .catch(() => {
    })
};

//显示参数配置
const showDevCfg = (row: any) => {
  state.cfgData = row as TAireadModel;

  state.cfgdialog = {
    title: "设备参数预览[" + state.cfgData.deviceSn + "]",
    visible: true,
    disabled: false,
  };
}

//双击复制调试信息
const celldblclick = (row: any, column: any, cell: any, event: any) => {
  let colInfo = JSON.parse(JSON.stringify(column));
  if (event.type === "dblclick" && colInfo.label === '调试信息') {
    let airead = row as TAireadModel;
    var save = function (e: any) {
      let strC = airead.alist + '\r\n' + airead.blist;

      e.clipboardData.setData('text/plain', strC);
      //e.clipboardData.setData('text/plain',event.target.innerText); 
      e.preventDefault();//阻止默认行为
    }
    document.addEventListener('copy', save);
    document.execCommand("copy");
    document.removeEventListener('copy', save);
    ElMessage.success("复制成功");
  }
}

//根据传进来的状态改变建议输入框的状态（展开|隐藏）
const changeStyle = (status: any, className: any) => {
  let dom = document.querySelectorAll(className);
  dom[0].style.display = status;
};

const handleSelect = (item: LinkItem) => {
  if (state.dynamicTags.indexOf(item.value) === -1) {
    dynamicTags.value.push(item.value);
    state.search_selStations.push(item.link);
  } else {
    ElMessage.warning("该站点已添加!!");
  }
};

const handleKeyup = (item: any) => {
  changeStyle("none", ".el-autocomplete-suggestion");
  if (state.search_stationsParam.stationName) {
    if (state.dynamicTags.indexOf(state.search_stationsParam.stationName) === -1) {
      dynamicTags.value.push(state.search_stationsParam.stationName);
      let linkItem = links.value.find(s => s.value === state.search_stationsParam.stationName);
      if (linkItem) {
        state.search_selStations.push(linkItem?.link);
      }
    } else {
      ElMessage.warning("该站点已添加!!");
    }
  }
};

let timeout: NodeJS.Timeout;
const querySearchAsync = (
  queryString: string,
  callback: (arg: any) => void
) => {
  links.value = [] as LinkItem[];
  if (!isNull(queryString)) {

    if (!global.isChinese(state.search_StationName)) {
      state.search_stationsParam.stationPy = state.search_StationName;
    } else {
      //state.queryParams.stationName=state.search_StationName;
      state.search_stationsParam.stationName = state.search_StationName;
    }
    StationAccAction.QueryStationAccList(state.search_stationsParam)
      .then((result) => {
        if (result.status === 200) {
          const { res, flag, error } = result.data;
          if (flag === "1") {
            const pageData = res as PageResult<StationAccModel[]>;
            pageData.list.forEach(element => {
              let link = {} as LinkItem;
              link.link = (element as StationAccModel).stationCode;
              link.value = (element as StationAccModel).stationName;
              links.value.push(link);
            });

            clearTimeout(timeout);
            timeout = setTimeout(() => {
              callback(links.value);
            }, 1000);
          } else {
            ElMessage.success(error || "未知异常...");
          }
        }
      }).catch((error) => {
        ElMessage.success(error || "未知异常...");
      });
  }
};

const isNull = (val: any) => {
  if (val) {
    return false;
  } else {
    return true;
  }
};

//新标签页打开服务侧图片
const openServerImage = (row: any) => {
  window.open(row.serverReadModel.jpgUrl, "_blank")
}

//快速创建远程任务
const openRemoteCfg = (row: any) => {
  state.cfgData = row as TAireadModel;
  state.CfgFormDialog = {
    title: "远程配置[" + state.cfgData.deviceSn + "]",
    visible: true,
    disabled: false,
  };
}

//远程任务子组件保存或取消的返回值
const childMethod = (val: Boolean) => {
  state.CfgFormDialog = {
    title: "",
    visible: false,
    disabled: true,
  };
}
</script>

<style lang="scss" scoped>
.el-header {
  height: 25px;
}

.el-form {
  height: 45px;
}

.el-main {
  margin-top: 10px;
}

.el-tabs {
  padding: 0;
}

.div {
  height: calc(100vh - 286px);
  width: calc(100vw - 400px);
}
</style>