<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="测量点编码" prop="pointCode">
        <el-input v-model="queryParams.pointCode" placeholder="请输入测量点编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="测量点名称" prop="pointName">
        <el-input v-model="queryParams.pointName" placeholder="请输入测量点名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="所属车间" prop="workshopId">
        <el-select v-model="queryParams.workshopId" placeholder="请选择车间" clearable filterable>
          <el-option v-for="item in workshopOptions" :key="item.workshopId" :label="item.workshopName" :value="item.workshopId" />
        </el-select>
      </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="启用状态" prop="enableFlag">
        <el-select v-model="queryParams.enableFlag" placeholder="请选择" clearable>
          <el-option v-for="dict in dict.type.sys_yes_no" :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="['mes:md:measurepoint: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="['mes:md:measurepoint: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="['mes:md:measurepoint:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-refresh" size="mini" @click="refreshLatest" v-hasPermi="['mes:md:measurepoint:query']">刷新最新值</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="measurePointList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="测量点编码" align="center" prop="pointCode" min-width="120">
        <template slot-scope="scope">
          <el-button type="text" @click="handleView(scope.row)" v-hasPermi="['mes:md:measurepoint:query']">{{ scope.row.pointCode }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="测量点名称" align="center" prop="pointName" min-width="140" />
      <el-table-column label="车间" align="center" prop="workshopName" min-width="120" />
      <el-table-column label="设备编码" align="center" prop="deviceCode" min-width="120" />
      <el-table-column label="节点编码" align="center" prop="nodeCode" min-width="120" />
      <el-table-column label="最新值" align="center" min-width="120">
        <template slot-scope="scope">
          <span>{{ formatLatestValue(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最新时间" align="center" prop="latestTime" min-width="180" :show-overflow-tooltip="true" />
      <el-table-column label="单位" align="center" prop="unit" width="80" />
      <el-table-column label="字段" align="center" prop="fieldKey" min-width="120" />
      <el-table-column label="启用" align="center" prop="enableFlag" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.enableFlag" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="260">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-data-line" @click="openHistory(scope.row)" v-hasPermi="['mes:md:measurepoint:query']">历史曲线</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['mes:md:measurepoint:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['mes:md:measurepoint: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="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="测量点编码" prop="pointCode">
              <el-input v-model="form.pointCode" :readonly="optType === 'view'" placeholder="请输入测量点编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="测量点名称" prop="pointName">
              <el-input v-model="form.pointName" :readonly="optType === 'view'" placeholder="请输入测量点名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属车间" prop="workshopId">
              <el-select v-model="form.workshopId" :disabled="optType === 'view'" placeholder="请选择车间" filterable style="width: 100%">
                <el-option v-for="item in workshopOptions" :key="item.workshopId" :label="item.workshopName" :value="item.workshopId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用状态" prop="enableFlag">
              <el-radio-group v-model="form.enableFlag" :disabled="optType === 'view'">
                <el-radio v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备编码" prop="deviceCode">
              <el-input v-model="form.deviceCode" :readonly="optType === 'view'" placeholder="请输入设备编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="节点编码" prop="nodeCode">
              <el-input v-model="form.nodeCode" :readonly="optType === 'view'" placeholder="请输入节点编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="字段名" prop="fieldKey">
              <el-input v-model="form.fieldKey" :readonly="optType === 'view'" placeholder="Influx field key" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" :readonly="optType === 'view'" placeholder="例如 ℃、kPa、A" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保留位数" prop="precisionDigit">
              <el-input-number v-model="form.precisionDigit" :disabled="optType === 'view'" :min="0" :max="6" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序号" prop="sortNum">
              <el-input-number v-model="form.sortNum" :disabled="optType === 'view'" :min="1" :max="9999" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="Tag 条件" prop="tagJson">
              <el-input v-model="form.tagJson" :readonly="optType === 'view'" type="textarea" :rows="4" placeholder='JSON，例如 {"lineCode":"L01","sensor":"TEMP"}' />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" :readonly="optType === 'view'" type="textarea" :rows="3" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="optType !== 'view'" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="historyTitle" :visible.sync="historyOpen" width="1100px" append-to-body @opened="renderHistoryChart">
      <el-row :gutter="12" class="history-toolbar">
        <el-col :span="5">
          <el-select v-model="historyQuery.range" placeholder="时间范围" @change="loadHistory">
            <el-option label="最近1小时" value="1h" />
            <el-option label="最近6小时" value="6h" />
            <el-option label="最近24小时" value="24h" />
            <el-option label="最近7天" value="7d" />
          </el-select>
        </el-col>
        <el-col :span="13">
          <el-date-picker
            v-model="historyDateRange"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            @change="handleDateRangeChange"
          />
        </el-col>
        <el-col :span="4" class="history-toolbar-action">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="loadHistory">查询曲线</el-button>
        </el-col>
      </el-row>
      <el-descriptions v-if="currentPoint.pointCode" :column="4" border size="small" class="history-summary">
        <el-descriptions-item label="测量点">{{ currentPoint.pointName || currentPoint.pointCode }}</el-descriptions-item>
        <el-descriptions-item label="最新值">{{ formatLatestValue(currentPoint) }}</el-descriptions-item>
        <el-descriptions-item label="最新时间">{{ currentPoint.latestTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="单位">{{ currentPoint.unit || '-' }}</el-descriptions-item>
      </el-descriptions>
      <div v-loading="historyLoading" ref="historyChart" class="history-chart"></div>
    </el-dialog>
  </div>
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons')
import { listAllWorkshop } from '@/api/mes/md/workshop'
import { addMeasurePoint, delMeasurePoint, getMeasurePoint, getMeasurePointHistory, listMeasurePoint, updateMeasurePoint } from '@/api/mes/md/measurepoint'

export default {
  name: 'MeasurePoint',
  dicts: ['sys_yes_no'],
  data() {
    return {
      loading: false,
      historyLoading: false,
      open: false,
      historyOpen: false,
      showSearch: true,
      single: true,
      multiple: true,
      total: 0,
      title: '',
      historyTitle: '历史曲线',
      optType: undefined,
      ids: [],
      workshopOptions: [],
      measurePointList: [],
      historyRecords: [],
      historyDateRange: [],
      currentPoint: {},
      historyChart: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        pointCode: null,
        pointName: null,
        workshopId: null,
        deviceCode: null,
        enableFlag: null
      },
      form: {},
      historyQuery: {
        pointCode: null,
        range: '24h',
        interval: '5m',
        startTime: null,
        endTime: null
      },
      rules: {
        pointCode: [{ required: true, message: '测量点编码不能为空', trigger: 'blur' }],
        pointName: [{ required: true, message: '测量点名称不能为空', trigger: 'blur' }],
        fieldKey: [{ required: true, message: '字段名不能为空', trigger: 'blur' }],
        enableFlag: [{ required: true, message: '请选择启用状态', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getWorkshopOptions()
    this.getList()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeHistoryChart)
    if (this.historyChart) {
      this.historyChart.dispose()
      this.historyChart = null
    }
  },
  methods: {
    getList() {
      this.loading = true
      listMeasurePoint(this.queryParams).then(response => {
        this.measurePointList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    getWorkshopOptions() {
      listAllWorkshop().then(response => {
        this.workshopOptions = response.data || []
      })
    },
    reset() {
      this.form = {
        pointId: null,
        pointCode: null,
        pointName: null,
        workshopId: null,
        deviceCode: null,
        nodeCode: null,
        fieldKey: null,
        tagJson: null,
        unit: null,
        precisionDigit: 2,
        sortNum: 1,
        enableFlag: 'Y',
        remark: 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.pointId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.optType = 'add'
      this.title = '新增测量点'
    },
    handleUpdate(row) {
      this.reset()
      const pointId = row.pointId || this.ids[0]
      getMeasurePoint(pointId).then(response => {
        this.form = response.data
        this.open = true
        this.optType = 'edit'
        this.title = '修改测量点'
      })
    },
    handleView(row) {
      this.reset()
      getMeasurePoint(row.pointId).then(response => {
        this.form = response.data
        this.open = true
        this.optType = 'view'
        this.title = '测量点详情'
      })
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return
        }
        const request = this.form.pointId ? updateMeasurePoint(this.form) : addMeasurePoint(this.form)
        request.then(() => {
          this.$modal.msgSuccess(this.form.pointId ? '修改成功' : '新增成功')
          this.open = false
          this.getList()
        })
      })
    },
    handleDelete(row) {
      const pointIds = row.pointId || this.ids
      this.$modal.confirm('是否确认删除测量点编号为“' + pointIds + '”的数据项？').then(() => {
        return delMeasurePoint(pointIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    cancel() {
      this.open = false
      this.reset()
    },
    refreshLatest() {
      this.getList()
    },
    formatLatestValue(row) {
      if (!row || row.latestValue === null || row.latestValue === undefined || row.latestValue === '') {
        return '-'
      }
      return row.unit ? row.latestValue + ' ' + row.unit : row.latestValue
    },
    openHistory(row) {
      this.currentPoint = { ...row }
      this.historyQuery.pointCode = row.pointCode
      this.historyQuery.range = '24h'
      this.historyQuery.interval = '5m'
      this.historyQuery.startTime = null
      this.historyQuery.endTime = null
      this.historyDateRange = []
      this.historyTitle = '历史曲线 - ' + (row.pointName || row.pointCode)
      this.historyOpen = true
      this.loadHistory()
    },
    handleDateRangeChange(value) {
      if (value && value.length === 2) {
        this.historyQuery.startTime = value[0]
        this.historyQuery.endTime = value[1]
      } else {
        this.historyQuery.startTime = null
        this.historyQuery.endTime = null
      }
    },
    loadHistory() {
      if (!this.historyQuery.pointCode) {
        return
      }
      this.historyLoading = true
      getMeasurePointHistory(this.historyQuery).then(response => {
        const data = response.data || {}
        this.currentPoint = data.point || this.currentPoint
        this.historyRecords = data.records || []
        this.historyLoading = false
        this.$nextTick(() => {
          this.renderHistoryChart()
        })
      }).catch(() => {
        this.historyLoading = false
      })
    },
    renderHistoryChart() {
      if (!this.historyOpen || !this.$refs.historyChart) {
        return
      }
      if (!this.historyChart) {
        this.historyChart = echarts.init(this.$refs.historyChart, 'macarons')
        window.addEventListener('resize', this.resizeHistoryChart)
      }
      const xAxisData = this.historyRecords.map(item => item.time)
      const seriesData = this.historyRecords.map(item => item.value)
      this.historyChart.setOption({
        tooltip: { trigger: 'axis' },
        grid: { left: 50, right: 30, top: 40, bottom: 80 },
        xAxis: {
          type: 'category',
          data: xAxisData,
          boundaryGap: false,
          axisLabel: { rotate: 30 }
        },
        yAxis: {
          type: 'value',
          name: this.currentPoint.unit || ''
        },
        dataZoom: [
          { type: 'inside' },
          { type: 'slider', bottom: 20 }
        ],
        series: [{
          name: this.currentPoint.pointName || this.currentPoint.pointCode,
          type: 'line',
          smooth: true,
          showSymbol: false,
          lineStyle: { width: 2 },
          areaStyle: { opacity: 0.15 },
          data: seriesData
        }]
      }, true)
      this.resizeHistoryChart()
    },
    resizeHistoryChart() {
      if (this.historyChart) {
        this.historyChart.resize()
      }
    }
  }
}
</script>

<style scoped>
.history-toolbar {
  margin-bottom: 12px;
}

.history-toolbar .el-select,
.history-toolbar .el-date-editor {
  width: 100%;
}

.history-toolbar-action {
  text-align: right;
}

.history-summary {
  margin-bottom: 12px;
}

.history-chart {
  width: 100%;
  height: 460px;
}
</style>
