<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="设备编号" prop="deviceId">
        <el-input v-model="queryParams.deviceId" placeholder="请输入设备编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceTypeId">
        <el-select v-model="queryParams.deviceTypeId" placeholder="请输入设备类型" clearable>
          <el-option v-for="dict in dict.type.device_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="所属地块" prop="fieldIdList">
        <el-select v-model="queryParams.fieldIdList" placeholder="请选择地块" multiple collapse-tags filterable clearable>
          <el-option v-for="dict in fieldIdList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>


      <el-form-item label="所属农场" prop="deptIdList">
        <treeselect v-model="queryParams.deptIdList" :options="deptOptions" multiple :flat="true" :limit="1"
          :limitText="count => `+${count}`" style="width:200px" :show-count="true" placeholder="请选所属农场" />
      </el-form-item>


      <el-form-item label="设备状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请输入设备状态" clearable>
          <el-option v-for="dict in dict.type.device_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </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="['base:device: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="['base:device: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="['base:device: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="['base:device:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" v-if="false" />
      <el-table-column label="设备编号" align="center" prop="deviceId" />
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="设备类型" align="center" prop="deviceTypeId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.device_type" :value="scope.row.deviceTypeId" />
        </template>
      </el-table-column>
      <el-table-column label="所属地块" align="center" key="fieldName" prop="fieldName" />
      <el-table-column label="所属农场" align="center" key="deptName" prop="dept.deptName" />

      <el-table-column label="设备型号" align="center" prop="model" />
      <el-table-column label="厂家" align="center" prop="manufacturer" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.device_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="最后活动时间" align="center" prop="lastActiveTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastActiveTime, '{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="handleView(scope.row)"
            v-hasPermi="['base:device:edit']">查看</el-button>

          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['base:device:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['base:device: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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备编号" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceTypeId">
          <el-select v-model="form.deviceTypeId" placeholder="请选择设备类型">
            <el-option v-for="dict in dict.type.device_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="厂家" prop="manufacturer">
          <el-input v-model="form.manufacturer" placeholder="请输入厂家" />
        </el-form-item>
        <el-form-item label="所属农场" prop="farmId">
          <treeselect v-model="form.farmId" :options="deptOptions" :show-count="true" placeholder="请选所属机构"
            @input='queryPersonCharge(form.farmId)' />
        </el-form-item>
        <el-form-item label="设备型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入设备型号" />
        </el-form-item>
        <el-form-item label="GPS经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入GPS经度" />
        </el-form-item>
        <el-form-item label="GPS纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入GPS纬度" />
        </el-form-item>

        <el-form-item label="安装日期" prop="installDate">
          <el-date-picker clearable v-model="form.installDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择安装日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <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="title" :visible.sync="openView" width="800px" append-to-body>
      <el-tabs v-model="activeTab" @tab-click="handleClick">
        <el-tab-pane label="基本信息" name="basicInfo">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="device-info">
                <h3>设备基础信息</h3>

                <ul>
                  <li><strong>设备编号：</strong> {{ formView.deviceId }}</li>
                  <li><strong>设备名称：</strong> {{ formView.deviceName }}</li>

                  <li><strong style="float: left;">设备类型：</strong><dict-tag :options="dict.type.device_type"
                      :value="formView.deviceTypeId" /></li>
                  <li><strong>设备型号：</strong> {{ formView.model }}</li>
                  <li><strong>制造厂商：</strong> {{ formView.manufacturer }}</li>
                </ul>

              </div>


            </el-col>
            <el-col :span="12">
              <div class="device-info">
                <h3>位置信息</h3>

                <ul>
                  <li><strong>所属农场：</strong> {{ formView.deptName }}</li>
                  <li><strong>所属地块：</strong> {{ formView.fieldName }}</li>
                  <li><strong>安装日期：</strong> {{ formView.installDate }}</li>
                  <li><strong>GPS坐标：</strong> {{ formView.longitude }} - {{ formView.latitude }}</li>
                </ul>

              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <h3>运行状态</h3>
              <el-row :gutter="20">
                <el-col :span="12">
                  <div>
                    <p>当前状态：
                      <el-tag :type="getTagType(formView.status)">{{ getStatusText(formView.status) }}</el-tag>
                    </p>
                  </div>
                  <div>
                    <p>最后活动：{{ formView.lastActiveTime }}</p>

                  </div>
                </el-col>
                <el-col :span="12">
                  <div>
                    <p>电量状态：
                      <el-progress :percentage="deviceStatus.battery" :stroke-width="10"></el-progress>
                    </p>
                  </div>
                  <div>
                    <p>信号强度：良好</p>
                  </div>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="实时数据" name="realTimeData">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>实时读数</span>
              <el-badge style="margin-left: 70%;">最后更新: {{ sensorRealTime.collectTime }}</el-badge>
            </div>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-card>
                  <div class="item-content">

                    <div class="item-value" style="color: #059669;">{{ sensorRealTime.temperature }}°C</div>
                    <div class="item-title">温度 (°C)</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card>
                  <div class="item-content">

                    <div class="item-value" style="color: #2563eb;">{{ sensorRealTime.humidity }}%</div>
                    <div class="item-title">湿度</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card>
                  <div class="item-content">

                    <div class="item-value">{{ sensorRealTime.lightIntensity }}</div>
                    <div class="item-title">光照 (lux)</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card>
                  <div class="item-content">

                    <div class="item-value" style="color: #7c3aed;">{{ sensorRealTime.soilMoisture }}%</div>
                    <div class="item-title">土壤湿度</div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-card>
          <div ref="chart" id="sensor" style="width: 750px; height: 400px;">
          </div>
          <el-card class="box-card">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-card>
                  <div class="item-content">
                    <div class="item-title">温度</div>
                    <div style="color: #1e1e1e;">最高温度{{ AverageSensorRealTime.temperature }}°C</div>
                    <div style="color: #1e1e1e;">最低温度{{ AverageSensorRealTime.temperature }}°C</div>

                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card>
                  <div class="item-content">
                    <div class="item-title">平均湿度</div>
                    <div class="item-value" style="color: #2563eb;">{{ AverageSensorRealTime.humidity }}%</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card>
                  <div class="item-content">
                    <div class="item-title">平均光照</div>
                    <div class="item-value">{{ AverageSensorRealTime.lightIntensity }}lux</div>

                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card>
                  <div class="item-content">
                    <div class="item-title">平均土壤湿度</div>
                    <div class="item-value" style="color: #7c3aed;">{{ AverageSensorRealTime.soilMoisture }}%</div>

                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-card>

        </el-tab-pane>
      </el-tabs>
    </el-dialog>



    <!-- 查看气象设备对话框 -->
    <el-dialog :title="title" :visible.sync="openWeatherView" width="800px" append-to-body>
      <el-tabs v-model="activeWeatherTab" @tab-click="handleClickWeather">
        <el-tab-pane label="基本信息" name="basicInfoWeather">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="device-info">
                <h3>设备基础信息</h3>

                <ul>
                  <li><strong>设备编号：</strong> {{ formView.deviceId }}</li>
                  <li><strong>设备名称：</strong> {{ formView.deviceName }}</li>

                  <li><strong style="float: left;">设备类型：</strong><dict-tag :options="dict.type.device_type"
                      :value="formView.deviceTypeId" /></li>
                  <li><strong>设备型号：</strong> {{ formView.model }}</li>
                  <li><strong>制造厂商：</strong> {{ formView.manufacturer }}</li>
                </ul>

              </div>


            </el-col>
            <el-col :span="12">
              <div class="device-info">
                <h3>位置信息</h3>

                <ul>
                  <li><strong>所属农场：</strong> {{ formView.deptName }}</li>
                  <li><strong>所属地块：</strong> {{ formView.fieldName }}</li>
                  <li><strong>安装日期：</strong> {{ formView.installDate }}</li>
                  <li><strong>GPS坐标：</strong> {{ formView.longitude }} - {{ formView.latitude }}</li>
                </ul>

              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <h3>运行状态</h3>
              <el-row :gutter="20">
                <el-col :span="12">
                  <div>
                    <p>当前状态：
                      <el-tag :type="getTagType(formView.status)">{{ getStatusText(formView.status) }}</el-tag>
                    </p>
                  </div>
                  <div>
                    <p>最后活动：{{ formView.lastActiveTime }}</p>

                  </div>
                </el-col>
                <el-col :span="12">
                  <div>
                    <p>电量状态：
                      <el-progress :percentage="deviceStatus.battery" :stroke-width="10"></el-progress>
                    </p>
                  </div>
                  <div>
                    <p>信号强度：良好</p>
                  </div>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="实时数据" name="realTimeData">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>实时气象数据</span>
              <el-badge style="margin-left: 70%;">最后更新: {{ weatherRealTime.collectTime }}</el-badge>
            </div>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-card>
                  <div class="item-content">

                    <div class="item-value" style="color: #059669;">{{ weatherRealTime.temperature }}°C</div>
                    <div class="item-title">气温 (°C)</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card>
                  <div class="item-content">

                    <div class="item-value" style="color: #2563eb;">{{ weatherRealTime.humidity }}%</div>
                    <div class="item-title">湿度</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card>
                  <div class="item-content">

                    <div class="item-value">{{ weatherRealTime.rainfall }}mm</div>
                    <div class="item-title">降雨量 (lux)</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card>
                  <div class="item-content">

                    <div class="item-value" style="color: #7c3aed;">{{ weatherRealTime.windDirection }}</div>
                    <div class="item-title">风向</div>
                  </div>
                </el-card>
              </el-col>
            </el-row>


            <el-row :gutter="20">
              <el-col :span="6">
                <el-card>
                  <div class="item-content">

                    <div class="item-value" style="color: #059669;">{{ weatherRealTime.windSpeed }}m/s</div>
                    <div class="item-title">风速</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card>
                  <div class="item-content">

                    <div class="item-value" style="color: #2563eb;">{{ weatherRealTime.airPressure }}hPa</div>
                    <div class="item-title">气压</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card>
                  <div class="item-content">

                    <div class="item-value">{{ weatherRealTime.lightIntensity }}lux</div>
                    <div class="item-title">光照</div>
                  </div>
                </el-card>
              </el-col>

              <el-col :span="6">
                <el-card>
                  <div class="item-content">

                    <div class="item-value">{{ weatherRealTime.soilN }}</div>
                    <div class="item-title">土壤氮</div>
                  </div>
                </el-card>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="6">
                <el-card>
                  <div class="item-content">

                    <div class="item-value">{{ weatherRealTime.soilP }}</div>
                    <div class="item-title">土壤磷</div>
                  </div>
                </el-card>
              </el-col>

              <el-col :span="6">
                <el-card>
                  <div class="item-content">

                    <div class="item-value">{{ weatherRealTime.soilK }}</div>
                    <div class="item-title">土壤钾</div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-card>
          <div>

            <div class="weather-chart-header">
              <p>气象数据统计图</p>
              <div class="time-btns">
                <el-button @click="twentyFourHours" round>24小时</el-button>
                <el-button @click="sevenDays" round>7天</el-button>
                <el-button @click="thirtyDays" round>30天</el-button>
              </div>
            </div>
            <div ref="chart" id="weather" style="width: 750px; height: 400px;"></div>

          </div>

          <el-card class="box-card">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-card>
                  <div class="item-content">
                    <div class="item-title">平均气温</div>
                    <div class="item-value" style="color: #059669;">{{ AverageweatherRealTime.temperature }}°C</div>

                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card>
                  <div class="item-content">
                    <div class="item-title">平均湿度</div>
                    <div class="item-value" style="color: #2563eb;">{{ AverageweatherRealTime.humidity }}%</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card>
                  <div class="item-content">
                    <div class="item-title">累计降雨量</div>
                    <div class="item-value">{{ AverageweatherRealTime.rainfallA }}mm</div>

                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card>
                  <div class="item-content">
                    <div class="item-title">平均风速</div>
                    <div class="item-value" style="color: #7c3aed;">{{ AverageweatherRealTime.windSpeed }}m/s</div>

                  </div>
                </el-card>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="6">
                <el-card>
                  <div class="item-content">
                    <div class="item-title">土壤氮</div>
                    <div class="item-value" style="color: #059669;">{{ AverageweatherRealTime.soilN }}</div>

                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card>
                  <div class="item-content">
                    <div class="item-title">土壤磷</div>
                    <div class="item-value" style="color: #2563eb;">{{ AverageweatherRealTime.soilP }}</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card>
                  <div class="item-content">
                    <div class="item-title">土壤钾</div>
                    <div class="item-value">{{ AverageweatherRealTime.soilK }}</div>

                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-card>

        </el-tab-pane>
      </el-tabs>
    </el-dialog>



    <!-- 查看控制器设备对话框 -->
    <el-dialog :title="title" :visible.sync="openControllerView" width="800px" append-to-body>
      <el-tabs v-model="activeControllerTab" @tab-click="handleClickController">
        <el-tab-pane label="基本信息" name="basicInfoController">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="device-info">
                <h3>设备基础信息</h3>

                <ul>
                  <li><strong>设备编号：</strong> {{ formView.deviceId }}</li>
                  <li><strong>设备名称：</strong> {{ formView.deviceName }}</li>

                  <li><strong style="float: left;">设备类型：</strong><dict-tag :options="dict.type.device_type"
                      :value="formView.deviceTypeId" /></li>
                  <li><strong>设备型号：</strong> {{ formView.model }}</li>
                  <li><strong>制造厂商：</strong> {{ formView.manufacturer }}</li>
                </ul>

              </div>


            </el-col>
            <el-col :span="12">
              <div class="device-info">
                <h3>位置信息</h3>

                <ul>
                  <li><strong>所属农场：</strong> {{ formView.deptName }}</li>
                  <li><strong>所属地块：</strong> {{ formView.fieldName }}</li>
                  <li><strong>安装日期：</strong> {{ formView.installDate }}</li>
                  <li><strong>GPS坐标：</strong> {{ formView.longitude }} - {{ formView.latitude }}</li>
                </ul>

              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <h3>运行状态</h3>
              <el-row :gutter="20">
                <el-col :span="12">
                  <div>
                    <p>当前状态：
                      <el-tag :type="getTagType(formView.status)">{{ getStatusText(formView.status) }}</el-tag>
                    </p>
                  </div>
                  <div>
                    <p>最后活动：{{ formView.lastActiveTime }}</p>

                  </div>
                </el-col>
                <el-col :span="12">
                  <div>
                    <p>电量状态：
                      <el-progress :percentage="deviceStatus.battery" :stroke-width="10"></el-progress>
                    </p>
                  </div>
                  <div>
                    <p>信号强度：良好</p>
                  </div>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="实时数据" name="realTimeData">
          <div>
            <el-row :gutter="20">
              <el-col :span="12">
                <h3>控制状态</h3>
                <ul>
                  <li v-for="item in controlStatus" :key="item.id">
                    <strong>{{ item.name }}</strong>

                  </li>
                </ul>
              </el-col>
              <el-col :span="12">
                <h3>运行参数</h3>
                <el-form>
                  <el-form-item label="系统工作模式">
                    <el-select v-model="systemMode" placeholder="请选择">
                      <el-option label="自动模式" value="auto"></el-option>
                      <el-option label="手动模式" value="manual"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="水泵1#流量">
                    <el-progress :percentage="waterPump1Flow" :stroke-width="18"></el-progress>
                  </el-form-item>
                  <el-form-item label="风机转速">
                    <el-progress :percentage="fanSpeed" :stroke-width="18"></el-progress>
                  </el-form-item>
                  <el-form-item label="阀门开度">
                    <el-progress :percentage="valveOpenDegree" :stroke-width="18"></el-progress>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
            <el-table :data="operationRecords" style="width: 100%">
              <el-table-column prop="time" label="时间" width="180" />
              <el-table-column prop="eventType" label="事件类型" width="180" />
              <el-table-column prop="operator" label="操作人员" width="180" />
              <el-table-column prop="detail" label="详情" />

            </el-table>
          </div>

        </el-tab-pane>
      </el-tabs>
    </el-dialog>





  </div>
</template>

<script>
import { listDevice, getDevice, delDevice, addDevice, updateDevice } from "@/api/base/device"
import { getInfoLatestTime, listSensorStatistics } from "@/api/base/sensor"
import { getInfoWeatherLatestTime, listWeatherStatistics } from "@/api/base/weather"
import { listFieldName } from "@/api/base/field"
import { deptTreeSelect } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import * as  echarts from 'echarts'

export default {
  name: "Device",
  components: { Treeselect },
  dicts: ['device_type', 'device_status'],
  data() {
    return {
      activeTab: 'basicInfo',
      activeWeatherTab: 'basicInfoWeather',
      activeControllerTab: 'basicInfoController',
      // 遮罩层
      loading: true,
      // 选中的设备编号
      deviceId: "",
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备表格数据
      deviceList: [],

      // 部门树选项
      deptOptions: undefined,
      // 所属地块
      fieldIdList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示查看传感器的弹出层
      openView: false,
      // 是否显示查看气象设备的弹出层
      openWeatherView: false,
      // 是否显示查看控制器的弹出层
      openControllerView: false,

      // 传感器日期数据
      sensorDate: [],
      // 传感器最高温度数据
      maxTemperature: [],
      // 传感器最底温度数据
      minTemperature: [],
      // 传感器湿度数据
      avgHumidity: [],
      // 传感器光照数据
      avgLightIntensity: [],
      // 传感器土壤湿度数据
      avgSoilMoisture: [],




      // 气象设备日期数据
      weatherDate: ['6/20', '6/21', '6/22', '6/23', '6/24', '6/25', '6/26'],
      /* weatherDate: ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00'], */
      // 气象设备最高温度数据
      weatherMaxTemperature: [31, 20, 25, 13, 24, 23, 26],
      // 气象设备最低温度数据
      weatherMinTemperature: [31, 20, 25, 13, 24, 23, 26],
      // 气象设备湿度数据
      weatherHumidity: [75, 63, 65, 73, 58, 50, 65],
      // 气象设备降雨数据
      weatherRainfall: [70, 23, 45, 38, 55, 60, 68],
      // 气象设备风速数据
      weatherWindSpeed: [20, 22, 25, 24, 22, 22, 22],
      // 气象设备氮数据
      weatherAvgSoilN: [20, 22, 25, 24, 22, 22, 22],
      // 气象设备磷数据
      weatherAvgSoilP: [20, 22, 25, 24, 22, 22, 22],
      // 气象设备钾数据
      weatherAvgSoilK: [20, 22, 25, 24, 22, 22, 22],

      controlStatus: [
        { name: '水泵1#', status: 'success' },
        { name: '水泵2#', status: 'danger' },
        { name: '风机', status: 'success' },
        { name: '灌溉阀门', status: 'warning' },
        { name: '照明系统', status: 'info' }
      ],

      systemMode: 'auto',
      waterPump1Flow: 65,
      fanSpeed: 80,
      valveOpenDegree: 45,
      operationRecords: [
        { time: '2023-10-16 14:30', eventType: '自动启动', operator: '系统', detail: '根据传感器数据，水泵1#自动启动' },
        { time: '2023-10-16 12:15', eventType: '手动调整', operator: '张农艺师', detail: '调整风机转速至80%' },
        { time: '2023-10-16 09:30', eventType: '自动关闭', operator: '系统', detail: '灌溉完成，阀门自动关闭' },
        { time: '2023-10-16 08:00', eventType: '系统检查', operator: '系统', detail: '日常自检完成，所有系统正常' }
      ],


      // 传感器实时数据
      sensorRealTime: {
        temperature: null,
        humidity: null,
        lightIntensity: null,
        soilMoisture: null,
        collectTime: null,
      },
      // 传感器实时数据平均
      AverageSensorRealTime: {
        temperature: null,
        humidity: null,
        lightIntensity: null,
        soilMoisture: null,
      },

      weatherRealTime: {
        temperature: null,
        humidity: null,
        rainfall: null,
        collectTime: null,
        windSpeed: null,
        windDirection: null,
        airPressure: null,
        lightIntensity: null,
      },

      /*  weatherRealTime: {
         temperature: 24.8,
         humidity: 76,
         rainfall: 2.5,
         collectTime: '2025-10-16 15:50',
         windSpeed: 3.2,
         windDirection: '东北',
         airPressure: 1013,
         lightIntensity: 12500,
       }, */
      AverageweatherRealTime: {
        temperature: null,
        humidity: null,
        rainfallA: null,
        windSpeed: null,
        soilN: null,
        soilP: null,
        soilK: null,

      },
      /* AverageweatherRealTime: {
        temperature: null,
        humidity: null,
        rainfall: null,
        windSpeed: null,

      }, */
      deviceInfo: {
        deviceCode: 'DEV20230001',
        deviceName: '温湿度传感器-A1',
        deviceType: '传感器',
        deviceModel: 'TS-100A',
        manufacturer: '智农科技',
        farmName: '东区智慧农场',
        location: 'A区大棚3号',
        installDate: '2023-01-15',
        gps: '30.2922° N, 120.1619° E'
      },
      deviceStatus: {
        battery: 85,
        signal: '良好',
        signalColor: 'green',
        lastActivity: '2023-10-15 14:30'
      },

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceId: null,
        deviceName: null,
        deviceTypeId: null,
        farmId: null,
        status: null,
        deptIdList: [],
      },
      // 表单参数
      form: {},

      // 查看传感器表单参数
      formView: {},
      // 查看气象设备表单参数
      formViewMeteorological: {},
      // 表单校验
      rules: {
        deviceId: [
          { required: true, message: "设备编号不能为空", trigger: "blur" }
        ],
        deviceName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        deviceTypeId: [
          { required: true, message: "设备类型不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ],
        farmId: [
          { required: true, message: "所属农场不能为空", trigger: "blur" }
        ],
      }
    }
  },
  mounted() {

  },




  created() {
    this.getList();
    this.getDeptTree();
    this.getFieldNameList();
  },
  methods: {




    /** 查询地块名称 **/
    getFieldNameList() {
      listFieldName().then(res => {
        this.fieldIdList = res;
        this.fieldIdList.forEach(x => {
          x.value = x.id;
          x.label = x.fieldName;
        })
      });
    },

    Sensor() {
      // let lCharts = echarts.init(document.getElementById('demoDiv'))
      const chart = echarts.init(document.getElementById('sensor'));
      const option = {
        title: {
          text: '数据统计图'
        },
        tooltip: {},
        legend: {
          data: ['最低温度', '最高温度', '湿度', '光照', '土壤湿度']
        },
        xAxis: {
          type: 'category',
          data: this.sensorDate
        },
        yAxis: {
          type: 'value'
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        series: [
          {
            name: '最低温度',
            type: 'line',
            data: this.minTemperature,
            smooth: true,
            areaStyle: {

            }
          },
          {
            name: '最高温度',
            type: 'line',
            data: this.maxTemperature,
            smooth: true,
            areaStyle: {

            }
          },
          {
            name: '湿度',
            type: 'line',
            data: this.avgHumidity,
            smooth: true,
            areaStyle: {

            }
          },
          {
            name: '光照',
            type: 'line',
            data: this.avgLightIntensity,
            smooth: true,
            areaStyle: {

            }
          },
          {
            name: '土壤湿度',
            type: 'line',
            data: this.avgSoilMoisture,
            smooth: true,
            areaStyle: {

            }
          }
        ]
      };
      chart.setOption(option);

    },

    /* 气象设备数据图 */
    weather() {
      // let lCharts = echarts.init(document.getElementById('demoDiv'))
      const chart = echarts.init(document.getElementById('weather'));
      const option = {
        /* title: {
          text: '数据统计图'
        }, */
        tooltip: {},
        legend: {
          data: ['最高温度', '最低温度', '湿度', '降雨量', '风速','土壤氮','土壤磷','土壤钾']
        },
        xAxis: {
          type: 'category',
          data: this.weatherDate
        },
        yAxis: {
          type: 'value'
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        series: [
          {
            name: '最高温度',
            type: 'line',
            data: this.weatherMaxTemperature,
            smooth: true,
            areaStyle: {

            }
          },
          {
            name: '最低温度',
            type: 'line',
            data: this.weatherMinTemperature,
            smooth: true,
            areaStyle: {

            }
          },
          {
            name: '湿度',
            type: 'line',
            data: this.weatherHumidity,
            smooth: true,
            areaStyle: {

            }
          },
          {
            name: '降雨量',
            type: 'line',
            data: this.weatherRainfall,
            smooth: true,
            areaStyle: {

            }
          },
          {
            name: '风速',
            type: 'line',
            data: this.weatherWindSpeed,
            smooth: true,
            areaStyle: {

            }
          },
          {
            name: '土壤氮',
            type: 'line',
            data: this.weatherAvgSoilN,
            smooth: true,
            areaStyle: {

            }
          },
          {
            name: '土壤磷',
            type: 'line',
            data: this.weatherAvgSoilP,
            smooth: true,
            areaStyle: {

            }
          },
          {
            name: '土壤钾',
            type: 'line',
            data: this.weatherAvgSoilK,
            smooth: true,
            areaStyle: {

            }
          }
        ]
      };
      chart.setOption(option);

    },


    getStatusText(status) {
      switch (status) {
        case 0:
          return '离线';
        case 1:
          return '在线';
        case 2:
          return '故障';
        case 3:
          return '维护中';
        default:
          // 如果状态值未知，返回默认文本
          return '未知状态';
      }
    },
    getTagType(status) {
      // 根据状态返回对应的标签类型
      switch (status) {
        case 0:
          return 'info';
        case 1:
          return 'success';
        case 2:
          return 'danger';
        case 3:
          return 'warning';
        default:
          // 如果状态值未知，返回默认类型
          return 'default';
      }
    },

    /* 传感器切换事件 */
    handleClick(tab, event) {
      console.log(tab, event);
      if (tab.index == 0) {
        console.log("传感器第一个");
      } else if (tab.index == 1) {
        console.log("传感器第二个");
        console.log(this.deviceId);


        /* getInfoLatestTime(this.deviceId).then(response => {
          this.sensorRealTime = response.data
        }) */
        getInfoLatestTime(this.deviceId)
          .then(response => {
            const data = response?.data;
            if (data == null || (Array.isArray(data) && data.length === 0)) {
              console.warn('实时传感器数据为空');
            } else {
              this.sensorRealTime = data;
            }
          })
          .catch(err => {
            console.error('获取实时数据失败', err);
            this.sensorRealTime = null;
          });
        listSensorStatistics(this.deviceId).then(response => {
          this.sensorDate = response.data.sensorDate
          this.maxTemperature = response.data.maxTemperature
          this.minTemperature = response.data.minTemperature
          this.avgHumidity = response.data.avgHumidity
          this.avgLightIntensity = response.data.avgLightIntensity
          this.avgSoilMoisture = response.data.avgSoilMoisture
          this.$nextTick(() => {
            this.Sensor();
          });
          this.AverageSensorRealTime = response.data.sensorRealtimeData

        })


      } else {
        //网络请求3getUserField
        console.log("传感器第三个");
      }

    },


    _fetchWeather(days = null) {
      const query = { deviceId: this.deviceId };
      if (days != null) query.NumberDay = days;

      const label = days == null ? '7天' : days === 24 ? '24小时' : `${days}天`;
      console.log(`按${label}键了`);

      listWeatherStatistics(query).then(({ data }) => {
        Object.assign(this, {
          weatherDate: data.weatherDate,
          weatherMaxTemperature: data.weatherMaxTemperature,
          weatherMinTemperature: data.weatherMinTemperature,
          weatherHumidity: data.weatherHumidity,
          weatherRainfall: data.weatherRainfall,
          weatherWindSpeed: data.weatherWindSpeed,
          weatherAvgSoilN: data.weatherAvgSoilN,
          weatherAvgSoilP: data.weatherAvgSoilP,
          weatherAvgSoilK: data.weatherAvgSoilK,
          AverageweatherRealTime: data.weatherRealtimeData
        });

        this.$nextTick(this.weather);
      });
    },

    /* 三个按钮入口 */
    twentyFourHours() {
      this._fetchWeather(24);
    },
    sevenDays() {
      this._fetchWeather();
    },
    thirtyDays() {
      this._fetchWeather(30);
    },


    /* 气象设备切换事件 */
    handleClickWeather(tab, event) {
      console.log(tab, event);
      if (tab.index == 0) {
        console.log("气象设备第一个");
      } else if (tab.index == 1) {


        /* getInfoWeatherLatestTime(this.deviceId).then(response => {
          if (response.data) {
            this.weatherRealTime = response.data;
          }
        }) */

        getInfoWeatherLatestTime(this.deviceId)
          .then(response => {
            const data = response?.data;
            if (data == null || Object.keys(data).length === 0) {
              console.warn('最新气象数据为空');
            } else {
              this.weatherRealTime = data;
            }
          })
          .catch(err => {
            console.error('获取最新气象数据失败', err);
          });

        const query = { deviceId: this.deviceId };

        listWeatherStatistics(query).then(response => {
          this.weatherDate = response.data.weatherDate
          this.weatherMaxTemperature = response.data.weatherMaxTemperature
          this.weatherMinTemperature = response.data.weatherMinTemperature
          this.weatherHumidity = response.data.weatherHumidity
          this.weatherRainfall = response.data.weatherRainfall
          this.weatherWindSpeed = response.data.weatherWindSpeed
          this.weatherAvgSoilN = response.data.weatherAvgSoilN
          this.weatherAvgSoilP = response.data.weatherAvgSoilP
          this.weatherAvgSoilK = response.data.weatherAvgSoilK
          this.$nextTick(() => {
            this.weather();
          });
          this.AverageweatherRealTime = response.data.weatherRealtimeData

        })

        console.log("气象设备第二个");
      } else {
        //网络请求3getUserField
        console.log("气象设备第三个");
      }

    },

    /* 控制器切换事件 */
    handleClickController(tab, event) {
      console.log(tab, event);
      if (tab.index == 0) {
        console.log("控制器第一个");
      } else if (tab.index == 1) {

        console.log("控制器第二个");
      } else {
        //网络请求3getUserField
        console.log("控制器第三个");
      }

    },

    /**查询对应的负责人 */
    queryPersonCharge() {

    },

    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询设备列表 */
    getList() {
      this.loading = true
      listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deviceId: null,
        deviceName: null,
        deviceTypeId: null,
        farmId: null,
        model: null,
        longitude: null,
        latitude: null,
        manufacturer: null,
        installDate: null,
        status: null,
        lastActiveTime: null,
        createTime: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    // 查看表单重置
    resetView() {
      this.formView = {
        id: null,
        deviceId: null,
        deviceName: null,
        deviceTypeId: null,
        farmId: null,
        model: null,
        longitude: null,
        latitude: null,
        manufacturer: null,
        installDate: null,
        status: null,
        lastActiveTime: null,
        createTime: null,
        updateTime: null,
        remark: null,
        deptName: null
      }
      this.resetForm("formView")
    },
    /** 搜索按钮操作 */
    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 id = row.id || this.ids
      getDevice(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改设备"
      })
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.resetView()
      const id = row.id || this.ids
      this.deviceId = row.deviceId
      getDevice(id).then(response => {
        this.formView = response.data
        this.formView.deptName = response.data.dept.deptName
        this.title = "设备详情"
      })
      if (row.deviceTypeId == 1) {// 传感器

        this.openView = true

      } else if (row.deviceTypeId == 2) {// 摄像头
      } else if (row.deviceTypeId == 3) {// 控制器
        this.openControllerView = true
      } else if (row.deviceTypeId == 4) {// 气象设备
        this.openWeatherView = true
      }

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addDevice(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 delDevice(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('base/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>


<style scoped>
li {
  list-style-type: none;
}

ul {
  margin: 0;
  padding: 0;
}


#Sensor {
  width: 500px;
  height: 300px;
  border: 1px solid red;
}


.box-card {
  margin-bottom: 20px;
}

.item-content {
  text-align: center;
}

.item-title {
  font-weight: bold;
}

.item-value {
  font-size: 24px;
}

.weather-chart-header {
  display: flex;
  /* 关键：让子元素横向排列 */
  align-items: center;
  /* 垂直居中 */
  gap: 12px;
  /* 按钮之间的间距 */
}
</style>
