<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备编号" prop="motherboardCode">
        <el-input
          v-model="queryParams.motherboardCode"
          placeholder="请输入绑定的设备编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="托盘编号" prop="trayCode">
        <el-input
          v-model="queryParams.trayCode"
          placeholder="请输入托盘编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标检单号" prop="productStandardInspectionNumber">
        <el-input
          v-model="queryParams.productStandardInspectionNumber"
          placeholder="请输入标检单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标检结果" prop="standardInspectResult">
        <el-select v-model="queryParams.standardInspectResult" placeholder="请选择">
          <el-option
            v-for="item in standardInspectResultOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload"
          size="mini"
          :loading="exportLoading"
          @click="handleReUpload"
        >重新上传</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="historyList">
      <el-table-column label="托盘编号" align="center" prop="trayCode" />
      <el-table-column label="标检单号" align="center" prop="productStandardInspectionNumber" width="100px" />
      <el-table-column label="绑定层编号" align="center" prop="storeyCode" width="100px" />
      <el-table-column label="设备编号" align="center" prop="motherboardCode" />
      <el-table-column label="行" align="center" prop="row" />
      <el-table-column label="列" align="center" prop="col" />
      <el-table-column label="第几个" align="center" prop="index" />
      <el-table-column label="编号" align="center" prop="number" />
      <el-table-column label="绑定时间" align="center" prop="bindingTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.bindingTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标检结果" align="center" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.standardInspectResult === '1'" class="write-success">合格</span>
          <span v-else class="write-failed">不合格</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="deviceStatus" >
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.deviceStatus === '0'">预热</el-tag>
          <el-tag type="success" v-if="scope.row.deviceStatus === '1'">正常</el-tag>
          <el-tag type="warning" v-if="scope.row.deviceStatus === '3'">传感器故障</el-tag>
          <el-tag type="danger" v-if="scope.row.deviceStatus === '4'">报警</el-tag>
          <el-tag type="danger" v-if="scope.row.deviceStatus === '5'">通讯故障</el-tag>
          <el-tag type="danger" v-if="scope.row.deviceStatus === '-9999'">通讯异常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="写时间状态" align="center" prop="writeTimeStatus" width="100px" >
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.writeTimeStatus === '0'">失败</el-tag>
          <el-tag type="success" v-if="scope.row.writeTimeStatus === '1'">成功</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="运行时间状态" align="center" prop="runTimeStatus" width="110px">
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.runTimeStatus === '0'">异常</el-tag>
          <el-tag type="success" v-if="scope.row.runTimeStatus === '1'">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="浓度值" align="center" prop="concentration" />
      <el-table-column label="实时AD值" align="center" prop="realTimeAd" />
      <el-table-column label="实时AD状态" align="center" prop="realTimeStatus" width="110px" >
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.realTimeStatus === '0'">异常</el-tag>
          <el-tag type="success" v-if="scope.row.realTimeStatus === '1'">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="标定浓度值" align="center" width="150" prop="calibrationConcentration"></el-table-column>
      <el-table-column label="标定状态" align="center" width="120">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.calibrationConcentrationStatus !== null && scope.row.calibrationConcentrationStatus === '4'">正常</el-tag>
          <el-tag type="info" v-if="scope.row.calibrationConcentrationStatus !== null && scope.row.calibrationConcentrationStatus !== '4' ">异常</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="写自检状态" align="center" width="150">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.writeSelfCheckStatus === 1">成功</el-tag>
          <el-tag type="info" v-if="scope.row.writeSelfCheckStatus === 0">失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="继电器状态" align="center" width="150">
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.relayStatus === 0">初始</el-tag>
          <el-tag type="success" v-if="scope.row.relayStatus === 1">动作</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="脉冲状态" align="center" width="120">
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.pulseStatus === 0">初始</el-tag>
          <el-tag type="success" v-if="scope.row.pulseStatus === 1">动作</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="模块状态" align="center" width="120">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.moduleStatus === 1">正常</el-tag>
          <el-tag type="info"  v-if="scope.row.moduleStatus === 0">异常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="SIM卡状态" align="center" width="150">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.simCardStatus === 1">正常</el-tag>
          <el-tag type="info"  v-if="scope.row.simCardStatus === 0">异常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="网络状态" align="center" width="120">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.networkStatus === 1">正常</el-tag>
          <el-tag type="info"  v-if="scope.row.networkStatus === 0">异常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="设置-年" align="center" prop="recordYear" />
      <el-table-column label="设置-月" align="center" prop="recordMonth" />
      <el-table-column label="设置-日" align="center" prop="recordDate" />
      <el-table-column label="设置-时" align="center" prop="recordHour" />
      <el-table-column label="设置-分" align="center" prop="recordMinute" />
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
  import { listFailure, exportFailure ,reUpload} from "@/api/palletDeviceBinding/palletDeviceUploadFailure";

