<template>
  <div class="app-container">
    <!-- 看板头部工具栏 -->
    <div class="board-header">
      <div class="board-title">生产控制看板</div>
      <div class="board-actions">
        <span class="board-time">{{ nowTimeStr }}</span>
        <el-switch v-model="autoRefresh" active-text="自动刷新" @change="onAutoRefreshChange" />
        <el-button type="primary" size="mini" icon="el-icon-refresh" @click="refreshBoard">刷新</el-button>
        <el-button type="info" size="mini" @click="toggleMode">{{ dashboardMode ? '切换列表' : '切换看板' }}</el-button>
      </div>
    </div>

    <!-- 看板搜索（可选） -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="!dashboardMode && showSearch" label-width="68px">
      <el-form-item label="参数编号" prop="paramCode">
        <el-input
          v-model="queryParams.paramCode"
          placeholder="请输入参数编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备编号" prop="deviceCode">
        <el-input
          v-model="queryParams.deviceCode"
          placeholder="请输入设备编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备ID" prop="deviceId">
        <el-input
          v-model="queryParams.deviceId"
          placeholder="请输入设备ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="参数名称" prop="paramName">
        <el-input
          v-model="queryParams.paramName"
          placeholder="请输入参数名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="参数值" prop="paramValue">
        <el-input
          v-model="queryParams.paramValue"
          placeholder="请输入参数值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采集时间" prop="collectTime">
        <el-date-picker clearable
          v-model="queryParams.collectTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择采集时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="记录时间" prop="recordTime">
        <el-date-picker clearable
          v-model="queryParams.recordTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择记录时间">
        </el-date-picker>
      </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" v-show="!dashboardMode">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['baseDeviceParamVal:val: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="['baseDeviceParamVal:val: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="['baseDeviceParamVal:val: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="['baseDeviceParamVal:val:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <!-- 看板视图 -->
    <div v-if="dashboardMode" class="board-container">
      <el-row :gutter="10">
        <el-col :span="12" v-for="dev in latestDevices" :key="dev.deviceCode">
          <el-card class="device-card">
            <div class="device-card__header">
              <div class="device-card__title">{{ dev.deviceCode || '未知设备' }}</div>
              <div class="device-card__time">最近记录：{{ parseTime(dev.latestRecordTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</div>
            </div>
            <el-row :gutter="10">
              <el-col :span="12">
                <div v-for="p in leftParams(dev.params)" :key="(p.paramCode||p.paramName)+'-L'" class="param-item">
                  <div class="param-name">{{ p.paramName || p.paramCode }}</div>
                  <div class="param-value">{{ p.paramValue }}</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div v-for="p in rightParams(dev.params)" :key="(p.paramCode||p.paramName)+'-R'" class="param-item">
                  <div class="param-name">{{ p.paramName || p.paramCode }}</div>
                  <div class="param-value">{{ p.paramValue }}</div>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>

      <el-card class="recent-card">
        <div class="recent-title">最近采集记录</div>
        <el-table :data="recentRecords" height="300" size="mini">
          <el-table-column label="设备编号" align="center" prop="deviceCode" width="120" />
          <el-table-column label="参数名称" align="center" prop="paramName" />
          <el-table-column label="参数值" align="center" prop="paramValue" width="120" />
          <el-table-column label="采集时间" align="center" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.collectTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="记录时间" align="center" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.recordTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 原列表视图 -->
    <el-table v-else v-loading="loading" :data="valList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="recordId" v-if="columns[0].visible"/>
      <el-table-column label="参数编号" align="center" prop="paramCode" v-if="columns[1].visible"/>
      <el-table-column label="设备编号" align="center" prop="deviceCode" v-if="columns[2].visible"/>
      <el-table-column label="设备ID" align="center" prop="deviceId" v-if="columns[3].visible"/>
      <el-table-column label="参数名称" align="center" prop="paramName" v-if="columns[4].visible"/>
      <el-table-column label="参数值" align="center" prop="paramValue" v-if="columns[5].visible"/>
      <el-table-column label="采集时间" align="center" prop="collectTime" width="180" v-if="columns[6].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.collectTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="记录时间" align="center" prop="recordTime" width="180" v-if="columns[7].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recordTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</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="['baseDeviceParamVal:val:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['baseDeviceParamVal:val:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination v-show="!dashboardMode && 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="paramCode">
          <el-input v-model="form.paramCode" placeholder="请输入参数编号" />
        </el-form-item>
        <el-form-item label="设备编号" prop="deviceCode">
          <el-input v-model="form.deviceCode" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="设备ID" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入设备ID" />
        </el-form-item>
        <el-form-item label="参数名称" prop="paramName">
          <el-input v-model="form.paramName" placeholder="请输入参数名称" />
        </el-form-item>
        <el-form-item label="参数值" prop="paramValue">
          <el-input v-model="form.paramValue" placeholder="请输入参数值" />
        </el-form-item>
        <el-form-item label="采集时间" prop="collectTime">
          <el-date-picker clearable
            v-model="form.collectTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择采集时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="记录时间" prop="recordTime">
          <el-date-picker clearable
            v-model="form.recordTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择记录时间">
          </el-date-picker>
        </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>
  </div>
</template>

<script>
import { listVal, getVal, delVal, addVal, updateVal, getListVal, getLatestVal } from "@/api/baseDeviceParamVal/val";

export default {
  name: "Val",
  data() {
    return {
      // 遮罩层
      loading: true,
      dashboardMode: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备工艺参数当前值表格数据
      valList: [],
      latestDevices: [],
      recentRecords: [],
      autoRefresh: true,
      refreshIntervalMs: 5000,
      refreshTimer: null,
      clockTimer: null,
      nowTimeStr: '',
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        paramCode: null,
        deviceCode: null,
        deviceId: null,
        paramName: null,
        paramValue: null,
        collectTime: null,
        recordTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        recordTime: [
          { required: true, message: "记录时间不能为空", trigger: "blur" }
        ]
      },
      columns: [
            { key: 0, label: `主键`, visible: true },
            { key: 1, label: `参数编号`, visible: true },
            { key: 2, label: `设备编号`, visible: true },
            { key: 3, label: `设备ID`, visible: true },
            { key: 4, label: `参数名称`, visible: true },
            { key: 5, label: `参数值`, visible: true },
            { key: 6, label: `采集时间`, visible: true },
            { key: 7, label: `记录时间`, visible: true },
        ]
    };
  },
  created() {
    this.tickClock();
    this.refreshBoard();
    this.getList();
    if (this.autoRefresh) this.startAutoRefresh();
  },
  beforeDestroy() {
    this.stopAutoRefresh();
    if (this.clockTimer) {
      clearInterval(this.clockTimer);
      this.clockTimer = null;
    }
  },
  methods: {
    toggleMode() {
      this.dashboardMode = !this.dashboardMode;
    },
    tickClock() {
      const update = () => {
        const d = new Date();
        const y = d.getFullYear();
        const m = (d.getMonth()+1).toString().padStart(2,'0');
        const day = d.getDate().toString().padStart(2,'0');
        const h = d.getHours().toString().padStart(2,'0');
        const i = d.getMinutes().toString().padStart(2,'0');
        const s = d.getSeconds().toString().padStart(2,'0');
        this.nowTimeStr = `${y}-${m}-${day} ${h}:${i}:${s}`;
      };
      update();
      this.clockTimer = setInterval(update, 1000);
    },
    startAutoRefresh() {
      this.stopAutoRefresh();
      this.refreshTimer = setInterval(() => {
        this.refreshBoard();
      }, this.refreshIntervalMs);
    },
    stopAutoRefresh() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer);
        this.refreshTimer = null;
      }
    },
    onAutoRefreshChange(val) {
      if (val) this.startAutoRefresh(); else this.stopAutoRefresh();
    },
    refreshBoard() {
      this.getLatest();
    },
    leftParams(arr) {
      const mid = Math.ceil((arr || []).length / 2);
      return (arr || []).slice(0, mid);
    },
    rightParams(arr) {
      const mid = Math.ceil((arr || []).length / 2);
      return (arr || []).slice(mid);
    },
    /** 查询设备工艺参数当前值列表 */
    getList() {
      this.loading = true;
      listVal(this.queryParams).then(response => {
        this.valList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 聚合最新参数（按设备+参数取最新记录） */
    getLatest() {
      this.loading = true;
      const q = { ...this.queryParams };
      // 使用后端“按设备聚合的最新参数”接口，减少数据量与前端计算
      getLatestVal(q).then(response => {
        const rows = response.rows || response.data || response || [];
        const byDev = {};
        rows.forEach(r => {
          const dev = r.deviceCode || '未知设备';
          const pKey = r.paramCode || r.paramName || '未知参数';
          const time = r.recordTime || r.collectTime;
          const ts = time ? new Date(time).getTime() : 0;
          if (!byDev[dev]) byDev[dev] = {};
          const prev = byDev[dev][pKey];
          const prevTs = prev ? new Date(prev.recordTime || prev.collectTime || 0).getTime() : -1;
          if (!prev || ts >= prevTs) {
            byDev[dev][pKey] = r;
          }
        });
        const devices = Object.keys(byDev).map(dev => {
          const params = Object.values(byDev[dev]).sort((a,b)=>{
            const an = a.paramName || a.paramCode || '';
            const bn = b.paramName || b.paramCode || '';
            return an.localeCompare(bn);
          });
          const latestRecordTime = params.reduce((max, r)=>{
            const t = r.recordTime ? new Date(r.recordTime).getTime() : 0;
            return Math.max(max, t);
          }, 0);
          return { deviceCode: dev, params, latestRecordTime };
        }).sort((a,b)=> b.latestRecordTime - a.latestRecordTime);

        const sortedRows = rows.slice().sort((a,b)=>{
          const ta = new Date(a.recordTime || a.collectTime || 0).getTime();
          const tb = new Date(b.recordTime || b.collectTime || 0).getTime();
          return tb - ta;
        });
        this.latestDevices = devices;
        this.recentRecords = sortedRows.slice(0, 20);
        this.loading = false;
      }).catch(()=>{ this.loading = false; });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        recordId: null,
        paramCode: null,
        deviceCode: null,
        deviceId: null,
        paramName: null,
        paramValue: null,
        collectTime: null,
        recordTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.recordId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备工艺参数当前值";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const recordId = row.recordId || this.ids
      getVal(recordId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备工艺参数当前值";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.recordId != null) {
            updateVal(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVal(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recordIds = row.recordId || this.ids;
      this.$modal.confirm('是否确认删除设备工艺参数当前值编号为"' + recordIds + '"的数据项？').then(function() {
        return delVal(recordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('baseDeviceParamVal/val/export', {
        ...this.queryParams
      }, `val_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.board-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.board-title {
  font-size: 18px;
  font-weight: 600;
}
.board-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}
.board-time { color: #888; }
.board-container { margin-top: 10px; }
.device-card { margin-bottom: 10px; background: #0f1f3a; color: #cfe7ff; }
.device-card__header { display: flex; justify-content: space-between; margin-bottom: 8px; font-weight: 600; }
.device-card__title { font-size: 16px; }
.device-card__time { font-size: 12px; color: #9fc2ff; }
.param-item { display: flex; justify-content: space-between; padding: 6px 8px; border-radius: 4px; background: rgba(255,255,255,0.05); margin-bottom: 6px; }
.param-name { color: #9ec1ff; }
.param-value { color: #fff; font-weight: 600; }
.recent-card { margin-top: 10px; }
.recent-title { font-weight: 600; margin-bottom: 6px; }
</style>
