<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产线">
        <el-select v-model="queryParams.productionLine" placeholder="请选择产线" clearable @change="handleQuery" style="width: 150px;">
          <el-option v-for="item in lineList" :key="item.lineId" :label="item.lineName" :value="item.lineId" />
        </el-select>
      </el-form-item>
      <el-form-item label="审批状态" prop="approvalStatus">
        <el-select v-model="queryParams.approvalStatus" placeholder="请选择状态" clearable @change="handleQuery" style="width: 120px;">
          <el-option label="待审批" :value="1" />
          <el-option label="已通过" :value="2" />
          <el-option label="已驳回" :value="3" />
          <el-option label="已撤销" :value="4" />
        </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" v-if="!readonly">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="approvalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" v-if="!readonly" />
      <el-table-column label="产线" align="center" prop="productionLine" width="100">
        <template slot-scope="scope">
          {{ getLineName(scope.row.productionLine) }}
        </template>
      </el-table-column>
      <el-table-column label="巡检开始时间" align="center" prop="insStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.insStartTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="巡检结束时间" align="center" prop="insEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.insEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center" prop="applyUser" width="100" />
      <el-table-column label="申请时间" align="center" prop="applyTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批状态" align="center" prop="approvalStatus" width="90">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.approvalStatus === 1" type="warning">待审批</el-tag>
          <el-tag v-else-if="scope.row.approvalStatus === 2" type="success">已通过</el-tag>
          <el-tag v-else-if="scope.row.approvalStatus === 3" type="danger">已驳回</el-tag>
          <el-tag v-else-if="scope.row.approvalStatus === 4" type="info">已撤销</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审批人" align="center" prop="approvalUser" width="100" />
      <el-table-column label="审批时间" align="center" prop="approvalTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approvalTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批意见" align="center" prop="approvalOpinion" show-overflow-tooltip />
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="操作" align="center" width="280" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>
          <el-button v-if="scope.row.approvalStatus === 1" size="mini" type="text" icon="el-icon-check" @click="handleApprove(scope.row)">通过</el-button>
          <el-button v-if="scope.row.approvalStatus === 1" size="mini" type="text" icon="el-icon-close" @click="handleReject(scope.row)">驳回</el-button>
          <el-button v-if="scope.row.approvalStatus === 1 || scope.row.approvalStatus === 4" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(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="dialogTitle" :visible.sync="dialogVisible" width="500px" append-to-body>
      <el-form ref="dialogForm" :model="dialogForm" :rules="dialogRules" label-width="80px">
        <el-form-item label="审批意见" prop="approvalOpinion">
          <el-input v-model="dialogForm.approvalOpinion" type="textarea" rows="3" placeholder="请输入审批意见" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitApproval">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEquipmentInspectionApproval, delEquipmentInspectionApproval, updateEquipmentInspectionApproval } from "@/api/mes/eqp/equipmentInspectionApproval";
import { listProductionLine } from "@/api/wms/productionLine";

export default {
  name: "EquipmentInspectionApproval",
  props: {
    readonly: {
      type: Boolean,
      default: false,
    },
    defaultStatus: {
      type: Number,
      default: undefined,
    },
  },
  data() {
    return {
      buttonLoading: false,
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      approvalList: [],
      dialogTitle: "",
      dialogVisible: false,
      approvalAction: "",
      currentRow: null,
      lineList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productionLine: undefined,
        approvalStatus: this.defaultStatus,
      },
      dialogForm: {
        approvalOpinion: "",
      },
      dialogRules: {},
    };
  },
  created() {
    this.loadLineList();
  },
  methods: {
    async loadLineList() {
      try {
        const res = await listProductionLine({ pageSize: 999 });
        if (res.rows) this.lineList = res.rows;
        this.getList();
      } catch (e) { console.error('加载产线列表失败', e); }
    },
    getLineName(lineId) {
      const found = this.lineList.find(l => l.lineId === lineId);
      return found ? found.lineName : '';
    },
    getList() {
      this.loading = true;
      listEquipmentInspectionApproval(this.queryParams).then(response => {
        this.approvalList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.approvalId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    formatQueryDate(date) {
      if (!date) return '';
      const d = new Date(date);
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
    },
    handleDetail(row) {
      this.$router.push({
        path: '/eqp/day',
        query: {
          productionLine: row.productionLine,
          startDate: this.formatQueryDate(row.insStartTime),
          endDate: this.formatQueryDate(row.insEndTime),
        }
      });
    },
    handleApprove(row) {
      this.currentRow = row;
      this.approvalAction = 'approve';
      this.dialogTitle = "审批通过";
      this.dialogForm.approvalOpinion = "";
      this.dialogVisible = true;
    },
    handleReject(row) {
      this.currentRow = row;
      this.approvalAction = 'reject';
      this.dialogTitle = "审批驳回";
      this.dialogForm.approvalOpinion = "";
      this.dialogVisible = true;
    },
    submitApproval() {
      this.$refs["dialogForm"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          const status = this.approvalAction === 'approve' ? 2 : 3;
          updateEquipmentInspectionApproval({
            approvalId: this.currentRow.approvalId,
            approvalStatus: status,
            approvalOpinion: this.dialogForm.approvalOpinion,
          }).then(() => {
            const msg = this.approvalAction === 'approve' ? '审批通过' : '已驳回';
            this.$modal.msgSuccess(msg);
            this.dialogVisible = false;
            this.getList();
          }).finally(() => {
            this.buttonLoading = false;
          });
        }
      });
    },
    handleDelete(row) {
      const approvalIds = row.approvalId || this.ids;
      this.$modal.confirm('是否确认删除审批记录编号为"' + approvalIds + '"的数据项？').then(() => {
        this.loading = true;
        return delEquipmentInspectionApproval(approvalIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
        this.loading = false;
      });
    },
  },
};
</script>
