<template>
  <div class="app-container">
    <el-card class="topCard">
      <div class="topDiv">
        <span style="">工位号：</span>
        <el-select v-model="stationNumberValue" placeholder="请选择工位号" size="small" style="width: 240px"
          @change="getTableData">
          <el-option v-for="item in stationNumber" :key="item.value" :label="item.label" :value="item.value"
            size="mini" />
        </el-select>
        <el-button type="primary" icon="el-icon-search" size="small" style="margin-left: 20px;"
          @click="getTableData()">查询</el-button>
        <span style="font-size: 20px;margin-left: 30px">当前班次：{{ shiftNumber }}</span>
        <span v-if="currentProductType" style="font-size: 18px;margin-left: 20px;color: #409eff;font-weight: bold;">当前型号：{{ currentProductType }}</span>
        <el-button v-if="haveTask" type="warning" icon="el-icon-document-add" size="small" style="margin-left: 20px;"
          @click="createTask()">创建首件任务</el-button>
        <el-button v-if="!haveTask" type="danger" icon="el-icon-refresh-right" size="small" style="margin-left: 10px;"
          @click="showResetDialog()">重置首件数据</el-button>
        <el-button type="success" icon="el-icon-finished" size="small" style="margin-left: 10px;"
          @click="submitAllFirstPart()">提交首件数据</el-button>
        <div class="progress-box">
          <div class="progress-item">
            <span class="progress-title">首件进度</span>
            <span class="progress-value">{{ completedItems }}/{{ totalItems }}</span>
          </div>
        </div>
        <div class="scales-box">
          <div class="scale-item scale1">
            <span class="scale-title">秤1</span>
            <span class="scale-value">{{ scale1Value || '--' }}</span>
          </div>
          <div class="scale-item scale2">
            <span class="scale-title">秤2</span>
            <span class="scale-value">{{ scale2Value || '--' }}</span>
          </div>
        </div>
      </div>
      <div class="cards-wrap" v-loading="loading">
        <div style="display: flex;flex-wrap: wrap;">
          <div v-for="(item, index) in tableData" :key="index" class="taskItem" :class="item._taskItemClass">
            <div class="taskItem-title" :class="item._titleClass">{{ item.检测项目 }}</div>
            <el-form label-position="right" label-width="80px">
              <el-row>
                <el-col :span="10">
                  <el-form-item label="单位" style="display: inline;margin-bottom: 05px;">
                    {{ item.单位 }}
                  </el-form-item>
                </el-col>
                <el-col :span="14">
                  <div style="display: flex;align-items: center;height: 40px;">
                    <div class="tag-row">
                      <el-tag v-if="item.数据类型 === 0" type="info" size="mini">定性</el-tag>
                      <el-tag v-if="item.数据类型 === 1" type="success" size="mini">定量</el-tag>
                      <el-tag v-if="item.数据类型 === 2" type="warning" size="mini">文本</el-tag>
                      <el-tag v-if="item.项目类型 === 0" type="success" size="mini">常规项目</el-tag>
                      <!-- <el-tag v-if="item.项目类型 === 1" type="warning" size="mini">送检项目</el-tag> -->
                      <el-tag v-if="item.项目类型 === 2" type="info" size="mini">设备采集</el-tag>
                      <el-tag v-if="item.项目类型 === 3" type="primary" size="mini">拍照上传</el-tag>
                      <el-tag v-if="item.必填 === 1 || item.必填 === '1'" type="danger" size="mini">必填</el-tag>
                    </div>
                    <!-- <div style="margin-left: 8px;" v-if="item.项目类型 === 0">
                      <el-tag v-if="item.结果确认 === 0" type="warning" size="small">待检测</el-tag>
                      <el-tag v-if="item.结果确认 === 1" type="success" size="small">检测完成</el-tag>
                    </div> -->
                    <div style="margin-left: 8px;" v-if="item.项目类型 === 1">
                      <el-tag v-if="item.结果确认 === 0 && item.送检状态 === 0" type="warning" size="small">待送检</el-tag>
                      <el-tag v-if="item.结果确认 === 0 && item.送检状态 === 1" type="warning" size="small">送检中</el-tag>
                      <el-tag v-if="item.结果确认 === 1" type="success" size="small">检测完成</el-tag>
                    </div>
                    <!-- <div style="margin-left: 8px;" v-if="item.项目类型 === 2">
                      <el-tag v-if="item.是否确认 != 1" type="info" size="small">设备采集中</el-tag>
                      <el-tag v-else type="success" size="small">采集完毕</el-tag>
                    </div> -->
                  </div>
                </el-col>
              </el-row>
              <el-row v-if="item.数据类型 === 1">
                <el-col :span="24">
                  <div class="range-row">
                    <el-tag size="mini">范围</el-tag>
                    <span class="range-text">{{ item.下限值 }} ~ {{ item.上限值 }} {{ item.单位 }}</span>
                  </div>
                </el-col>
              </el-row>
              <el-form-item label="检测结果" style="display: inline;margin-bottom: 0px;">
                <div v-if="item.数据类型 === 1" style="display:flex; align-items:center;">
                  <el-input-number
                    :disabled="item._resultConfirm === 1 || (item.项目类型 === 1 && item._resultConfirm === 0 && item.送检状态 === 0) || item.项目类型 === 2"
                    v-model="item.测量值" size="mini" style="width: 200px" placeholder="请输入检测值"
                    @change="judgeResult(item)" />
                  <template
                    v-if="item.项目类型 !== 2 && item._resultConfirm !== 1 && !(item.项目类型 === 1 && item._resultConfirm === 0 && item.送检状态 === 0)">
                    <i class="el-icon-download" style="color: #409eff; cursor: pointer; margin-left: 6px; font-size: 16px;"
                       @click="fillByScale(item, 1)" title="从秤1获取数据"></i>
                    <i class="el-icon-download" style="color: #67c23a; cursor: pointer; margin-left: 6px; font-size: 16px;"
                       @click="fillByScale(item, 2)" title="从秤2获取数据"></i>
                  </template>
                </div>
                <el-radio-group v-if="item.数据类型 === 0 && item._resultConfirm !== 1 && item.项目类型 !== 3"
                  :disabled="item._resultConfirm === 1 || (item.项目类型 === 1 && item._resultConfirm === 0 && item.送检状态 === 0) || item.项目类型 === 2"
                  v-model="item.是否合格2" @change="recordValueChange(item)">
                  <el-radio :label="1"><span style="color: #00893d">OK</span></el-radio>
                  <el-radio :label="2"><span style="color: #ff0000">NG</span></el-radio>
                </el-radio-group>
                <el-input v-if="item.数据类型 === 2"
                  :disabled="item._resultConfirm === 1 || (item.项目类型 === 1 && item._resultConfirm === 0 && item.送检状态 === 0) || item.项目类型 === 2"
                  v-model="item.测量值" size="mini" class="inline-input" placeholder="请输入文本结果" />
                <el-radio-group v-if="item.数据类型 === 2 && item._resultConfirm !== 1 && item.项目类型 !== 3"
                  :disabled="item._resultConfirm === 1 || (item.项目类型 === 1 && item._resultConfirm === 0 && item.送检状态 === 0) || item.项目类型 === 2"
                  v-model="item.是否合格2" @change="recordValueChange(item)" style="margin-left: 10px;">
                  <el-radio :label="1"><span style="color: #00893d">OK</span></el-radio>
                  <el-radio :label="2"><span style="color: #ff0000">NG</span></el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="检测人" style="display: inline;margin-bottom: 0px;">
                <el-input
                  :disabled="item._resultConfirm === 1 || (item.项目类型 === 1 && item._resultConfirm === 0 && item.送检状态 === 0) || item.项目类型 === 2"
                  v-model="item.检测人" size="mini" style="width: 200px" placeholder="请输入检测人" />
                <i class="el-icon-user-solid" style="color: #0028aa" title="点击获取当前登录人" @click="getPeopleName(item)" />
              </el-form-item>
              <el-form-item v-if="item.项目类型 === 1" label="送检时间" style="display: inline;margin-bottom: 0px;">
                {{ item.送检时间 }}
              </el-form-item>
              <el-form-item label="完成时间" style="display: inline;margin-bottom: 0px;">
                <span>{{ item.检测时间 }}</span>
                <el-tag v-if="item.数据类型 === 1 && parseInt(item.是否合格) === 1" type="success" size="small" style="margin-left: 8px;">OK</el-tag>
                <el-tag v-if="item.数据类型 === 1 && parseInt(item.是否合格) === 2" type="warning" size="small" style="margin-left: 8px;">NG</el-tag>
                <el-tag v-if="item.数据类型 === 0 && item._resultConfirm === 1 && parseInt(item.是否合格) === 1" type="success" size="small" style="margin-left: 8px;">OK</el-tag>
                <el-tag v-if="item.数据类型 === 0 && item._resultConfirm === 1 && parseInt(item.是否合格) === 2" type="warning" size="small" style="margin-left: 8px;">NG</el-tag>
                <el-tag v-if="item.数据类型 === 2 && item._resultConfirm === 1 && parseInt(item.是否合格) === 1" type="success" size="small" style="margin-left: 8px;">OK</el-tag>
                <el-tag v-if="item.数据类型 === 2 && item._resultConfirm === 1 && parseInt(item.是否合格) === 2" type="warning" size="small" style="margin-left: 8px;">NG</el-tag>
                <i v-if="item._resultConfirm === 1" class="el-icon-refresh-left reset-single-icon" title="单项重置" @click="resetSingleItem(item)"></i>
              </el-form-item>
            </el-form>
            <div v-if="item.项目类型 === 0" class="taskItem-one">
              <div v-if="item._resultConfirm === 0" style="text-align: center;margin: 0 auto"><el-button type="primary"
                  size="mini" @click="submitCheckResult(item)">结果确认</el-button></div>
            </div>
            <div v-if="item.项目类型 === 3" class="taskItem-one">
              <div v-if="item._resultConfirm === 0" style="text-align: center;margin: 0 auto"><el-button type="primary"
                  size="mini" @click="submitCheckResult(item)">结果确认</el-button></div>
            </div>
            <div v-if="item.项目类型 === 1" class="taskItem-one">
              <div v-if="item._resultConfirm === 0 && item.送检状态 === 0" style="text-align: center;margin: 0 auto"><el-button
                  type="warning" size="mini" @click="submitGoCheck(item)">样品送检</el-button></div>
              <div v-if="item._resultConfirm === 0 && item.送检状态 === 1" style="text-align: center;margin: 0 auto"><el-button
                  type="warning" size="mini" @click="submitCheckResult(item)">结果确认</el-button></div>
            </div>
          </div>
        </div>
      </div>
    </el-card>
    <el-dialog :visible.sync="dialogFormVisible_CreateTask" title="创建首件任务" center style="min-height: 230px;"
      width="400px">
      <el-form ref="form_task" :model="form_task" :rules="rules_task" label-position="right" label-width="110px">
        <el-form-item label="工位号" prop="工位号" style="display: inline">
          <el-select v-model="form_task.工位号" disabled size="small" style="width: 200px" @change="getTableData">
            <el-option v-for="item in stationNumber" :key="item.value" :label="item.label" :value="item.value"
              size="mini" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品型号" prop="产品代码" style="display: inline">
          <el-select v-model="form_task.产品代码" size="small" placeholder="请选择产品型号" style="width: 200px">
            <el-option v-for="item in productTypes" :key="item.value" :label="item.label" :value="item.value"
              size="mini" />
          </el-select>
        </el-form-item>
        <el-form-item label="当前班次" prop="当前班次" style="display: inline">
          <el-input v-model="form_task.班次" readonly class="myReadOnly-input" size="small" style="width: 200px" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="callOff_task('form_task')">取消</el-button>
        <el-button type="primary" size="small" @click="submitAdd_task('form_task')">确定</el-button>
      </div>
    </el-dialog>
    <!-- 重置首件数据对话框 -->
    <el-dialog :visible.sync="dialogFormVisible_Reset" title="重置首件数据" center width="400px">
      <el-form ref="form_reset" :model="form_reset" :rules="rules_reset" label-position="right" label-width="110px">
        <el-form-item label="工位号" style="display: inline">
          <el-input v-model="stationNumberValue" disabled size="small" style="width: 200px" />
        </el-form-item>
        <el-form-item label="产品型号" prop="产品代码" style="display: inline">
          <el-select v-model="form_reset.产品代码" size="small" placeholder="请选择要重置的产品型号" style="width: 200px">
            <el-option v-for="item in productTypes" :key="item.value" :label="item.label" :value="item.value"
              size="mini" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible_Reset = false">取消</el-button>
        <el-button type="danger" size="small" @click="confirmResetFirstPart">确认重置</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { mapGetters } from 'vuex'
