<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:200px" clearable >
          <el-option
            v-for="item in basedatalx"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <span class="show-text">参数名称:</span>
        <el-input
          v-model="dataname"
          placeholder="请输入参数名称"
          clearable
          style="width: 150px; margin-right: 10px"
        />
        <el-button type="primary" icon="el-icon-search" size="small" style="margin-left: 20px" plain @click="pageSize = 20;pageCurrent = 1;searchTable()">查询</el-button>
        <el-button
          :disabled="tableData.length === 0"
          :loading="exporting"
          type="success"
          icon="el-icon-download"
          size="small"
          plain
          @click="exportToExcel">导出</el-button>
      </div>
      <div>
        <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="设备编号" prop="TagID" align="center" width="150px" >
            <template slot-scope="scope">
              {{ scope.row.TagID }}
            </template>
          </el-table-column> -->
          <el-table-column label="数值" align="center" width="250px">
            <template slot-scope="scope">
              {{ scope.row.值 }}
            </template>
          </el-table-column>
<!--          <el-table-column label="单位" prop="TagUnit" align="center" width="150px" >-->
<!--            <template slot-scope="scope">-->
<!--              {{ scope.row.TagUnit }}-->
<!--            </template>-->
<!--          </el-table-column>-->

          <el-table-column label="采集时间" align="center" width="160px">
            <template slot-scope="scope">
              {{ scope.row.创建时间 }}
            </template>
          </el-table-column>
        </el-table>
      </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'
import * as XLSX from 'xlsx'
export default {
  data() {
    return {
      completionTime: [],
      routineCheckType: [],
      dialogFormVisible: false,
      title: '',
      equipmentValue: '',
      equipmentName: '',
      equipmentType: '',
      opName: '',
      process: [],
      form: {
        设备名称: '',
        设备型号: '',
        设备类型: ''
        // 加工工艺: '',
        // 工位号: '',
        // 点检类型: '',
        // 工时单价: '',
        // 月设备加工能力: ''
      },
      basedatalx: [],
      rules: {
        设备名称: [{ required: true, message: '请输入设备名称' }],
        // 设备型号: [{ required: true, message: '请输入设备型号' }],
        // 加工工艺: [{ required: true, message: '请选择加工工艺' }],
        设备类型: [{ required: true, message: '请选择' }]
      },
      original: '',
      total: 0, // 分页总数
      tableData: [], // 设备信息表
      pageCurrent: 1, // 分页当前页
      pageSize: 20, // 分页每页显示条数
      dataname: '',
      exporting: false
    }
  },
  computed: {
    ...mapGetters([
      'id',
      'token'
    ])
  },
  created() {
    this.completionTime = [getNowDate(), getNowDate()]
    this.searchTable()
    this.getbasedata()
  },
  methods: {

    getbasedata() {
      var Data = this.CreateData('11', 'MES_登录_工位与名称_查询')
      this.ExecDatabase(Data).then(response => {
        response.data.forEach(element => {
          this.basedatalx.push({
            name: element.工位名称,
            id: element.工位号
          })
        })
      })
    },
    searchTable() {
      var param = this.buildQueryParams(this.pageSize, this.pageCurrent)
      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)
      })
    },
    buildQueryParams(pageSize, pageCurrent) {
      var param = []
      param.push(['PageCurrent', pageCurrent])
      param.push(['PageSize', 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(['参数名称', this.dataname])
      return param
    },
    exportToExcel() {
      if (this.tableData.length === 0) {
        this.$message.warning('没有数据可导出')
        return
      }

      this.exporting = true
      const exportPageSize = this.total > 0 ? this.total : this.tableData.length
      const param = this.buildQueryParams(exportPageSize, 1)
      const Data = this.CreateData('11', '设备管理_设备数据_历史查询', param)

      this.ExecDatabase(Data).then(response => {
        const rows = response.data && response.data.result ? response.data.result : []
        if (rows.length === 0) {
          this.$message.warning('没有数据可导出')
          return
        }
        this.writeHistoryExcel(rows)
      }).catch(error => {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      }).finally(() => {
        this.exporting = false
      })
    },
    writeHistoryExcel(rows) {
      const exportData = rows.map((item, index) => ({
        序号: index + 1,
        设备名称: item.设备代码 || '',
        参数名称: item.变量名称 || '',
        数值: item.值 || '',
        采集时间: item.创建时间 || ''
      }))
      const wb = XLSX.utils.book_new()
      const ws = XLSX.utils.json_to_sheet(exportData)
      ws['!cols'] = [
        { wch: 8 },
        { wch: 20 },
        { wch: 24 },
        { wch: 18 },
        { wch: 22 }
      ]
      XLSX.utils.book_append_sheet(wb, ws, '设备历史数据')
      XLSX.writeFile(wb, `设备历史数据_${this.formatDateForFileName(new Date())}.xlsx`)
      this.$message.success('导出成功')
    },
    formatDateForFileName(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}${month}${day}_${hours}${minutes}${seconds}`
    },

    handleSizeChanges(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.searchTable()
    },
    handleCurrentChanges(val) {
      this.pageCurrent = val
      this.searchTable()
    }
  }
}
</script>

