<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="发货单名称" prop="waybillName">
        <el-input v-model="queryParams.waybillName" placeholder="请输入发货单名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="收货单位" prop="consigneeUnit">
        <el-input v-model="queryParams.consigneeUnit" 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-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" :disabled="!selectedPlan"
          title="请先选择发货计划">新增</el-button> -->
        <el-button type="success" plain icon="el-icon-refresh" size="mini" @click="handleQuery">刷新</el-button>
        <!-- <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button> -->
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" border :data="deliveryWaybillList" highlight-current-row>
      <el-table-column label="发货单唯一ID" align="center" prop="waybillId" v-if="false" />
      <el-table-column label="发货单名称" align="center" prop="waybillName" />
      <el-table-column label="车牌" align="center" prop="licensePlate" width="100" />
      <el-table-column label="发货单位" align="center" prop="senderUnit" />
      <el-table-column label="发货时间" align="center" prop="deliveryTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="负责人" align="center" prop="principal" />
      <el-table-column label="负责人电话" align="center" prop="principalPhone" width="100" />
      <el-table-column label="完成状态" align="center" prop="status" width="120">
        <template slot-scope="scope">
          <!-- <el-tag size="mini" type="success" v-if="scope.row.status === 1">已发货</el-tag>
          <el-tag size="mini" type="info" v-else>未发货</el-tag> -->
          <el-select v-model="scope.row.status" placeholder="请选择完成状态" @change="handleStatusChange(scope.row)">
            <el-option label="已发货" :value="1" />
            <el-option label="未发货" :value="0" />
            <el-option label="已打印" :value="2" />
            <el-option label="未打印" :value="3" />
          </el-select>
        </template>
      </el-table-column>
      <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-view" @click.stop="handlePrint(scope.row)">打印发货单</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" :disabled="scope.row.status === 1" title="已发货的发货单不能修改"
            @click.stop="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" :disabled="scope.row.status === 1"
            title="已发货的发货单不能删除" @click.stop="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="打印发货单" :visible.sync="printDialogVisible" width="1000px" append-to-body center>
      <WayBill :waybill="currentWaybill" :waybillDetails="currentWaybillDetails" />
    </el-dialog>
  </div>
</template>

<script>
import { listDeliveryWaybill, updateDeliveryWaybillStatus } from "@/api/wms/deliveryWaybill";
import { listDeliveryWaybillDetail } from "@/api/wms/deliveryWaybillDetail";
import { listCoilByIds } from "@/api/wms/coil";
import WayBill from "../components/wayBill.vue";

export default {
  name: "Exp-Bills",
  data() {
    return {
      deliveryWaybillList: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        waybillName: '',
        consigneeUnit: ''
      },
      printDialogVisible: false,
      currentWaybill: {},
      currentWaybillDetails: [],
      loading: false,
      showSearch: true,
    }
  },
  components: {
    WayBill
  },
  mounted() {
    this.getList();
  },
  methods: {
    /** 完成状态改变时的处理 */
    handleStatusChange(row) {
      // 确保在更新状态时包含waybillId
      updateDeliveryWaybillStatus({
        waybillId: row.waybillId,
        status: row.status
      }).then(() => {
        this.$modal.msgSuccess("状态更新成功");
        this.getList(); // 刷新列表
      });
    },
    /** 查询发货单列表 */
    getList() {
      this.loading = true;
      // 确保查询参数包含planId
      const params = {
        ...this.queryParams,
        // 如果选中了计划，传递planId，否则不传递该参数
        planId: this.selectedPlan ? this.selectedPlan.planId : undefined
      };
      listDeliveryWaybill(params).then(response => {
        this.deliveryWaybillList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wms/deliveryWaybill/export', {
        ...this.queryParams
      }, `deliveryWaybill_${new Date().getTime()}.xlsx`)
    },
    /** 打印发货单 */
    handlePrint(row) {
      this.loading = true;
      // 获取发货单明细
      listDeliveryWaybillDetail({
        waybillId: row.waybillId,
        pageNum: 1,
        pageSize: 1000 // 获取所有明细
      }).then(response => {
        // 处理字段映射，确保与wayBill组件使用的字段名一致
        this.currentWaybillDetails = response.rows.map(item => ({
          coilId: item.coilId,
          productName: item.productName,
          edgeType: item.edgeType,
          packageType: item.packaging, // 映射packaging到packageType
          settlementType: item.settlementType,
          rawMaterialFactory: item.rawMaterialFactory,
          coilNumber: item.coilNo, // 映射coilNo到coilNumber
          specification: item.specification,
          material: item.material,
          quantity: item.quantity,
          weight: item.weight,
          unitPrice: item.unitPrice || '',
          // 单价为空时，显示为空字符串
          remark: item.remark
        }));
        const coils = this.currentWaybillDetails.map(item => item.coilId).join(',');
        if (coils) {
          listCoilByIds(coils).then(response => {
            // 取前三位, 然后去抽后用;连接
            // 设置当前发货单
            const actualWahouseNames = [...new Set(response.rows.filter(item => Boolean(item.actualWarehouseName)).map(item => item.actualWarehouseName.slice(0, 3)))].join(';');
            this.currentWaybill = {
              ...row,
              pickupLocation: actualWahouseNames || '',
            };
            this.currentWaybillDetails = this.currentWaybillDetails.map(item => {
              const actualWarehouseName = response.rows.find(detail => detail.coilId === item.coilId)?.actualWarehouseName || '';
              return {
                ...item,
                actualWarehouseName: actualWarehouseName,
              };
            });
          });
        }
        this.currentWaybill = {
          ...row,
        };
        this.printDialogVisible = true;
        this.loading = false;

      }).catch(error => {
        console.error('获取发货单明细失败:', error);
        this.$modal.msgError('获取发货单明细失败');
        this.loading = false;
      });
    }
  }
}
</script>