<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备编号" prop="deviceCode">
        <el-input
          v-model="queryParams.deviceCode"
          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>
        <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="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <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" @selection-change="handleSelectionChange">
      <el-table-column label="托盘编号" align="center" prop="trayCode" />
      <el-table-column label="绑定层编号" align="center" prop="storeyCode" width="100px" />
      <el-table-column label="设备编号" align="center" prop="deviceCode" />
      <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" prop="unbindingTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.unbindingTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.status === '0'">预热</el-tag>
          <el-tag type="success" v-if="scope.row.status === '1'">正常</el-tag>
          <el-tag type="warning" v-if="scope.row.status === '3'">传感器故障</el-tag>
          <el-tag type="danger" v-if="scope.row.status === '4'">报警</el-tag>
          <el-tag type="danger" v-if="scope.row.status === '5'">通讯故障</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="realTimeAdStatus" width="110px" >
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.realTimeAdStatus === '0'">异常</el-tag>
          <el-tag type="success" v-if="scope.row.realTimeAdStatus === '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 === 1">初始</el-tag>
          <el-tag type="success" v-if="scope.row.relayStatus === 0">动作</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 === 1">初始</el-tag>
          <el-tag type="success" v-if="scope.row.pulseStatus === 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.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="调零AD" align="center" prop="adjustmentZeroAd" />-->
<!--      <el-table-column label="调零状态" align="center" prop="zeroStatus" >-->
<!--        <template slot-scope="scope">-->
<!--          <el-tag type="info" v-if="scope.row.zeroStatus === '0'">异常</el-tag>-->
<!--          <el-tag type="success" v-if="scope.row.zeroStatus === '1'">正常</el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="标定AD" align="center" prop="calibrationAd" />-->
<!--      <el-table-column label="标定状态" align="center" prop="calibrationStatus" >-->
<!--        <template slot-scope="scope">-->
<!--          <el-tag type="info" v-if="scope.row.calibrationStatus === '0'">异常</el-tag>-->
<!--          <el-tag type="success" v-if="scope.row.calibrationStatus === '1'">正常</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-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--        <template slot-scope="scope">-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleSingleUpload(scope.row)"-->
<!--          >上传</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>

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

    <!-- 添加或修改未上传成功的历史数据列对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="托盘id" prop="trayId">
          <el-input v-model="form.trayId" placeholder="请输入托盘id" />
        </el-form-item>
        <el-form-item label="绑定的设备编号" prop="deviceCode">
          <el-input v-model="form.deviceCode" placeholder="请输入绑定的设备编号" />
        </el-form-item>
        <el-form-item label="行" prop="row">
          <el-input v-model="form.row" placeholder="请输入行" />
        </el-form-item>
        <el-form-item label="列" prop="col">
          <el-input v-model="form.col" placeholder="请输入列" />
        </el-form-item>
        <el-form-item label="第几个" prop="index">
          <el-input v-model="form.index" placeholder="请输入第几个" />
        </el-form-item>
        <el-form-item label="编号" prop="number">
          <el-input v-model="form.number" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="绑定时间" prop="bindingTime">
          <el-date-picker clearable size="small"
            v-model="form.bindingTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择绑定时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="解绑时间" prop="unbindingTime">
          <el-date-picker clearable size="small"
            v-model="form.unbindingTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择解绑时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="0-预热；1-正常;3-传感器故障;4-报警；5-通讯故障">
          <el-radio-group v-model="form.status">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="设置-年" prop="recordYear">
          <el-input v-model="form.recordYear" placeholder="请输入设置-年" />
        </el-form-item>
        <el-form-item label="设置-月" prop="recordMonth">
          <el-input v-model="form.recordMonth" placeholder="请输入设置-月" />
        </el-form-item>
        <el-form-item label="设置-日" prop="recordDate">
          <el-input v-model="form.recordDate" placeholder="请输入设置-日" />
        </el-form-item>
        <el-form-item label="设置-时" prop="recordHour">
          <el-input v-model="form.recordHour" placeholder="请输入设置-时" />
        </el-form-item>
        <el-form-item label="设置-分" prop="recordMinute">
          <el-input v-model="form.recordMinute" placeholder="请输入设置-分" />
        </el-form-item>
        <el-form-item label="写入时间状态;0-失败;1-成功">
          <el-radio-group v-model="form.writeTimeStatus">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="调零AD" prop="adjustmentZeroAd">
          <el-input v-model="form.adjustmentZeroAd" placeholder="请输入调零AD" />
        </el-form-item>
        <el-form-item label="合格；不合格">
          <el-radio-group v-model="form.zeroStatus">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标定AD" prop="calibrationAd">
          <el-input v-model="form.calibrationAd" placeholder="请输入标定AD" />
        </el-form-item>
        <el-form-item label="合格；不合格">
          <el-radio-group v-model="form.calibrationStatus">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="浓度值" prop="concentration">
          <el-input v-model="form.concentration" placeholder="请输入浓度值" />
        </el-form-item>
        <el-form-item label="写入时间状态;0-失败;1-成功">
          <el-radio-group v-model="form.runTimeStatus">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="实时AD值" prop="realTimeAd">
          <el-input v-model="form.realTimeAd" placeholder="请输入实时AD值" />
        </el-form-item>
        <el-form-item label="实时AD状态;0-异常;1-正常">
          <el-radio-group v-model="form.realTimeAdStatus">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listHistory, getHistory, delHistory, addHistory, updateHistory, exportHistory ,reUpload} from "@/api/palletDeviceBinding/palletDeviceUploadHistory";

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,
        deviceCode: null,
        trayCode: null,
        row: null,
        col: null,
        index: null,
        number: null,
        bindingTime: null,
        unbindingTime: null,
        createTime: null,
        status: 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,
        realTimeAdStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        trayId: [
          { required: true, message: "托盘id不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取标定状态文本
    getCalibrationText(status) {
      if (status === '4') {
        return '正常'
      } else if (status) {
        return '异常'
      }
    },
// 获取标定状态的el-tag类型
    getCalibrationTagType(status) {
      if (status === '4') {
        return 'success' // 正常 - 绿色
      } else if (status) {
        return 'info' // 异常 - 红色
      }
    },
    /** 查询未上传成功的历史数据列列表 */
    getList() {
      this.loading = true;
      listHistory(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,
        deviceCode: null,
        row: null,
        col: null,
        index: null,
        number: null,
        bindingTime: null,
        unbindingTime: null,
        createTime: null,
        status: "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,
        realTimeAdStatus: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加未上传成功的历史数据列";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getHistory(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改未上传成功的历史数据列";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateHistory(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHistory(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除未上传成功的历史数据列编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delHistory(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    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 exportHistory(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
