<template>
  <div class="app-container">
    <el-card style="height: 850px">
      <div style="margin-top: 7px; margin-bottom: 7px">
        &nbsp;&nbsp;
        <span class="show-text">日期:</span>
        <el-date-picker
          v-model="completionTime"
          :clearable="false"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          popper-class="virtual-cell-time-picker"
          range-separator="-"
          start-placeholder="开始日期"
          style="width: 280px;vertical-align: top"
          type="daterange"
          value-format="yyyy-MM-dd"
        />
        &nbsp;&nbsp;
        <span class="show-text">设备:</span>
        <el-select v-model="equipmentType" placeholder="请选择设备" filterable size="small" style="width:100px" @change="searchTable" >
          <el-option
            v-for="item in basedatalx"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
        <el-button type="primary" icon="el-icon-search" size="small" style="margin-left: 20px" plain @click="pageSize = 20;pageCurrent = 1;searchTable()">查询</el-button>
      </div>
      <div style="display: flex">
        <div style="width: 600px">
          <el-table :data="tableData" border size="small" stripe highlight-current-row height="740px" >
            <el-table-column label="设备名称" prop="Zone" align="center" width="150px" >
              <template slot-scope="scope">
                {{ scope.row.设备名称 }}
              </template>
            </el-table-column>
            <el-table-column label="参数名称" prop="TagName" align="center" width="150px" >
              <template slot-scope="scope">
                {{ scope.row.参数名称 }}
              </template>
            </el-table-column>
            <el-table-column label="参数值" align="center">
              <template slot-scope="scope">
                {{ scope.row.参数值 }}{{ scope.row.参数单位 }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100px">
              <template slot-scope="scope">
                <el-button v-if="scope.row.数据类型 > 0" type="text" size="mini" icon="el-icon-search" style="width: 20px" @click="handleSearch(scope.row)"/>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="width: 800px;margin-left: 5px">
          <el-table v-if="dataType === 1" :data="tableData1" v-loading="loading" border size="small" stripe highlight-current-row height="740px" >
            <el-table-column label="开始时间" prop="Zone" align="center" width="150px" >
              <template slot-scope="scope">
                {{ scope.row.开始时间 }}
              </template>
            </el-table-column>
            <el-table-column label="结束时间" prop="TagName" align="center" width="150px" >
              <template slot-scope="scope">
                {{ scope.row.结束时间 }}
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" width="100px" >
              <template slot-scope="scope">
                {{ scope.row.状态名称 }}
              </template>
            </el-table-column>
            <el-table-column label="时长(min)" align="center">
              <template slot-scope="scope">
                {{ scope.row.累计分钟数 }}
              </template>
            </el-table-column>
          </el-table>
          <div v-if="dataType === 2">
            <span class="show-text">订单编号:</span>
            <el-input
              v-model="orderNo"
              placeholder="请输入订单编号"
              clearable
              style="width: 150px; margin-right: 10px"
            />
            <el-button type="primary" icon="el-icon-search" size="small" style="margin-left: 20px" plain @click="handleSearch(currentRow)">查询</el-button>
            <el-table :data="tableData1" border size="small" stripe highlight-current-row height="700px" style="margin-top: 5px" >
              <el-table-column label="订单编号" prop="Zone" align="center" width="100px" >
                <template slot-scope="scope">
                  {{ scope.row.订单编号 }}
                </template>
              </el-table-column>
              <el-table-column label="加工时长(min)" prop="TagName" align="center">
                <template slot-scope="scope">
                  {{ scope.row.循环时间 }}
                </template>
              </el-table-column>
              <el-table-column label="换件时长(min)" prop="TagName" align="center">
                <template slot-scope="scope">
                  {{ scope.row.换件时间 }}
                </template>
              </el-table-column>
              <el-table-column label="采集时间" align="center" width="150px" >
                <template slot-scope="scope">
                  {{ scope.row.采集时间 }}
                </template>
              </el-table-column>
            </el-table>
            <div class="block" style="margin-top: 10px;">
              <el-pagination
                :current-page="pageCurrent"
                :page-sizes="[20, 40, 50, 100]"
                :page-size="pageSize"
                :total="total"
                :small="true"
                layout="total, sizes, prev, pager, next"
                @size-change="handleSizeChanges"
                @current-change="handleCurrentChanges"/>
            </div>
          </div>
          <el-table v-if="dataType === 3" :data="tableData1" border size="small" stripe highlight-current-row height="740px" >
            <el-table-column label="订单编号" prop="Zone" align="center" width="100px" >
              <template slot-scope="scope">
                {{ scope.row.订单编号 }}
              </template>
            </el-table-column>
            <el-table-column label="程序时长(min)" prop="Zone" align="center" width="120px" >
              <template slot-scope="scope">
                <span style="color: #0ba9e3">{{ scope.row.程序时长 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="最小时长(min)" prop="Zone" align="center" width="120px" >
              <template slot-scope="scope">
                {{ scope.row.最小时长 }}
              </template>
            </el-table-column>
            <el-table-column label="最大时长(min)" prop="Zone" align="center" width="120px" >
              <template slot-scope="scope">
                {{ scope.row.最大时长 }}
              </template>
            </el-table-column>
<!--            <el-table-column label="频次/总数" prop="Zone" align="center" >-->
<!--              <template slot-scope="scope">-->
<!--                {{ scope.row.频次 }} / {{ scope.row.总记录数 }}-->
<!--              </template>-->
<!--            </el-table-column>-->
            <el-table-column label="产品编码" prop="Zone" align="center">
              <template slot-scope="scope">
                {{ scope.row.产品编码 }}
              </template>
            </el-table-column>
            <el-table-column label="产品名称" prop="Zone" align="center" >
              <template slot-scope="scope">
                {{ scope.row.产品名称 }}
              </template>
            </el-table-column>
          </el-table>
          <el-table v-if="dataType === 4" :data="tableData1" border size="small" stripe highlight-current-row height="740px" >
            <el-table-column label="订单编号" prop="Zone" align="center" width="100px" >
              <template slot-scope="scope">
                {{ scope.row.订单编号 }}
              </template>
            </el-table-column>
            <el-table-column label="换件时长(min)" prop="Zone" align="center" width="120px" >
              <template slot-scope="scope">
                <span style="color: #0ba9e3">{{ scope.row.换件时长 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="最小时长(min)" prop="Zone" align="center" width="120px" >
              <template slot-scope="scope">
                {{ scope.row.最小时长 }}
              </template>
            </el-table-column>
            <el-table-column label="最大时长(min)" prop="Zone" align="center" width="120px" >
              <template slot-scope="scope">
                {{ scope.row.最大时长 }}
              </template>
            </el-table-column>
<!--            <el-table-column label="频次/总数" prop="Zone" align="center" >-->
<!--              <template slot-scope="scope">-->
<!--                {{ scope.row.频次 }} / {{ scope.row.总记录数 }}-->
<!--              </template>-->
<!--            </el-table-column>-->
            <el-table-column label="产品编码" prop="Zone" align="center" >
              <template slot-scope="scope">
                {{ scope.row.产品编码 }}
              </template>
            </el-table-column>
            <el-table-column label="产品名称" prop="Zone" align="center" >
              <template slot-scope="scope">
                {{ scope.row.产品名称 }}
              </template>
            </el-table-column>
          </el-table>

        </div>
      </div>

      <!--      <div class="block" style="margin-top: 10px;">-->
      <!--        <el-pagination-->
      <!--          :current-page="pageCurrent"-->
      <!--          :page-sizes="[10, 20, 30, 40, 100]"-->
      <!--          :page-size="pageSize"-->
      <!--          :total="total"-->
      <!--          layout="total, sizes, prev, pager, next, jumper"-->
      <!--          @size-change="handleSizeChanges"-->
      <!--          @current-change="handleCurrentChanges"/>-->
      <!--      </div>-->
    </el-card>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getNowDate, getNowTime } from '../../../utils/tool'
export default {
  data() {
    return {
      completionTime: [],
      routineCheckType: [],
      dataType: 0,
      orderNo: '',
      loading: false,
      dialogFormVisible: false,
      title: '',
      equipmentValue: '',
      equipmentName: '',
      equipmentType: '',
      opName: '',
      process: [],
      form: {
        设备名称: '',
        设备型号: '',
        设备类型: ''
        // 加工工艺: '',
        // 工位号: '',
        // 点检类型: '',
        // 工时单价: '',
        // 月设备加工能力: ''
      },
      basedatalx: [],
      rules: {
        设备名称: [{ required: true, message: '请输入设备名称' }],
        // 设备型号: [{ required: true, message: '请输入设备型号' }],
        // 加工工艺: [{ required: true, message: '请选择加工工艺' }],
        设备类型: [{ required: true, message: '请选择' }]
      },
      original: '',
      currentRow: null,
      total: 0, // 分页总数
      tableData: [], // 设备信息表
      tableData1: [], // 设备信息表
      pageCurrent: 1, // 分页当前页
      pageSize: 20, // 分页每页显示条数
      dataname: ''
    }
  },
  computed: {
    ...mapGetters([
      'id',
      'token'
    ])
  },
  created() {
    this.completionTime = [getNowDate(), getNowDate()]
    this.getbasedata()
  },
  methods: {

    getbasedata() {
      var Data = this.CreateData('11', '设备管理_设备数据_工位信息_查询')
      this.ExecDatabase(Data).then(response => {
        response.data.forEach(element => {
          this.basedatalx.push({
            name: element.工位名称,
            id: element.工位号
          })
        })
        if (response.data.length > 0) {
          this.equipmentType = response.data[0].工位号
          this.searchTable()
        }
      })
    },
    searchTable() {
      if (this.equipmentType === '') {
        this.$message({
          message: '请选择设备',
          type: 'warning'
        })
        return
      }
      var param = []
      // param.push(['PageCurrent', this.pageCurrent]),
      // param.push(['PageSize', this.pageSize]),
      // param.push(['PageCount', '1111', 'int', '1']),
      // param.push(['ItemCount', '1111', 'int', '1'])
      param.push(['开始时间', this.completionTime[0]])
      param.push(['结束时间', this.completionTime[1]])
      param.push(['设备名称', this.equipmentType])
      var Data = this.CreateData('11', '设备管理_设备数据_统计数据查询', param)
      this.ExecDatabase(Data).then(response => {
        this.tableData = response.data
        // this.tableData = response.data.result
        // this.total = parseInt(response.data.output[0].ItemCount)
      })
    },
    /**
     * 处理设备状态记录，合并连续状态的时间段
     * @param {Array} records - 原始记录数组，每条记录需包含 DeviceCode, 设备状态, 创建时间
     * @returns {Array} 合并后的时间段数组
     */
    mergeContinuousStatus(records) {
      if (!records || records.length === 0) return []

      // 1. 按创建时间排序（升序）
      const sorted = [...records].sort((a, b) => new Date(a.创建时间) - new Date(b.创建时间))

      const result = []
      let currentGroup = null

      for (const record of sorted) {
        const currentTime = new Date(record.创建时间)
        const status = record.设备状态
        const statusName = record.状态名称
        const deviceCode = record.DeviceCode

        if (!currentGroup) {
          // 第一个记录，初始化分组
          currentGroup = {
            DeviceCode: deviceCode,
            设备状态: status,
            状态名称: statusName,
            开始时间: record.创建时间,
            结束时间: record.创建时间,
            累计分钟数: 1,
            记录数: 1
          }
        } else {
          // 检查是否与上一记录连续（时间差 ≤ 1分钟）
          const lastTime = new Date(currentGroup.结束时间)
          const diffMinutes = (currentTime - lastTime) / (1000 * 60)

          // 连续条件：状态相同 且 时间间隔 ≤ 1分钟
          if (currentGroup.设备状态 === status && diffMinutes <= 1) {
            // 合并：更新结束时间和累计时间
            currentGroup.结束时间 = record.创建时间
            currentGroup.累计分钟数 += diffMinutes
            currentGroup.记录数 += 1
          } else {
            // 不连续或状态变化，保存当前分组，开始新分组
            result.push({ ...currentGroup })
            currentGroup = {
              DeviceCode: deviceCode,
              设备状态: status,
              状态名称: statusName,
              开始时间: record.创建时间,
              结束时间: record.创建时间,
              累计分钟数: 1,
              记录数: 1
            }
          }
        }
      }

      // 添加最后一个分组
      if (currentGroup) {
        result.push(currentGroup)
      }
      console.log(result)
      return result
    },

    handleSearch(row) {
      this.loading = true
      this.tableData1 = []
      this.dataType = row.数据类型
      this.currentRow = row
      var param = []
      param.push(['PageCurrent', this.pageCurrent])
      param.push(['PageSize', this.pageSize])
      param.push(['PageCount', '1111', 'int', '1'])
      param.push(['ItemCount', '1111', 'int', '1'])
      param.push(['开始时间', this.completionTime[0]])
      param.push(['结束时间', this.completionTime[1]])
      param.push(['设备名称', this.equipmentType])
      param.push(['参数名称', row.参数名称])
      param.push(['数据类型', row.数据类型])
      param.push(['订单编号', this.orderNo])
      var Data = this.CreateData('11', '设备管理_设备数据_统计数据查询_通过类型', param)
      this.ExecDatabase(Data).then(response => {
        this.loading = false
        console.log(response.data)
        if (row.数据类型 === 1) {
          this.tableData1 = this.mergeContinuousStatus(response.data.result)
        } else if (row.数据类型 === 2) {
          this.tableData1 = response.data.result
          this.total = parseInt(response.data.output[0].ItemCount)
        } else {
          this.tableData1 = response.data.result
        }

        // this.tableData = response.data.result
        // this.total = parseInt(response.data.output[0].ItemCount)
      }).catch(() => {
        this.loading = false
      })
    },
    handleSizeChanges(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.handleSearch(this.currentRow)
    },
    handleCurrentChanges(val) {
      this.pageCurrent = val
      this.handleSearch(this.currentRow)
    }
  }
}
</script>

