<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="60px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input v-model="queryParams.taskName" placeholder="请输入任务名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="机组" prop="unitGroup">
        <el-input v-model="queryParams.unitGroup" placeholder="请输入机组" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工段" prop="workshopSection">
        <el-input v-model="queryParams.workshopSection" placeholder="请输入工段" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工序" prop="process">
        <el-input v-model="queryParams.process" placeholder="请输入工序" clearable @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="success" plain icon="el-icon-edit" size="mini" :disabled="!selectedTask"
          @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 上方任务列表表格 -->
    <div class="mb10">
      <KLPTable ref="checkTaskTable" height="300px" highlight-current-row v-loading="loading" :data="checkTaskList"
        @row-click="handleRowClick">
        <el-table-column label="任务名称" align="center" prop="taskName" />
        <el-table-column label="钢卷号" align="center" prop="coilList[0].currentCoilNo" />
        <el-table-column label="工段" align="center" prop="workshopSection" />
        <el-table-column label="工序" align="center" prop="process" />
        <el-table-column label="机组" align="center" prop="unitGroup" />
        <el-table-column label="检验结果" align="center">
          <template slot-scope="scope">
            <span>
              <span v-if="scope.row.inspectionResult == 0" style="color: grey;">未检验</span>
              <span v-else-if="scope.row.inspectionResult == 1" style="color: #67C23A;">合格</span>
              <span v-else-if="scope.row.inspectionResult == 2" style="color: #FF4949;">不合格</span>
              <span v-else style="color: grey;">未知</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <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="handleAccept(scope.row)">合格</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleReject(scope.row)">不合格</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </KLPTable>

    </div>

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

    <!-- 下方检测详情表格 -->
    <div class="detail-section">
      <div class="table-title">检测详情</div>
      <div v-if="selectedTask && detailData.itemList && detailData.itemList.length > 0">
        <KLPTable v-loading="detailLoading" :data="detailData.itemList" style="margin-top: 10px;">
          <el-table-column label="检查项" align="center" prop="itemName">
            <template slot-scope="scope">
              <el-tag type="info">{{ scope.row.itemName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="定性定量" align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.qualitativeQuantitative !== undefined"
                :type="scope.row.qualitativeQuantitative === 0 ? 'primary' : 'warning'">
                {{ scope.row.qualitativeQuantitative === 0 ? '定性' : '定量' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="标准目标" align="center" prop="standardTarget"></el-table-column>
          <el-table-column label="目标上限" align="center" prop="targetUpper"></el-table-column>
          <el-table-column label="目标下限" align="center" prop="targetLower"></el-table-column>
          <el-table-column label="实测值" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.actualMeasure" placeholder="请输入实测值" clearable
                @blur="handleBlur(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column label="单位" align="center" prop="unit"></el-table-column>
          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <span>
                <span v-if="scope.row.status == 0" style="color: gray;">未检测</span>
                <span v-else-if="scope.row.status == 1" style="color: #67C23A;">通过</span>
                <span v-else-if="scope.row.status == 2" style="color: #FF4949;">不通过</span>
                <span v-else style="color: gray;">未知</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button v-if="scope.row.status == 0" size="mini" type="text" style="color: #67C23A;"
                @click="changeItemStatus(detailData.taskId, scope.row.itemId, 1)">通过</el-button>
              <el-button v-if="scope.row.status == 0" size="mini" type="text" style="margin-left: 8px; color: #FF4949;"
                @click="changeItemStatus(detailData.taskId, scope.row.itemId, 2)">不通过</el-button>
            </template>
          </el-table-column>
        </KLPTable>
      </div>
      <div v-else class="empty-tip">
        <el-empty description="请选择一个待检任务查看详情"></el-empty>
      </div>
    </div>

    <!-- 添加或修改检查任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="钢卷号">
          <!-- <el-input v-model="form.verifyTarget.coilId" placeholder="请输入钢卷号" /> -->
          <coil-selector v-model="form.coilIds" @select="handleCoilChange"></coil-selector>
        </el-form-item>
        <el-form-item label="检查项" prop="itemId" v-if="!form.taskId">
          <CheckItemSelect v-model="form.itemId" />
        </el-form-item>
        <el-form-item label="工段" prop="workshopSection">
          <el-input v-model="form.workshopSection" placeholder="请输入工段" />
        </el-form-item>
        <el-form-item label="工序" prop="process">
          <el-input v-model="form.process" placeholder="请输入工序" />
        </el-form-item>
        <el-form-item label="机组" prop="unitGroup">
          <el-input v-model="form.unitGroup" placeholder="请输入机组" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <!-- <el-form-item label="检验结果" prop="inspectionResult">
          <el-select v-model="form.inspectionResult" placeholder="请选择检验结果">
            <el-option label="未检验" :value="0" />
            <el-option label="合格" :value="1" />
            <el-option label="不合格" :value="2" />
          </el-select>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { listCheckTask, getCheckTask, delCheckTask, addCheckTask, updateCheckTask } from '@/api/mes/qc/checkTask'
import { updateCheckTaskItemStatus, updateCheckTaskItem } from '@/api/mes/qc/checkTaskItem'
import CheckItemSelect from '@/components/KLPService/CheckItemSelect/index'
import CoilSelector from '@/components/CoilSelector/index.vue'


export default {
  name: 'CheckTask',
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 检查任务表格数据
      checkTaskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        taskName: undefined,
        unitGroup: undefined,
        workshopSection: undefined,
        process: undefined,
        inspectionType: 'section'
      },
      // 表单参数
      form: {
        verifyTarget: {
          coilId: undefined
        },
        workshopSection: undefined,
        process: undefined,
        unitGroup: undefined,
        inspectionResult: 0,
        inspectionType: 'section'
      },
      // 表单校验
      rules: {
      },
      detailData: {},
      // 选中的任务（当前选择的行）
      selectedTask: null
    };
  },
  created() {
    console.log(this.$refs.checkTaskTable, '初始化表格数据')
    this.getList();
  },
  components: {
    CheckItemSelect,
    CoilSelector
  },
  methods: {
    /** 查询检查任务列表 */
    getList() {
      this.loading = true;
      listCheckTask(this.queryParams).then(response => {
        this.checkTaskList = response.rows.map(item => ({
          ...item,
          verifyTarget: JSON.parse(item.verifyTarget)
        }));
        this.total = response.total;
        this.loading = false;
      });
    },
    handleCoilChange(coil) {
      this.form.verifyTarget.coilId = coil.coilId
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    handleBlur(row) {
      updateCheckTaskItem({ ...row, itemId: row.checkTaskItemId }).then(response => {
        this.$message({
          message: '更新成功',
          type: 'success'
        })
      })
    },
    handleAccept(row) {
      updateCheckTask({ taskId: row.taskId, inspectionResult: 1 }).then(response => {
        this.$message({
          message: '更新成功',
          type: 'success'
        })
        this.getList()
      })
    },
    handleReject(row) {
      updateCheckTask({ taskId: row.taskId, inspectionResult: 2 }).then(response => {
        this.$message({
          message: '更新成功',
          type: 'success'
        })
        this.getList()
      })
    },
    // 表单重置
    reset() {
      this.form = {
        taskId: undefined,
        taskName: undefined,
        itemId: [],
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        remark: undefined,
        verifyTarget: {
          coilId: undefined
        },
        workshopSection: undefined,
        process: undefined,
        unitGroup: undefined,
        inspectionResult: 0,
        inspectionType: 'section',
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 点击行选中任务 */
    handleRowClick(row) {
      // 否则选中当前行
      this.selectedTask = row
      this.loadTaskDetail(row.taskId)
    },

    // 加载任务详情
    loadTaskDetail(taskId) {
      this.detailLoading = true
      console.log(taskId, '加载任务详情')
      getCheckTask(taskId)
        .then(response => {
          this.detailData = response.data
          this.detailLoading = false
        })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加检查任务";
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.loading = true;
      this.reset();
      getCheckTask(this.selectedTask.taskId).then(response => {
        this.loading = false;
        this.form = {
          ...response.data,
          verifyTarget: JSON.parse(response.data.verifyTarget)
        };
        this.open = true;
        this.title = "修改检查任务";
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.loading = true
      getCheckTask(row.taskId).then(response => {
        this.detailData = response.data
      }).finally(() => {
        this.loading = false
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          // 对象转json
          const payload = {
            ...this.form,
            itemId: this.form.itemId.split(','),
            verifyTarget: JSON.stringify(this.form.verifyTarget)
          }
          if (this.form.taskId != null) {
            updateCheckTask(payload).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addCheckTask(payload).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const taskId = row ? row.taskId : this.selectedTask.taskId;
      this.$modal.confirm('是否确认删除检查任务编号为"' + taskId + '"的数据项？').then(() => {
        this.loading = true;
        return delCheckTask(taskId);
      }).then(() => {
        this.loading = false;
        this.getList();
        // 重置选中状态和详情数据
        this.selectedTask = null;
        this.detailData = {};
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('qc/checkTask/export', {
        ...this.queryParams
      }, `checkTask_${new Date().getTime()}.xlsx`)
    },
    /** 修改检查项状态 */
    changeItemStatus(checkTaskId, checkItemId, status) {
      this.$modal.confirm('确定要将该检查项状态修改为' + (status === 1 ? '通过' : '不通过') + '吗？').then(() => {
        // 调用新接口
        return updateCheckTaskItemStatus({ checkTaskId, checkItemId, status })
      }).then(() => {
        this.$modal.msgSuccess('状态修改成功')
        // 重新拉取详情
        getCheckTask(this.detailData.taskId).then(response => {
          this.detailData = response.data
        })
      })
    },
  },

  // 添加样式
  computed: {
    styles() {
      return {
        mb10: { marginBottom: '10px' },
        detailSection: {
          marginTop: '20px',
          border: '1px solid #e6e6e6',
          borderRadius: '4px',
          padding: '10px'
        },
        tableTitle: {
          fontSize: '16px',
          fontWeight: 'bold',
          marginBottom: '10px',
          color: '#333'
        },
        emptyTip: {
          textAlign: 'center',
          padding: '40px 0',
          backgroundColor: '#fafafa',
          borderRadius: '4px'
        }
      }
    }
  },
};
</script>
