<template>
  <div class="app-container device-information-page">
    <el-card class="device-card">
      <div class="filter-bar">
        <el-input v-model="equipmentName" placeholder="生产用名" size="small" clearable class="filter-control"/>
        <el-select v-model="equipmentType" placeholder="设备类型" filterable size="small" clearable class="filter-control">
          <el-option
            v-for="item in basedatalx"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-button type="primary" icon="el-icon-search" size="small" plain @click="pageSize = 20; pageCurrent = 1; searchTable()">查询</el-button>
        <el-tooltip effect="dark" content="添加新设备" placement="top">
          <el-button type="distribution" icon="el-icon-circle-plus-outline" size="small" @click="ADD()">设备</el-button>
        </el-tooltip>
      </div>
      <el-table
        :data="sortedTableData"
        :row-class-name="tableRowClassName"
        border
        size="small"
        stripe
        highlight-current-row
        height="740px"
        class="device-table">
        <el-table-column label="设备名称" prop="名称" align="center" width="150" show-overflow-tooltip/>
        <el-table-column label="公司编码（财务）" prop="公司编码" align="center" width="140" show-overflow-tooltip/>
        <el-table-column label="生产用名" prop="设备名称" align="center" width="150" show-overflow-tooltip/>
        <el-table-column label="规格/型号" prop="设备型号" align="center" width="150" show-overflow-tooltip/>
        <el-table-column label="设备类型" prop="设备类型名称" align="center" width="130" show-overflow-tooltip/>
        <el-table-column label="设备信息" prop="设备信息" align="center" width="160" show-overflow-tooltip/>
        <el-table-column label="使用部门" prop="使用部门" align="center" width="120" show-overflow-tooltip/>
        <el-table-column label="入账日期" prop="入账日期" align="center" width="120">
          <template slot-scope="scope">{{ formatDate(scope.row.入账日期) }}</template>
        </el-table-column>
        <el-table-column label="单位" prop="单位" align="center" width="80" show-overflow-tooltip/>
        <el-table-column label="数量" prop="数量" align="center" width="90" show-overflow-tooltip/>
        <el-table-column label="状态" prop="状态" align="center" width="100" show-overflow-tooltip/>
        <el-table-column label="维修记录" prop="维修记录" align="center" width="160" show-overflow-tooltip/>
        <el-table-column label="维保记录" prop="维保记录" align="center" width="160" show-overflow-tooltip/>
        <el-table-column label="工位绑定" prop="工位绑定" align="center" width="180" show-overflow-tooltip>
          <template slot-scope="scope">{{ formatStationNames(scope.row.工位绑定) }}</template>
        </el-table-column>
        <el-table-column label="主要设备" prop="主要设备" align="center" width="90" show-overflow-tooltip/>
        <el-table-column label="设备标准开机工时(小时)" prop="设备标准开机工时" align="center" width="170" show-overflow-tooltip/>
        <el-table-column label="特种设备" prop="特种设备" align="center" width="90" show-overflow-tooltip/>
        <el-table-column label="证书有效期至" prop="证书有效期至" align="center" width="130">
          <template slot-scope="scope">{{ formatDate(scope.row.证书有效期至) }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="90">
          <template slot-scope="scope">
            <el-button type="text" size="mini" icon="el-icon-edit" style="margin-right:10px" @click="handleEdit(scope.row)"/>
            <el-button type="text" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)"/>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-bar">
        <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>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" center width="980px">
      <el-form ref="form" :model="form" :rules="rules" label-position="right" label-width="150px" class="device-form">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="名称">
              <el-input v-model="form.名称" placeholder="设备名称" size="small" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司编码（财务）" prop="公司编码">
              <el-input v-model="form.公司编码" :disabled="title === '编辑设备'" placeholder="公司编码（财务）" size="small" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产用名" prop="设备名称">
              <el-input v-model="form.设备名称" placeholder="生产用名" size="small" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格/型号" prop="设备型号">
              <el-input v-model="form.设备型号" placeholder="规格/型号" size="small" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="设备类型">
              <el-select v-model="form.设备类型" placeholder="设备类型" filterable size="small" clearable>
                <el-option
                  v-for="item in basedatalx"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备信息" prop="设备信息">
              <el-input v-model="form.设备信息" placeholder="设备信息" size="small" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用部门" prop="使用部门">
              <el-input v-model="form.使用部门" placeholder="使用部门" size="small" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入账日期" prop="入账日期">
              <el-date-picker v-model="form.入账日期" type="date" placeholder="入账日期" size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="单位">
              <el-input v-model="form.单位" placeholder="单位" size="small" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="数量">
              <el-input v-positive="'float'" v-model="form.数量" type="number" placeholder="数量" size="small" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="状态">
              <el-input v-model="form.状态" placeholder="状态" size="small" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维修记录" prop="维修记录">
              <el-input v-model="form.维修记录" placeholder="维修记录" size="small" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维保记录" prop="维保记录">
              <el-input v-model="form.维保记录" placeholder="维保记录" size="small" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工位绑定" prop="工位绑定">
              <el-select v-model="form.工位绑定" placeholder="工位绑定" filterable multiple collapse-tags size="small" clearable>
                <el-option
                  v-for="item in stationOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主要设备" prop="主要设备">
              <el-select v-model="form.主要设备" placeholder="主要设备" size="small" clearable>
                <el-option label="是" value="是"/>
                <el-option label="否" value="否"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备标准开机工时" prop="设备标准开机工时">
              <el-input v-positive="'float'" v-model="form.设备标准开机工时" type="number" placeholder="小时" size="small" clearable>
                <template slot="append">小时</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="特种设备" prop="特种设备">
              <el-select v-model="form.特种设备" placeholder="特种设备" size="small" clearable>
                <el-option label="是" value="是"/>
                <el-option label="否" value="否"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证书有效期至" prop="证书有效期至">
              <el-date-picker v-model="form.证书有效期至" type="date" placeholder="证书有效期至" size="small"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="callOff('form')">取消</el-button>
        <el-button v-show="title === '新增设备'" type="primary" @click="submitAdd('form')">确定</el-button>
        <el-button v-show="title === '编辑设备'" type="primary" @click="submitEdit('form')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

