<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="入场钢卷号" prop="enterCoilNo">
        <el-input v-model="queryParams.enterCoilNo" placeholder="请输入入场钢卷号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="当前钢卷号" prop="currentCoilNo">
        <el-input v-model="queryParams.currentCoilNo" placeholder="请输入当前钢卷号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="数据状态">
        <el-select v-model="queryParams.dataType" placeholder="请选择数据状态" clearable>
          <el-option :value="0" label="历史数据">历史数据</el-option>
          <el-option :value="1" label="当前数据">当前数据</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="厂家卷号" prop="supplierCoilNo">
        <el-input v-model="queryParams.supplierCoilNo" placeholder="请输入厂家原料卷号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="班组" prop="team">
        <el-input v-model="queryParams.team" 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="single"
          @click="handleCheck">修正</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleDelete">删除</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>

    <el-table v-loading="loading" :data="materialCoilList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="入场钢卷号" align="center" prop="enterCoilNo" />
      <el-table-column label="当前钢卷号" align="center" prop="currentCoilNo" />
      <el-table-column label="厂家原料卷号" align="center" prop="supplierCoilNo" />
      <el-table-column label="数据类型" align="center" prop="dataType">
        <template slot-scope="scope">
          {{ scope.row.dataType == 0 ? '历史数据' : '当前数据' }}
        </template>
      </el-table-column>
      <el-table-column label="二维码" v-if="qrcode">
        <template slot-scope="scope">
          <QRCode v-if="scope.row.dataType == 1" :content="scope.row.qrcodeRecordId" :size="50" />
        </template>
      </el-table-column>
      <el-table-column label="班组" align="center" prop="team" />
      <el-table-column label="毛重" align="center" prop="grossWeight" />
      <el-table-column label="净重" align="center" prop="netWeight" />
      <el-table-column label="仓库" align="center" prop="warehouseName" />
      <el-table-column label="物品" align="center" prop="itemName">
        <template slot-scope="scope">
          <ProductInfo v-if="scope.row.itemType == 'product'" productId="scope.row.itemId">
            <template slot-scope="{ product }">
              {{ product.productName }}({{ product.productCode }})
            </template>
          </ProductInfo>
          <RawMaterialInfo v-else-if="scope.row.itemType === 'raw_material'" :materialId="scope.row.itemId">
            <template slot-scope="{ material }">
              {{ material.rawMaterialName }}({{ material.rawMaterialCode }})
            </template>
          </RawMaterialInfo>
        </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-download" @click="handleDownloadQRCode(scope.row)"
            v-if="qrcode">
            下载二维码
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleCheck(scope.row)">修正</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-search" @click="handleTrace(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="100px">
        <el-form-item label="入场钢卷号" prop="enterCoilNo">
          <el-input v-model="form.enterCoilNo" placeholder="请输入入场钢卷号" />
        </el-form-item>
        <el-form-item label="当前钢卷号" prop="currentCoilNo">
          <el-input v-model="form.currentCoilNo" placeholder="请输入当前钢卷号" />
        </el-form-item>
        <el-form-item v-if="!form.coilId" label="厂家原料卷号" prop="supplierCoilNo">
          <el-input v-model="form.supplierCoilNo" placeholder="请输入厂家原料卷号" />
        </el-form-item>
        <el-form-item label="所在库区" prop="warehouseId">
          <warehouse-select v-model="form.warehouseId" placeholder="请选择仓库/库区/库位" style="width: 100%;" clearable />
        </el-form-item>
        <el-form-item label="班组" prop="team">
          <el-input v-model="form.team" placeholder="请输入班组" />
        </el-form-item>
        <el-form-item label="物品类型" prop="itemType">
          <el-select v-model="form.itemType" placeholder="请选择物品类型">
            <el-option label="成品" value="product" />
            <el-option label="原料" value="raw_material" />
          </el-select>
        </el-form-item>
        <el-form-item label="物品ID" prop="itemId">
          <product-select v-if="form.itemType == 'product'" v-model="form.itemId" placeholder="请选择成品ID" style="width: 100%;" clearable />
          <raw-material-select v-else-if="form.itemType == 'raw_material'" v-model="form.itemId" placeholder="请选择原料ID" style="width: 100%;" clearable />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="毛重" prop="grossWeight">
          <el-input v-model="form.grossWeight" placeholder="请输入毛重" />
        </el-form-item>
        <el-form-item label="净重" prop="NetWeight">
          <el-input v-model="form.netWeight" placeholder="请输入净重" />
        </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>

    <!-- 钢卷追溯对话框（使用封装的组件） -->
    <el-dialog title="钢卷追溯" :visible.sync="traceOpen" width="90%" append-to-body>
      <coil-trace-result :trace-result="traceResult"></coil-trace-result>
    </el-dialog>
  </div>
</template>