import { Mqtt } from '@/utils/mqtt'

export default {
  data() {
    return {
      haveTask: false,
      dialogFormVisible_CreateTask: false,
      dialogFormVisible_Reset: false,
      form_task: {
        工位号: '',
        班次: '',
        产品代码: null
      },
      rules_task: {
        产品代码: [{ required: true, message: '请选择产品型号', trigger: 'change' }]
      },
      form_reset: {
        产品代码: null
      },
      rules_reset: {
        产品代码: [{ required: true, message: '请选择要重置的产品型号', trigger: 'change' }]
      },
      currentProductType: '',
      productTypes: [],
      shiftNumber: '',
      stationNumberValue: '',
      stationNumber: [],
      loading: false,
      tableData: [],
      // scales
      scale1Value: '--',
      scale2Value: '--',
      scalesTopics: [],
      mqtt: null
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'id'
    ]),
    totalItems() {
      return this.tableData.length
    },
    completedItems() {
      return this.tableData.filter(item => item._resultConfirm === 1).length
    }
  },
  created() {
    this.getStationClasses()
    this.getStationNumber()
    this.getProductTypes()
    this.initMqtt()
    this.startShiftPolling()
  },
  beforeDestroy() {
    if (this.shiftTimer) {
      clearInterval(this.shiftTimer)
      this.shiftTimer = null
    }
  },
  methods: {
    getTitleClass(item) {
      const resultConfirm = parseInt(item.结果确认) || 0
      const isQualified = parseInt(item.是否合格) || 0
      const itemType = parseInt(item.项目类型) || 0

      if (resultConfirm === 1 && isQualified === 1) return 'title-ok'
      if (resultConfirm === 1 && isQualified === 2) return 'title-ng'
      if (itemType === 2) return 'title-device'
      if (itemType === 3) return 'title-photo'
      return 'title-pending'
    },
    getTaskItemClass(item) {
      const resultConfirm = parseInt(item.结果确认) || 0
      const isQualified = parseInt(item.是否合格) || 0
      if (resultConfirm === 1 && isQualified === 2) {
        // 已确认且不合格：整体卡片背景淡粉色
        return 'taskItem-ng'
      }
      return ''
    },
    initMqtt() {
      try {
        const cfg = {
          host: window.g.mqttIP,
          port: window.g.mqttPortNumber,
          endpoint: '/mqtt',
          reconnectPeriod: 4000,
          clean: true,
          clientId: 'FirstPartRecord-' + Math.random().toString(16).slice(2)
        }
        const m = new Mqtt(cfg)
        m.createConnection()
        this.mqtt = m
        this.scalesTopics = Array.isArray(window.g.ScalesTopic) ? window.g.ScalesTopic : []
        if (this.mqtt && this.mqtt.client && this.mqtt.client.on) {
          this.mqtt.client.on('connect', () => {
            this.subscribeScales()
          })
          this.mqtt.client.on('message', (topic, payload) => {
            const text = payload ? payload.toString() : ''
            if (this.scalesTopics[0] && topic === this.scalesTopics[0]) {
              this.scale1Value = text
            } else if (this.scalesTopics[1] && topic === this.scalesTopics[1]) {
              this.scale2Value = text
            }
          })
        }
      } catch (e) {
        console.error('initMqtt error', e)
      }
    },
    resetFirstPart() {
      if (!this.stationNumberValue) {
        this.$message.warning('请选择工位号！')
        return
      }
      this.$confirm('即将重置当前首件数据，是否继续？', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const param = []
        param.push(['工位号', this.stationNumberValue])
        param.push(['产品代码', this.form_reset.产品代码])
        const Data = this.CreateData('12', '电子看板_质量数据_首件数据_MOBY_增加', param)
        this.ExecDatabase(Data).then(response => {
          this.$message.success('重置首件数据成功！')
          this.getTableData()
        }).catch(err => {
          this.$message.error('重置首件数据失败，请稍后重试！')
          console.error('resetFirstPart error', err)
        })
      }).catch(() => { })
    },
    showResetDialog() {
      if (!this.stationNumberValue) {
        this.$message.warning('请选择工位号！')
        return
      }
      this.form_reset.产品代码 = null
      this.dialogFormVisible_Reset = true
    },
    confirmResetFirstPart() {
      this.$refs['form_reset'].validate(valid => {
        if (valid) {
          this.$confirm('即将重置当前首件数据，是否继续？', '提示', {
            confirmButtonText: '继续',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const param = []
            param.push(['工位号', this.stationNumberValue])
            param.push(['产品代码', this.form_reset.产品代码])
            const Data = this.CreateData('12', '电子看板_质量数据_首件数据_MOBY_增加', param)
            this.ExecDatabase(Data).then(response => {
              this.$message.success('重置首件数据成功！')
              this.dialogFormVisible_Reset = false
              this.getTableData()
            }).catch(err => {
              this.$message.error('重置首件数据失败，请稍后重试！')
              console.error('confirmResetFirstPart error', err)
            })
          }).catch(() => { })
        }
      })
    },
    startShiftPolling() {
      try {
        if (this.shiftTimer) clearInterval(this.shiftTimer)
        this.shiftTimer = setInterval(this.checkShiftUpdate, 5 * 60 * 1000)
      } catch (e) { console.error('startShiftPolling error', e) }
    },
    checkShiftUpdate() {
      try {
        const param = []
        const Data = this.CreateData('11', 'MES_操作着_生产班次_查询', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data && response.data.length > 0) {
            const cur = response.data[0]['班次描述']
            if (cur && cur !== this.shiftNumber) {
              this.shiftNumber = cur
              if (this.stationNumberValue) this.getTableData()
            }
          }
        }).catch(() => { })
      } catch (e) { console.error('checkShiftUpdate error', e) }
    },
    subscribeScales() {
      try {
        if (!this.mqtt || !this.mqtt.client || !this.mqtt.client.connected) return
        if (this.scalesTopics[0]) this.mqtt.doSubscribe({ topic: this.scalesTopics[0], qos: 0 })
        if (this.scalesTopics[1]) this.mqtt.doSubscribe({ topic: this.scalesTopics[1], qos: 0 })
      } catch (e) { console.error('subscribeScales error', e) }
    },
    fillByScale(item, which) {
      const raw = which === 1 ? this.scale1Value : this.scale2Value
      const val = parseFloat(raw)
      if (isNaN(val)) {
        this.$message && this.$message.warning('当前秤无有效数据')
        return
      }
      this.$set(item, '测量值', val)
      this.judgeResult(item)
    },
    submitAllFirstPart() {
      // 前置校验：按必填规则检查
      const pendingRequired = []
      const ngItems = []

      for (let i = 0; i < this.tableData.length; i++) {
        const item = this.tableData[i]
        const isRequired = item._isRequired
        const hasValue = item.测量值 !== '' && item.测量值 !== null && item.测量值 !== undefined
        const confirmed = item._resultConfirm === 1
        const isNG = parseInt(item.是否合格) === 2

        // 1) 必填项：必须有值且已确认
        if (isRequired) {
          if (!hasValue || !confirmed) {
            pendingRequired.push(item.检测项目)
          }
        }

        // 2) 记录已完成但NG的项目（用于二次确认提示）
        if (hasValue && confirmed && isNG) {
          ngItems.push(item.检测项目)
        }
      }

      if (this.tableData.length === 0) {
        this.$message.warning('当前工位当前班次无首件数据，请创建任务！')
        return
      }

      if (pendingRequired.length > 0) {
        this.$message.warning(`存在必填项目未完成或未确认：${pendingRequired.slice(0, 5).join('、')}${pendingRequired.length > 5 ? ' 等' : ''}`)
        return
      }

      // 组合确认文案：如果存在NG项，给出二次确认提示
      let confirmMessage = '已检查所有必填项目均已填写并确认，是否提交首件数据？'
      if (ngItems.length > 0) {
        confirmMessage = `存在以下项目检测结果为不合格：\n${ngItems.slice(0, 10).join('、')}${ngItems.length > 10 ? ' 等' : ''}\n\n是否仍然提交首件数据？`
      }

      this.$confirm(confirmMessage, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: ngItems.length > 0 ? 'warning' : 'info'
      }).then(() => {
        const apiUrl = window.g.API_MES_Controller_URL + '/FirstProductUpLoad'
        const payload = {
          MsgId: this.generateUUID(),
          OpName: this.stationNumberValue
        }
        axios.post(apiUrl, payload, { headers: { 'Content-Type': 'application/json' } })
          .then(res => {
            const code = res && res.data ? res.data.Code : null
            const message = res && res.data ? (res.data.Message || '') : ''
            if (code === '200') {
              this.$alert(message, '提示', { type: 'success' })
              this.getTableData()
            } else {
              this.$alert(`${message || '未知错误'}`, '错误', { type: 'error' })
            }
          })
          .catch(err => {
            this.$alert(`首件数据上传异常：${err && err.message ? err.message : err}`, '错误', { type: 'error' })
          })
      }).catch(() => { })
    },
    generateUUID() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        const r = Math.random() * 16 | 0
        const v = c === 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
      })
    },
    getStationNumber() {
      this.stationNumber = []
      var param = []
      var Data = this.CreateData('11', '电子看板_质量数据_首件数据_工位表_查询', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.stationNumber.push({
            label: `【${response.data[i].工位号}】${response.data[i].工位名称}`,
            value: response.data[i].工位号
          })
        }
        // 自动选中第一个工位并加载数据，避免空内容
        if (this.stationNumber.length > 0 && !this.stationNumberValue) {
          this.stationNumberValue = this.stationNumber[0].value
          this.getTableData()
        }
      })
    },
    getProductTypes() {
      const param = []
      this.productTypes = []
      const Data = this.CreateData('11', 'CATL_基础_整机_产品代码_查询', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.productTypes.push({
            label: response.data[i]['产品名称'],
            value: response.data[i]['产品代码']
          })
        }
      })
    },
    getStationClasses() {
      const param = []
      const Data = this.CreateData('11', 'MES_操作着_生产班次_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) {
          this.shiftNumber = response.data[0]['班次描述']
        }
      })
    },
    getTableData() {
      // 记录滚动位置，减少刷新跳动
      if (typeof this._savedScrollTop !== 'number') {
        this._savedScrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0
      }
      if (this.stationNumberValue === '') {
        this.$message.warning('请选择工位号！')
        return
      }
      // 如果当前正在加载，同一时刻不重复触发，避免多次白屏
      if (this.loading) {
        return
      }
      this.loading = true
      var param = []
      param.push(['工位号', this.stationNumberValue])
      var Data = this.CreateData('11', '电子看板_质量数据_首件数据_MOBY_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) {
          // 轻量预处理，减少模板中的计算量
          const processed = response.data.map(item => {
            const resultConfirm = parseInt(item.结果确认) || 0
            const isQualified = parseInt(item.是否合格) || 0
            const itemType = parseInt(item.项目类型) || 0
            const dataType = parseInt(item.数据类型) || 0
            const isRequired = item.必填 === 1 || item.必填 === '1'

            // 标题样式
            let titleClass = 'title-pending'
            if (resultConfirm === 1 && isQualified === 1) titleClass = 'title-ok'
            else if (resultConfirm === 1 && isQualified === 2) titleClass = 'title-ng'
            else if (itemType === 2) titleClass = 'title-device'
            else if (itemType === 3) titleClass = 'title-photo'

            // 卡片背景样式（NG）
            const taskItemClass = (resultConfirm === 1 && isQualified === 2) ? 'taskItem-ng' : ''

            // 默认检测人为当前登录人（仅当后端未给值时）
            const defaultChecker = (item.检测人 && item.检测人 !== '') ? item.检测人 : this.name

            return {
              ...item,
              检测人: defaultChecker,
              _resultConfirm: resultConfirm,
              _isQualified: isQualified,
              _itemType: itemType,
              _dataType: dataType,
              _isRequired: isRequired,
              _titleClass: titleClass,
              _taskItemClass: taskItemClass
            }
          })
          // 分批渲染：先展示前40条，剩余的异步追加，减轻一次性渲染压力
          const firstBatchSize = 40
          this.tableData = processed.slice(0, firstBatchSize)
          if (processed.length > firstBatchSize) {
            this.$nextTick(() => {
              setTimeout(() => {
                this.tableData = processed
              }, 0)
            })
          }
          this.haveTask = false
          // 从第一行数据获取当前型号
          if (response.data.length > 0 && response.data[0].产品型号) {
            this.currentProductType = response.data[0].产品型号
          } else {
            this.currentProductType = ''
          }
        } else {
          this.tableData = []
          this.currentProductType = ''
          this.$message.error('该工位当前班次无首件数据，请创建任务！')
          this.haveTask = true
        }
        this.loading = false
        this.$nextTick(() => {
          try {
            if (typeof this._savedScrollTop === 'number') {
              window.scrollTo(0, this._savedScrollTop)
            }
          } catch (e) { }
          this._savedScrollTop = undefined
        })
      }).catch(error => {
        this.loading = false
        this.$message.error('数据加载失败，请稍后重试！')
        console.error('Error fetching interface data:', error)
      })
    },
    createTask() {
      this.form_task.工位号 = this.stationNumberValue
      this.form_task.班次 = this.shiftNumber
      this.dialogFormVisible_CreateTask = true
    },
    callOff_task(form) {
      this.dialogFormVisible_CreateTask = false
      try {
        const f = this.$refs[form]
        if (f && typeof f.resetFields === 'function') f.resetFields()
      } catch (e) {}
    },
    submitAdd_task(form) {
      const doCreate = () => {
        var param = []
        param.push(['工位号', this.form_task.工位号])
        param.push(['产品代码', this.form_task.产品代码])
        var Data = this.CreateData('12', '电子看板_质量数据_首件数据_MOBY_增加', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data && response.data[0] && response.data[0].result === '1') {
            this.$message.success('首件任务创建成功！')
            this.dialogFormVisible_CreateTask = false
            this.getTableData()
          } else {
            this.$message.error('首件任务创建失败，请稍后重试！')
          }
        }).catch(error => {
          console.error('Error creating task:', error)
          this.$message.error('首件任务创建失败，请稍后重试！')
        })
      }
      try {
        const f = this.$refs[form]
        if (f && typeof f.validate === 'function') {
          f.validate(valid => { if (valid) doCreate() })
        } else {
          doCreate()
        }
      } catch (e) { doCreate() }
    },
    getPeopleName(row) {
      console.log(row)
      if (row._resultConfirm === 1) {
        this.$message.warning('当前检测项已完成，无法修改检测人！')
      } else if (row.项目类型 === 1 && row._resultConfirm === 0 && row.送检状态 === 0) {
        this.$message.warning('当前检测项未送检，无法修改检测人！')
      } else {
        row.检测人 = this.name
      }
    },
    judgeResult(row) {
      if (row.数据类型 === 1 && row.测量值 !== '') {
        if (parseFloat(row.测量值) < parseFloat(row.下限值) || parseFloat(row.测量值) > parseFloat(row.上限值)) {
          row.是否合格 = 2 // NG
        } else {
          row.是否合格 = 1 // OK
        }
      }
    },
    recordValueChange(row) {
      console.log(row)
      if (row.是否合格2 === 1) {
        row.是否合格 = 1
        // 定性数据：测量值入库改为 1
        if (row.数据类型 === 0) {
          row.测量值 = 1
        } else {
          row.测量值 = 'OK'
        }
      }
      if (row.是否合格2 === 2) {
        // 定性数据：测量值入库改为 0
        if (row.数据类型 === 0) {
          row.测量值 = 0
        } else {
          row.测量值 = 'NG'
        }
        row.是否合格 = 2
      }
    },
    submitCheckResult(row) {
      if (row.检测人 === '' || row.检测人 == null) {
        this.$message.warning('请先填写检测人！')
        return
      }
      if (row.测量值 === '' || row.测量值 == null) {
        this.$message.warning('请先填写测量值！')
        return
      }
      // 拍照上传类型不要求选择OK/NG，默认按合格处理
      if (row.项目类型 === 3 && (row.是否合格 === '' || row.是否合格 === null || row.是否合格 === undefined)) {
        row.是否合格 = 1
      }
      if (row.是否合格 === '' || row.是否合格 === null || row.是否合格 === undefined) {
        this.$message.warning('请先填写测量值！')
        return
      }
      // 记录滚动位置，提交后恢复
      this._savedScrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0
      var param = []
      param.push(['ID', row.ID])
      param.push(['测量值', row.测量值])
      param.push(['是否合格', row.是否合格])
      param.push(['检测人', row.检测人])
      var Data = this.CreateData('12', '电子看板_质量数据_首件数据_MOBY_结果确认', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data[0].result === '1') {
          this.$message.success('检查项数据提交成功！')
          this.getTableData()
        } else {
          this.$message.error('检查项数据提交失败，请稍后重试！')
        }
      }).catch(error => {
        console.error('Error creating task:', error)
        this.$message.error('检查项数据提交失败，请稍后重试！')
      })
    },
    submitGoCheck(row) {
      var param = []
      param.push(['ID', row.ID])
      var Data = this.CreateData('12', '电子看板_质量数据_首件数据_MOBY_样品送检', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data[0].result === '1') {
          this.$message.success('检查项送检提交成功！')
          this.getTableData()
        } else {
          this.$message.error('检查项送检提交失败，请稍后重试！')
        }
      }).catch(error => {
        console.error('Error creating task:', error)
        this.$message.error('检查项送检提交失败，请稍后重试！')
      })
    },
    resetSingleItem(row) {
      this.$confirm(`确定要重置【${row.检测项目}】吗？重置后需重新填写检测结果。`, '单项重置', {
        confirmButtonText: '确定重置',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this._savedScrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0
        var param = []
        param.push(['ID', row.ID])
        var Data = this.CreateData('12', '电子看板_质量数据_首件数据_MOBY_单项重置', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === '1') {
            this.$message.success('单项重置成功！')
            this.getTableData()
          } else {
            this.$message.error('单项重置失败，请稍后重试！')
          }
        }).catch(error => {
          console.error('resetSingleItem error:', error)
          this.$message.error('单项重置失败，请稍后重试！')
        })
      }).catch(() => { })
    }
  }
}
</script>