const emptyForm = () => ({
  名称: '',
  公司编码: '',
  设备名称: '',
  设备型号: '',
  设备类型: '',
  设备信息: '',
  使用部门: '',
  入账日期: null,
  单位: '',
  数量: '',
  状态: '',
  维修记录: '',
  维保记录: '',
  工位绑定: [],
  主要设备: '',
  设备标准开机工时: '',
  特种设备: '',
  证书有效期至: null
})

export default {
  name: 'DeviceInformation',
  data() {
    const validateCompanyCode = (rule, value, callback) => {
      if (this.title === '新增设备' && !value) {
        callback(new Error('请输入公司编码'))
      } else {
        callback()
      }
    }

    return {
      dialogFormVisible: false,
      title: '',
      equipmentValue: '',
      equipmentName: '',
      equipmentType: '',
      form: emptyForm(),
      basedatalx: [],
      stationOptions: [],
      rules: {
        公司编码: [{ validator: validateCompanyCode, trigger: 'blur' }],
        设备名称: [{ required: true, message: '请输入生产用名', trigger: 'blur' }]
      },
      total: 0,
      tableData: [],
      pageCurrent: 1,
      pageSize: 20
    }
  },
  computed: {
    ...mapGetters([
      'id',
      'token'
    ]),
    sortedTableData() {
      return [...this.tableData].sort((a, b) => {
        const aLevel = this.getCertificateLevel(a.证书有效期至)
        const bLevel = this.getCertificateLevel(b.证书有效期至)
        if (aLevel !== bLevel) return aLevel - bLevel
        return this.getDateTime(a.证书有效期至) - this.getDateTime(b.证书有效期至)
      })
    }
  },
  created() {
    this.searchTable()
    this.getbasedata()
    this.getStationOptions()
  },
  methods: {
    getbasedata() {
      var Data = this.CreateData('11', '查询字典')
      this.ExecDatabase(Data).then(response => {
        this.basedatalx = []
        response.data.forEach(element => {
          if (element.数据类别 == '设备类型') {
            this.basedatalx.push({
              name: element.词条名称,
              id: element.AID
            })
          }
        })
      })
    },
    getStationOptions() {
      var Data = this.CreateData('11', 'MES_登录_工位与名称_查询', [])
      this.ExecDatabase(Data).then(response => {
        this.stationOptions = (response.data || []).map(item => ({
          label: item.指南工位号 || item.工位名称 || item.工位号,
          value: item.工位号
        }))
      })
    },
    searchTable() {
      let equipmentName_check, equipmentType_check
      this.equipmentName ? equipmentName_check = 1 : equipmentName_check = 0
      this.equipmentType ? equipmentType_check = 1 : equipmentType_check = 0
      var param = []
      param[0] = ['设备名称_check', equipmentName_check]
      param[1] = ['设备名称', this.equipmentName]
      param[2] = ['设备类型', this.equipmentType]
      param[3] = ['设备类型_check', equipmentType_check]
      var Data = this.CreateData('11', '设备管理_设备信息_查询', param, this.pageSize, this.pageCurrent)
      this.ExecDatabase(Data).then(response => {
        this.tableData = response.data.rows || []
        this.total = response.data.total || 0
      })
    },
    ADD() {
      this.title = '新增设备'
      if (this.$refs.form !== undefined) {
        this.$refs.form.resetFields()
      }
      this.form = emptyForm()
      this.dialogFormVisible = true
    },
    handleEdit(row) {
      this.title = '编辑设备'
      if (this.$refs.form !== undefined) {
        this.$refs.form.resetFields()
      }
      this.equipmentValue = row.设备流水号
      const editForm = {
        名称: row.名称 || '',
        公司编码: row.公司编码 || '',
        设备名称: row.设备名称 || '',
        设备型号: row.设备型号 || '',
        设备类型: row.设备类型 ? parseInt(row.设备类型) : '',
        设备信息: row.设备信息 || '',
        使用部门: row.使用部门 || '',
        入账日期: this.parseDateValue(row.入账日期 || row['入账日期']),
        单位: row.单位 || '',
        数量: row.数量 || '',
        状态: row.状态 || '',
        维修记录: row.维修记录 || '',
        维保记录: row.维保记录 || '',
        工位绑定: this.parseStationBinding(row.工位绑定),
        主要设备: row.主要设备 || '',
        设备标准开机工时: row.设备标准开机工时 || '',
        特种设备: row.特种设备 || '',
        证书有效期至: this.parseDateValue(row.证书有效期至 || row['证书有效期至'])
      }
      Object.keys(editForm).forEach(key => {
        this.$set(this.form, key, editForm[key])
      })
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$set(this.form, '入账日期', editForm.入账日期)
        this.$set(this.form, '证书有效期至', editForm.证书有效期至)
      })
    },
    callOff(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    submitAdd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var Data = this.CreateData('12', '设备管理_设备信息_增加', this.buildSubmitParams())
          this.ExecDatabase(Data).then(response => {
            if (response.data[0].result === '1') {
              this.$message.success('添加成功')
              this.searchTable()
              this.dialogFormVisible = false
            } else {
              this.$message.error('添加失败')
            }
          })
        }
      })
    },
    submitEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var param = this.buildSubmitParams()
          param.unshift(['设备流水号', this.equipmentValue])
          var Data = this.CreateData('12', '设备管理_设备信息_编辑', param)
          this.ExecDatabase(Data).then(response => {
            if (response.data[0].result === '1') {
              this.$message.success('编辑成功')
              this.searchTable()
              this.dialogFormVisible = false
            } else {
              this.$message.error('编辑失败')
            }
          })
        }
      })
    },
    buildSubmitParams() {
      return [
        ['名称', this.form.名称],
        ['公司编码', this.form.公司编码],
        ['设备名称', this.form.设备名称],
        ['设备型号', this.form.设备型号],
        ['设备类型', this.form.设备类型],
        ['设备信息', this.form.设备信息],
        ['使用部门', this.form.使用部门],
        ['入账日期', this.dateParam(this.form.入账日期)],
        ['单位', this.form.单位],
        ['数量', this.nullIfEmpty(this.form.数量)],
        ['状态', this.form.状态],
        ['维修记录', this.form.维修记录],
        ['维保记录', this.form.维保记录],
        ['工位绑定', (this.form.工位绑定 || []).join(',')],
        ['主要设备', this.form.主要设备],
        ['设备标准开机工时', this.nullIfEmpty(this.form.设备标准开机工时)],
        ['特种设备', this.form.特种设备],
        ['证书有效期至', this.dateParam(this.form.证书有效期至)]
      ]
    },
    handleDelete(row) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var param = []
        param[0] = ['设备流水号', row.设备流水号]
        var Data = this.CreateData('12', '设备管理_设备信息_删除', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === '1') {
            this.$message.success('删除成功')
            this.pageCurrent = 1
            this.searchTable()
          } else {
            this.$message.error('删除失败')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSizeChanges(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.searchTable()
    },
    handleCurrentChanges(val) {
      this.pageCurrent = val
      this.searchTable()
    },
    tableRowClassName({ row }) {
      const level = this.getCertificateLevel(row.证书有效期至)
      if (level === 0) return 'certificate-expired-row'
      if (level === 1) return 'certificate-warning-row'
      return ''
    },
    getCertificateLevel(value) {
      const time = this.getDateTime(value)
      if (!time) return 2
      const today = new Date()
      today.setHours(0, 0, 0, 0)
      const warningEnd = new Date(today)
      warningEnd.setDate(warningEnd.getDate() + 30)
      if (time < today.getTime()) return 0
      if (time <= warningEnd.getTime()) return 1
      return 2
    },
    getDateTime(value) {
      if (!value) return 0
      const date = new Date(value)
      if (Number.isNaN(date.getTime())) return 0
      date.setHours(0, 0, 0, 0)
      return date.getTime()
    },
    formatDate(value) {
      if (!value) return ''
      if (typeof value === 'string') {
        const timestampMatch = value.match(/\/Date\((\d+)\)\//)
        if (timestampMatch) return this.formatDate(new Date(Number(timestampMatch[1])))
        const match = value.match(/\d{4}[-/.]\d{1,2}[-/.]\d{1,2}/)
        return match ? match[0].replace(/[/.]/g, '-') : ''
      }
      const date = new Date(value)
      if (Number.isNaN(date.getTime())) return ''
      const month = `${date.getMonth() + 1}`.padStart(2, '0')
      const day = `${date.getDate()}`.padStart(2, '0')
      return `${date.getFullYear()}-${month}-${day}`
    },
    parseStationBinding(value) {
      if (!value) return []
      if (Array.isArray(value)) return value
      return `${value}`.split(/[,，]/).map(item => item.trim()).filter(item => item)
    },
    formatStationNames(value) {
      const values = this.parseStationBinding(value)
      if (values.length === 0) return ''
      return values.map(value => {
        const option = this.stationOptions.find(item => item.value === value)
        return option ? option.label : value
      }).join(',')
    },
    nullIfEmpty(value) {
      return value === '' || value === undefined ? null : value
    },
    dateParam(value) {
      if (value === null || value === undefined || value === '') return ''
      return this.formatDate(value)
    },
    parseDateValue(value) {
      if (!value) return null
      if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value
      const text = this.formatDate(value)
      if (!text) return null
      const parts = text.split('-').map(item => Number(item))
      if (parts.length !== 3 || parts.some(item => Number.isNaN(item))) return null
      return new Date(parts[0], parts[1] - 1, parts[2])
    },
    debugDateValue(label, value) {
      if (process.env.NODE_ENV !== 'production') {
        console.log(`[DeviceInformation] ${label}:`, value, this.parseDateValue(value))
      }
    }
  }
}
</script>

<style scoped>
.device-card {
  height: 850px;
}

.filter-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 7px;
  margin-bottom: 7px;
}

.filter-control {
  width: 200px;
}

.device-table {
  width: 100%;
}

.pagination-bar {
  margin-top: 10px;
}

.device-form ::v-deep .el-input,
.device-form ::v-deep .el-select,
.device-form ::v-deep .el-date-editor {
  width: 260px;
}

.device-information-page ::v-deep .certificate-expired-row td {
  background-color: #fde2e2 !important;
}

.device-information-page ::v-deep .certificate-warning-row td {
  background-color: #fdf6d3 !important;
}
</style>