<script>
import { listMaterialCoil, getMaterialCoil, delMaterialCoil, addMaterialCoil, updateMaterialCoilSimple, getMaterialCoilTrace } from "@/api/wms/coil";
import WarehouseSelect from "@/components/WarehouseSelect";
import QRCode from "../../print/components/QRCode.vue";
import { saveAsImage } from '@/utils/klp';
import ProductSelect from "@/components/KLPService/ProductSelect";
import RawMaterialSelect from "@/components/KLPService/RawMaterialSelect";
// import MaterialSelect from "@/components/KLPService/ProductSelect";
import ProductInfo from "@/components/KLPService/Renderer/ProductInfo";
import BomInfoMini from "@/components/KLPService/Renderer/BomInfoMini";
import RawMaterialInfo from "@/components/KLPService/Renderer/RawMaterialInfo";
import RightToolbar from "@/components/RightToolbar";
import Pagination from "@/components/Pagination";
// 引入封装的追溯结果组件
import CoilTraceResult from "./CoilTraceResult.vue"; // 路径根据实际存放位置调整

export default {
  name: "MaterialCoil",
  components: {
    WarehouseSelect,
    QRCode,
    // MaterialSelect,
    ProductSelect,
    RawMaterialSelect,
    ProductInfo,
    RawMaterialInfo,
    BomInfoMini,
    RightToolbar,
    Pagination,
    CoilTraceResult // 注册组件
  },
  props: {
    qrcode: {
      type: Boolean,
      default: false,
    },
    querys: {
      type: Object,
      default: () => {},
    }
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 钢卷物料表格数据
      materialCoilList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 追溯对话框显示
      traceOpen: false,
      // 追溯结果数据（传递给组件）
      traceResult: null,
      // 查询参数
      queryParams: {
        ...this.querys,
        pageNum: 1,
        pageSize: 10,
        enterCoilNo: undefined,
        currentCoilNo: undefined,
        supplierCoilNo: undefined,
        warehouseId: undefined,
        nextWarehouseId: undefined,
        qrcodeRecordId: undefined,
        team: undefined,
        hasMergeSplit: undefined,
        parentCoilNos: undefined,
        itemId: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      transferCoilForm: {},
      // 表单校验
      rules: {
        enterCoilNo: [
          { required: true, message: "入场钢卷号不能为空", trigger: "blur" }
        ],
        currentCoilNo: [
          { required: true, message: "当前钢卷号不能为空", trigger: "blur" }
        ],
        itemId: [
          { required: true, message: "物品ID不能为空", trigger: "blur" }
        ],
        itemType: [
          { required: true, message: "物品类型不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询钢卷物料列表 */
    getList() {
      this.loading = true;
      listMaterialCoil(this.queryParams).then(response => {
        this.materialCoilList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 追溯按钮操作 */
    handleTrace(row) {
      this.traceOpen = true;
      this.traceResult = null; // 清空历史数据
      getMaterialCoilTrace({
        enterCoilNo: row.enterCoilNo,
        currentCoilNo: row.currentCoilNo,
      }).then(res => {
        this.traceResult = res.data; // 将结果传递给组件
      }).catch(err => {
        console.error('溯源查询失败：', err);
        this.$message.error('溯源查询失败，请重试');
      });
    },
    /** 下载二维码 */
    handleDownloadQRCode(row) {
      try {
        saveAsImage(
          row.qrcodeRecordId,
          '',
          1,
          {
            barcodeWidth: 200,
            barcodeHeight: 200
          }
        );
        this.$message.success('图片保存成功');
      } catch (error) {
        console.error('保存图片失败', error);
        this.$message.error('保存图片失败，请稍后重试');
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        coilId: undefined,
        enterCoilNo: undefined,
        currentCoilNo: undefined,
        supplierCoilNo: undefined,
        dataType: undefined,
        warehouseId: undefined,
        nextWarehouseId: undefined,
        qrcodeRecordId: undefined,
        team: undefined,
        hasMergeSplit: undefined,
        parentCoilNos: undefined,
        itemId: undefined,
        itemType: undefined,
        status: undefined,
        remark: undefined,
        delFlag: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.coilId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.isCheck = false;
      this.reset();
      this.open = true;
      this.title = "添加钢卷物料";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isCheck = false;
      this.loading = true;
      this.reset();
      const coilId = row.coilId || this.ids
      getMaterialCoil(coilId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改钢卷物料";
      });
    },
    handleCheck(row) {
      this.isCheck = true;
      this.loading = true;
      this.reset();
      const coilId = row.coilId || this.ids
      getMaterialCoil(coilId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改钢卷物料";
      });
    },
    transferCoil() {},
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.coilId != null) {
            updateMaterialCoilSimple(this.form).then(_ => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addMaterialCoil(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const coilIds = row.coilId || this.ids;
      this.$modal.confirm('是否确认删除钢卷物料编号为"' + coilIds + '"的数据项？').then(() => {
        this.loading = true;
        return delMaterialCoil(coilIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/materialCoil/export', {
        ...this.queryParams
      }, `materialCoil_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>