<template>
  <div>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="编号" prop="id">
          <el-input
            v-model="queryParams.id"
            placeholder="请输入编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="样品名称" prop="sampleName">
          <el-input
            v-model="queryParams.sampleName"
            placeholder="请输入样品名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="质检状态" prop="status">
          <el-input
            v-model="queryParams.status"
            placeholder="请输入质检状态"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="操作者" prop="operator">
          <el-input
            v-model="queryParams.operator"
            placeholder="请输入操作者"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="测试时间">
          <el-date-picker
            v-model="testTimeRange"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </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"
            v-hasPermi="['system:data:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:data:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:data:remove']"
          >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:data:export']"
          >导出
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        <el-col :span="2" style="text-align:right;float:right;">
          <el-button type="warning" icon="el-icon-refresh" size="mini" @click="handleRefreshStatus">
            状态一键判定
          </el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="自增主键" align="center" prop="id"/>
        <el-table-column label="样品名称" align="center" prop="sampleName"/>
        <el-table-column label="材料" align="center" prop="material"/>
        <el-table-column label="采购信息" align="center" prop="purchase"/>
        <el-table-column label="分析组" align="center" prop="analysisGroup"/>
        <el-table-column label="操作者" align="center" prop="operator"/>
        <el-table-column label="测试时间" align="center" prop="testTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.testTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="准直器 (mm)" align="center" prop="collimator"/>
        <el-table-column label="备注" align="center" prop="remark"/>
        <el-table-column label="状态" align="center" prop="status"/>
        <el-table-column label="记录创建时间" align="center" prop="createdAt" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="showDetails(scope.row)"
            >详情
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-circle-check"
              v-hasPermi="['system:data:release']"
              v-if="scope.row.status==='不合格'"
              @click="handleStatusChange(scope.row, '已放行')"
            >放行
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-close"
              v-hasPermi="['system:data:abolish']"
              v-if="scope.row.status==='不合格'"
              @click="handleStatusChange(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"
      />

      <!-- 添加或修改RoHS 测试数据，支持镉、铅、汞、铬、溴、氯检测对话框 -->
      <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="编号" prop="no">
            <el-input v-model="form.no" placeholder="请输入编号"/>
          </el-form-item>
          <el-form-item label="样品名称" prop="sampleName">
            <el-input v-model="form.sampleName" placeholder="请输入样品名称"/>
          </el-form-item>
          <el-form-item label="收件人" prop="addressee">
            <el-input v-model="form.addressee" placeholder="请输入收件人"/>
          </el-form-item>
          <el-form-item label="报告日期" prop="reportDate">
            <el-date-picker clearable
                            v-model="form.reportDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择报告日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="部件号" prop="partNo">
            <el-input v-model="form.partNo" placeholder="请输入部件号"/>
          </el-form-item>
          <el-form-item label="重量" prop="weight">
            <el-input v-model="form.weight" placeholder="请输入重量"/>
          </el-form-item>
          <el-form-item label="材料" prop="material">
            <el-input v-model="form.material" placeholder="请输入材料"/>
          </el-form-item>
          <el-form-item label="采购信息" prop="purchase">
            <el-input v-model="form.purchase" placeholder="请输入采购信息"/>
          </el-form-item>
          <el-form-item label="分析组" prop="analysisGroup">
            <el-input v-model="form.analysisGroup" placeholder="请输入分析组"/>
          </el-form-item>
          <el-form-item label="操作者" prop="operator">
            <el-input v-model="form.operator" placeholder="请输入操作者"/>
          </el-form-item>
          <el-form-item label="测试时间" prop="testTime">
            <el-date-picker clearable
                            v-model="form.testTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择测试时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="数据文件路径" prop="path">
            <el-input v-model="form.path" type="textarea" placeholder="请输入内容"/>
          </el-form-item>
          <el-form-item label="测试环境大气" prop="atmosphere">
            <el-input v-model="form.atmosphere" placeholder="请输入测试环境大气"/>
          </el-form-item>
          <el-form-item label="准直器 (mm)" prop="collimator">
            <el-input v-model="form.collimator" placeholder="请输入准直器 (mm)"/>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
          </el-form-item>
          <el-form-item label="部件编号 (P/N)" prop="pN">
            <el-input v-model="form.pN" placeholder="请输入部件编号 (P/N)"/>
          </el-form-item>
          <el-form-item label="单元编号" prop="unitNo">
            <el-input v-model="form.unitNo" placeholder="请输入单元编号"/>
          </el-form-item>
          <el-form-item label="业务单元" prop="businessUnit">
            <el-input v-model="form.businessUnit" placeholder="请输入业务单元"/>
          </el-form-item>
          <el-form-item label="记录创建时间" prop="createdAt">
            <el-date-picker clearable
                            v-model="form.createdAt"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择记录创建时间">
            </el-date-picker>
          </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>
    <!-- 新增RoHS详细字段详情弹窗 -->
    <el-dialog :title="'RoHS检测详细信息'" :visible.sync="detailsOpen" width="600px" append-to-body>
      <div v-if="detailsData">
        <el-descriptions column="2" :border="true">
          <el-descriptions-item
            v-for="item in filteredDetailFields"
            :key="item.key"
            :label="item.label"
          >
            {{ detailsData[item.key] }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="detailsOpen = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {listData, getData, delData, addData, updateData, refreshStatus} from "@/api/qc/data"

export default {
  name: "Data",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // RoHS 测试数据，支持镉、铅、汞、铬、溴、氯检测表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      testTimeRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id : null,
        no: null,
        sampleName: null,
        status: null,
        addressee: null,
        reportDate: null,
        partNo: null,
        weight: null,
        material: null,
        purchase: null,
        analysisGroup: null,
        operator: null,
        testTime: null,
        path: null,
        atmosphere: null,
        collimator: null,
        remark: null,
        pN: null,
        unitNo: null,
        businessUnit: null,
        createdAt: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      detailsOpen: false,
      detailsData: null,
      detailFields: [
        {key: 'cadmiumPpm', label: '镉含量(ppm)'},
        {key: 'cadmium3sigma', label: '镉 3sigma'},
        {key: 'cadmiumJudgment', label: '镉判断结果'},
        {key: 'cadmiumKv', label: '镉测试 kV'},
        {key: 'cadmiumFilter', label: '镉滤波器'},
        {key: 'cadmiumUa', label: '镉 uA'},
        {key: 'cadmiumTime', label: '镉测试时间(秒)'},
        {key: 'cadmiumDt', label: '镉 DT'},
        {key: 'leadPpm', label: '铅含量(ppm)'},
        {key: 'lead3sigma', label: '铅 3sigma'},
        {key: 'leadJudgment', label: '铅判断结果'},
        {key: 'leadKv', label: '铅测试 kV'},
        {key: 'leadFilter', label: '铅滤波器'},
        {key: 'leadUa', label: '铅 uA'},
        {key: 'leadTime', label: '铅测试时间(秒)'},
        {key: 'leadDt', label: '铅 DT'},
        {key: 'mercuryPpm', label: '汞含量(ppm)'},
        {key: 'mercury3sigma', label: '汞 3sigma'},
        {key: 'mercuryJudgment', label: '汞判断结果'},
        {key: 'mercuryKv', label: '汞测试 kV'},
        {key: 'mercuryFilter', label: '汞滤波器'},
        {key: 'mercuryUa', label: '汞 uA'},
        {key: 'mercuryTime', label: '汞测试时间(秒)'},
        {key: 'mercuryDt', label: '汞 DT'},
        {key: 'chromiumPpm', label: '铬含量(ppm)'},
        {key: 'chromium3sigma', label: '铬 3sigma'},
        {key: 'chromiumJudgment', label: '铬判断结果'},
        {key: 'chromiumKv', label: '铬测试 kV'},
        {key: 'chromiumFilter', label: '铬滤波器'},
        {key: 'chromiumUa', label: '铬 uA'},
        {key: 'chromiumTime', label: '铬测试时间(秒)'},
        {key: 'chromiumDt', label: '铬 DT'},
        {key: 'brominePpm', label: '溴含量(ppm)'},
        {key: 'bromine3sigma', label: '溴 3sigma'},
        {key: 'bromineJudgment', label: '溴判断结果'},
        {key: 'bromineKv', label: '溴测试 kV'},
        {key: 'bromineFilter', label: '溴滤波器'},
        {key: 'bromineUa', label: '溴 uA'},
        {key: 'bromineTime', label: '溴测试时间(秒)'},
        {key: 'bromineDt', label: '溴 DT'},
        {key: 'chlorinePpm', label: '氯含量(ppm)'},
        {key: 'chlorine3sigma', label: '氯 3sigma'},
        {key: 'chlorineJudgment', label: '氯判断结果'},
        {key: 'chlorineKv', label: '氯测试 kV'},
        {key: 'chlorineFilter', label: '氯滤波器'},
        {key: 'chlorineUa', label: '氯 uA'},
        {key: 'chlorineTime', label: '氯测试时间(秒)'},
        {key: 'chlorineDt', label: '氯 DT'}
      ],
    }
  },
  computed: {
    filteredDetailFields() {
      if (!this.detailsData) return [];
      return this.detailFields.filter(item => {
        const v = this.detailsData[item.key];
        // 为空(null/undefined/空字符串)时过滤掉
        return v !== null && v !== undefined && v !== '';
      });
    }
  },
  created() {
    this.queryParams.id = this.$route.query.id ? this.$route.query.id : null;
    this.getList()
  },
  methods: {
    /** 查询RoHS 测试数据，支持镉、铅、汞、铬、溴、氯检测列表 */
    getList() {
      this.loading = true
      listData(this.addDateRange(this.queryParams, this.testTimeRange, 'TestTime')).then(response => {
        console.log("--------" + response)
        this.dataList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        no: null,
        sampleName: null,
        addressee: null,
        reportDate: null,
        partNo: null,
        weight: null,
        material: null,
        purchase: null,
        analysisGroup: null,
        operator: null,
        testTime: null,
        path: null,
        atmosphere: null,
        collimator: null,
        remark: null,
        pN: null,
        unitNo: null,
        businessUnit: null,
        createdAt: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      console.log('resetQuery');
      
      this.testTimeRange = []
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        id: null,
        no: null,
        sampleName: null,
        status: null,
        addressee: null,
        reportDate: null,
        partNo: null,
        weight: null,
        material: null,
        purchase: null,
        analysisGroup: null,
        operator: null,
        testTime: null,
        path: null,
        atmosphere: null,
        collimator: null,
        remark: null,
        pN: null,
        unitNo: null,
        businessUnit: null,
        createdAt: null
      }
      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 = "添加RoHS 测试数据，支持镉、铅、汞、铬、溴、氯检测"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getData(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改RoHS 测试数据，支持镉、铅、汞、铬、溴、氯检测"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateData(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addData(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除RoHS 测试数据，支持镉、铅、汞、铬、溴、氯检测编号为"' + ids + '"的数据项？').then(function () {
        return delData(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/data/export', {
        ...this.queryParams
      }, `data_${new Date().getTime()}.xlsx`)
    },
    showDetails(row) {
      const id = row.id;
      getData(id).then(response => {
        this.detailsData = response.data || {};
        this.detailsOpen = true;
      });
    },
    handleRefreshStatus() {
      this.$confirm('是否批量刷新所有RoHS数据的合格/不合格状态？', '提示', {
        type: 'warning'
      }).then(() => {
        this.loading = true;
        refreshStatus().then(res => {
          this.$message.success(res.msg || '刷新完成');
          this.getList();
        }).finally(() => {
          this.loading = false;
        });
      });
    },
    handleStatusChange(row, newStatus) {
      const id = row.id;
      const updated = {id, status: newStatus};
      this.$modal.confirm(`确认将编号为\"${id}\"的数据状态修改为\"${newStatus}\"吗？`).then(() => {
        updateData(updated).then(res => {
          this.$modal.msgSuccess('状态更新成功');
          this.getList();
        });
      });
    },
  }
}
</script>
