<template>
  <div class="inspection-terminal">
    <el-card class="station-card" shadow="never">
      <div class="station-info">
        <div class="station-name">{{ stationName || '-' }}</div>
        <div class="station-extra">
          <span>工位号：{{ stationNumber || '-' }}</span>
          <span>当前操作员：{{ operatorName || '未登录' }}</span>
          <span>工号：{{ operatorCode || '-' }}</span>
        </div>
      </div>
      <div class="station-actions">
        <el-button type="primary" icon="el-icon-refresh" @click="refreshAll">刷新数据</el-button>
      </div>
    </el-card>

    <el-card class="tab-card" shadow="never">
      <el-tabs v-model="activeCycle" @tab-click="handleCycleChange">
        <el-tab-pane v-for="tab in cycleTabs" :key="tab.value" :label="`${tab.label} (${tab.count})`" :name="tab.value">
          <div class="tab-caption">
            <span>有效点检任务</span>
            <small v-if="tab.desc">{{ tab.desc }}</small>
          </div>
          <el-table
            v-loading="taskLoading"
            :data="taskList"
            border
            height="520"
            empty-text="当前周期暂无需要点检的项目">
            <el-table-column type="index" width="60" label="#"/>
            <el-table-column prop="点检项目" label="点检项目/内容" min-width="220" show-overflow-tooltip>
              <template slot-scope="scope">
                <div class="cell-main">{{ scope.row['点检项目'] || '-' }}</div>
                <div class="cell-sub">{{ scope.row['点检内容'] || '' }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="资产名称" label="资产信息" min-width="180">
              <template slot-scope="scope">
                <div class="cell-main">{{ scope.row['资产名称'] || '-' }}</div>
                <div class="cell-sub">{{ scope.row['资产编号'] || '' }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="标准要求" label="标准要求" min-width="160" show-overflow-tooltip />
            <el-table-column prop="截止时间" label="截止时间" min-width="150">
              <template slot-scope="scope">
                <span :class="{'text-danger': isExpired(scope.row)}">
                  {{ formatDate(scope.row['截止时间']) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="120">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row)" disable-transitions>
                  {{ getStatusText(scope.row) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="140" fixed="right">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  :disabled="disableSubmit(scope.row)"
                  @click="openSubmitDialog(scope.row)">点检</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      width="520px"
      :close-on-click-modal="false">
      <el-form :model="formModel" :rules="formRules" ref="resultForm" label-width="110px">
        <el-form-item label="点检值" prop="checkValue">
          <el-input v-model.trim="formModel.checkValue" placeholder="请输入实际点检值" clearable />
        </el-form-item>
        <el-form-item label="点检结果" prop="checkResult">
          <el-select v-model="formModel.checkResult" placeholder="选择结果" @change="handleResultChange">
            <el-option v-for="item in resultOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否异常">
          <el-tag :type="formModel.abnormal === '1' ? 'danger' : 'success'">
            {{ formModel.abnormal === '1' ? '异常' : '正常' }}
          </el-tag>
        </el-form-item>
        <el-form-item label="异常描述" prop="exceptionDesc" v-if="formModel.abnormal === '1'">
          <el-input
            v-model.trim="formModel.exceptionDesc"
            type="textarea"
            :rows="3"
            placeholder="请描述异常情况"/>
        </el-form-item>
        <el-form-item label="点检人">
          <el-input v-model="operatorName" disabled />
        </el-form-item>
        <el-form-item label="点检时间" prop="checkTime">
          <el-date-picker
            v-model="formModel.checkTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择点检时间"
            style="width: 100%" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitResult">提交点检结果</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      stationNumber: this.$store.state.station.stationNumber,
      stationName: this.$store.state.station.stationName,
      operatorName: this.$store.state.station.stationUserName,
      operatorCode: this.$store.state.station.stationUserCount,
      activeCycle: 'DAY',
      cycleTabs: [
        { label: '日常', value: 'DAY', count: 0, desc: '每日必检项' },
        { label: '周保养', value: 'WEEK', count: 0, desc: '七天周期' },
        { label: '月保养', value: 'MONTH', count: 0, desc: '三十天周期' },
        { label: '季保养', value: 'QUARTER', count: 0, desc: '九十天周期' },
        { label: '年保养', value: 'YEAR', count: 0, desc: '年度巡检' },
        { label: '单次', value: 'SINGLE', count: 0, desc: '一次性任务' }
      ],
      taskList: [],
      taskLoading: false,
      dialogVisible: false,
      dialogTitle: '',
      submitLoading: false,
      currentRow: {},
      formModel: {
        planId: '',
        detailId: '',
        checkValue: '',
        checkResult: '8ad0c970-ac18-46b4-bda6-643bb26d776e',
        abnormal: '0',
        exceptionDesc: '',
        checkTime: ''
      },
      formRules: {
        checkValue: [{ required: true, message: '请输入点检值', trigger: 'blur' }],
        checkResult: [{ required: true, message: '请选择点检结果', trigger: 'change' }],
        checkTime: [{ required: true, message: '请选择点检时间', trigger: 'change' }],
        exceptionDesc: [{ required: true, message: '请填写异常描述', trigger: 'blur' }]
      },
      resultOptions: [
        { label: '正常', value: '8ad0c970-ac18-46b4-bda6-643bb26d776e', abnormal: '0' },
        { label: '异常', value: '7f4e18d0-ca26-e64e-ef87-29d5917166c2', abnormal: '1' },
        { label: '待确定', value: '938e0b05-febc-5d44-d8e3977a12bf', abnormal: '1' }
      ]
    }
  },
  created() {
    this.refreshAll()
  },
  methods: {
    refreshAll() {
      this.fetchCounts()
      this.fetchTaskList()
    },
    handleCycleChange() {
      this.fetchTaskList()
    },
    fetchCounts() {
      const param = []
      param[0] = ['工位号', this.stationName || this.stationNumber || '']
      const Data = this.CreateData('11', 'MES_点检计划_工位任务统计', param)
      this.ExecDatabase(Data).then(res => {
        const list = res.data || []
        this.cycleTabs = this.cycleTabs.map(tab => {
          const target = list.find(item => item['周期类型'] === tab.value)
          return { ...tab, count: target ? Number(target['数量'] || 0) : 0 }
        })
      })
    },
    fetchTaskList() {
      this.taskLoading = true
      const param = []
      param[0] = ['工位号', this.stationName || this.stationNumber || '']
      param[1] = ['周期类型', this.activeCycle]
      param[2] = ['包含已完成', 0, 'bit']
      const Data = this.CreateData('11', 'MES_点检计划_工位任务查询', param)
      this.ExecDatabase(Data).then(res => {
        this.taskList = res.data || []
      }).finally(() => {
        this.taskLoading = false
      })
    },
    openSubmitDialog(row) {
      if (!this.operatorCode) {
        this.$message.error('未检测到当前操作员工号，无法提交点检结果。')
        return
      }
      this.currentRow = row
      this.dialogTitle = `${row['点检项目'] || ''} - 点检录入`
      this.formModel = {
        planId: row['点检计划ID'],
        detailId: row['点检明细ID'],
        checkValue: '',
        checkResult: this.resultOptions[0].value,
        abnormal: '0',
        exceptionDesc: '',
        checkTime: this.getNow()
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.resultForm && this.$refs.resultForm.clearValidate()
      })
    },
    handleResultChange(val) {
      const target = this.resultOptions.find(item => item.value === val)
      if (target) {
        this.formModel.abnormal = target.abnormal
        if (target.abnormal === '0') {
          this.formModel.exceptionDesc = ''
        }
      }
    },
    submitResult() {
      if (!this.operatorCode) {
        this.$message.error('请先登录操作员账号')
        return
      }
      this.$refs.resultForm.validate(valid => {
        if (!valid) return
        this.submitLoading = true
        const param = []
        param[0] = ['点检结果ID', '', 'nvarchar']
        param[1] = ['点检计划ID', this.formModel.planId]
        param[2] = ['点检计划明细ID', this.formModel.detailId]
        param[3] = ['工位号', this.stationNumber || this.stationName || '']
        param[4] = ['工位名称', this.stationName || '']
        param[5] = ['点检值', this.formModel.checkValue]
        param[6] = ['点检结果', this.formModel.checkResult]
        param[7] = ['是否异常', this.formModel.abnormal]
        param[8] = ['点检人编号', this.operatorCode || '']
        param[9] = ['点检人名称', this.operatorName || '']
        param[10] = ['点检时间', this.formModel.checkTime]
        param[11] = ['异常描述', this.formModel.exceptionDesc || '']
        const Data = this.CreateData('12', 'MES_点检结果_保存', param)
        this.ExecDatabase(Data).then(res => {
          const result = (res.data && res.data[0]) ? res.data[0] : {}
          if (result.result === '1') {
            this.$message.success('点检结果已保存')
            this.dialogVisible = false
            this.fetchTaskList()
            this.fetchCounts()
            // TODO: 调用后台接口上传工厂MES
          } else {
            this.$message.error(result.msg || '保存失败')
          }
        }).finally(() => {
          this.submitLoading = false
        })
      })
    },
    disableSubmit(row) {
      return this.isExpired(row) || (row['状态'] || '').toLowerCase() === 'completed'
    },
    isExpired(row) {
      return Number(row['是否过期'] || 0) === 1
    },
    formatDate(value) {
      if (!value) return '-'
      const str = value.toString().replace('T', ' ')
      return str.length > 19 ? str.substr(0, 19) : str
    },
    getStatusText(row) {
      if (this.isExpired(row)) return '已过期'
      const status = (row['状态'] || '').toLowerCase()
      if (status === 'completed') return '已完成'
      return '待点检'
    },
    getStatusType(row) {
      if (this.isExpired(row)) return 'danger'
      const status = (row['状态'] || '').toLowerCase()
      if (status === 'completed') return 'success'
      return 'warning'
    },
    getNow() {
      const now = new Date()
      const pad = n => n.toString().padStart(2, '0')
      return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`
    }
  }
}
</script>

<style lang="scss" scoped>
.inspection-terminal {
  padding: 10px;
  .station-card {
    margin-bottom: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .station-info {
    .station-name {
      font-size: 24px;
      font-weight: 600;
      margin-bottom: 6px;
    }
    .station-extra {
      color: #909399;
      span {
        margin-right: 18px;
      }
    }
  }
  .tab-card {
    .tab-caption {
      margin-bottom: 10px;
      font-size: 16px;
      font-weight: 600;
      small {
        font-size: 12px;
        color: #909399;
        margin-left: 6px;
        font-weight: 400;
      }
    }
  }
  .cell-main {
    font-size: 14px;
    color: #303133;
  }
  .cell-sub {
    font-size: 12px;
    color: #909399;
  }
  .text-danger {
    color: #f56c6c;
  }
}
</style>