export default {
  name: "History",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 未上传成功的历史数据列表格数据
      historyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        trayId: null,
        motherboardCode: null,
        trayCode: null,
        row: null,
        col: null,
        index: null,
        number: null,
        bindingTime: null,
        unbindingTime: null,
        createTime: null,
        deviceStatus: null,
        recordYear: null,
        recordMonth: null,
        recordDate: null,
        recordHour: null,
        recordMinute: null,
        writeTimeStatus: null,
        adjustmentZeroAd: null,
        zeroStatus: null,
        calibrationAd: null,
        calibrationStatus: null,
        concentration: null,
        runTimeStatus: null,
        realTimeAd: null,
        realTimeStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        trayId: [
          { required: true, message: "托盘id不能为空", trigger: "blur" }
        ],
      },

      standardInspectResultOptions: [{
        value: '1',
        label: '合格'
      }, {
        value: '0',
        label: '不合格'
      }],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取标定状态文本
    getCalibrationText(deviceStatus) {
      if (deviceStatus === '4') {
        return '正常'
      } else if (deviceStatus) {
        return '异常'
      }
    },
// 获取标定状态的el-tag类型
    getCalibrationTagType(deviceStatus) {
      if (deviceStatus === '4') {
        return 'success' // 正常 - 绿色
      } else if (deviceStatus) {
        return 'info' // 异常 - 红色
      }
    },
    /** 查询未上传成功的历史数据列列表 */
    getList() {
      this.loading = true;
      listFailure(this.queryParams).then(response => {
        this.historyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        trayId: null,
        motherboardCode: null,
        row: null,
        col: null,
        index: null,
        number: null,
        bindingTime: null,
        unbindingTime: null,
        createTime: null,
        deviceStatus: "0",
        recordYear: null,
        recordMonth: null,
        recordDate: null,
        recordHour: null,
        recordMinute: null,
        writeTimeStatus: "0",
        adjustmentZeroAd: null,
        zeroStatus: "0",
        calibrationAd: null,
        calibrationStatus: "0",
        concentration: null,
        runTimeStatus: "0",
        realTimeAd: null,
        realTimeStatus: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleReUpload() {
      this.$confirm('是否确认重新上传当前时间下设备编号不为空的所有数据?', '提示-成功后数据直接删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        reUpload().then(response => {
          // 确保 response 有正确的结构
          if (response && response.code === 200) {
            // 处理部分失败或完全失败的情况
            this.handleUploadResult(response);
          }
          this.getList(); // 重新加载数据
        })
      }).catch(() => {
      });
    },

// 单独处理上传结果的方法
    handleUploadResult(response) {
      if (!response) {
        this.$message.error('上传失败，服务器无响应');
        return;
      }

      // 检查是否有 data 字段
      if (response.data) {
        const data = response.data;

        if (data.successCount >= 0 && data.failedCount >= 0) {
          // 部分失败的情况
          if (data.failedCount > 0) {
            // 显示失败设备列表
            if (data.failedDeviceCodes && data.failedDeviceCodes.length > 0) {
              this.$alert(`失败设备：${data.failedDeviceCodes.join(', ')}`, '上传失败设备', {
                confirmButtonText: '确定',
                type: 'warning',
                callback: () => {
                  this.getList();
                }
              })
            }
          } else {
            this.$message.success('所有数据上传成功');
          }
        } else {
          // 没有统计信息，显示通用错误消息
          this.$message.error(response.msg || '上传失败');
        }
      } else {
        // 没有 data 字段，显示错误消息
        this.$message.error(response.msg || '上传失败');
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有未上传成功的历史数据列数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportFailure(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    }
  }
};
</script>

<style>

.write-success {
  color: #67c23a;
  font-weight: bold;
}

.write-failed {
  color: #f56c6c;
  font-weight: bold;
}
</style>