<style scoped>
.topCard {
  margin: 5px;
}

.topDiv {
  margin-bottom: 0px;
}

.progress-box {
  float: right;
  display: flex;
  align-items: center;
  margin-right: 12px;
}

.progress-item {
  display: flex;
  align-items: center;
  background: #f8f9fb;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 6px 10px;
  min-width: 150px;
  justify-content: space-between;
}

.progress-item .progress-title {
  display: inline-block;
  font-size: 12px;
  color: #909399;
  background: #eef1f6;
  border-radius: 4px;
  padding: 2px 6px;
}

.progress-item .progress-value {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  letter-spacing: 0.5px;
}

.scales-box {
  float: right;
  display: flex;
  align-items: center;
  gap: 12px;
}

.scale-item {
  display: flex;
  align-items: center;
  background: #f8f9fb;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 6px 10px;
  min-width: 150px;
  justify-content: space-between;
}

.scale-item .scale-title {
  display: inline-block;
  font-size: 12px;
  color: #909399;
  background: #eef1f6;
  border-radius: 4px;
  padding: 2px 6px;
}

.scale-item .scale-value {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  letter-spacing: 0.5px;
}

.scale1 .scale-title {
  background: #ecf5ff;
  color: #409eff;
}

.scale2 .scale-title {
  background: #f0f9eb;
  color: #67c23a;
}

.taskItem {
  display: flex;
  flex-direction: column;
  width: 350px;
  height: 310px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin: 5px 5px 0 0;
}

.taskItem-title {
  height: 25px;
  text-align: center;
  background-color: #eaeaea;
  font-size: 16px;
  line-height: 25px;
}

.title-pending{
  background-color: #f0f3f5 !important;
  color: #909399 !important;
}

.title-ok{
  background-color: #f0f9eb !important;
  color: #67c23a !important;
}

.title-ng{
  background-color: #fef0f0 !important;
  color: #f56c6c !important;
}

.title-device{
  background-color: #fdf6ec !important;
  color: #e6a23c !important;
}

.title-photo{
  background-color: #f0f9ff !important;
  color: #409eff !important;
}

.taskItem-one {
  height: 25px;
  font-size: 14px;
  padding: 0 5px;
  margin: 5px 0;
  display: flex;
  align-items: center;
}

.taskItem-one span {
  width: 80px;
}

.taskItem-one i {
  margin-left: 5px;
  color: #409eff;
}

.tag-row>.el-tag {
  margin-right: 6px;
}

.range-row {
  display: flex;
  align-items: center;
}

.range-text {
  margin-left: 6px;
  color: #606266;
}

.inline-input {
  width: 220px;
}

.taskItem {
  box-sizing: border-box;
}

.taskItem .el-form-item {
  margin-bottom: 8px;
}

.cards-wrap {
  width: 100%;
  margin-top: 10px;
}

/* 新增NG背景样式 */
.taskItem-ng {
  background-color: #fff5f7; /* 淡粉色背景 */
}

/* 单项重置图标样式 - 不显眼 */
.reset-single-icon {
  margin-left: 20px;
  font-size: 12px;
  /* color: #c0c4cc; */
  cursor: pointer;
  opacity: 0.6;
  transition: all 0.2s;
}

.reset-single-icon:hover {
  color: #909399;
  opacity: 1;
}
</style>
