<template>
  <el-card class="box-card">
    <!-- 合并标题区域和筛选区域 -->
    <div class="header-container">
      <div class="left">
        <span class="title">发货状态</span>
        <span class="update-time" v-if="updateTime">{{ updateTime }}更新</span>
      </div>
      <div class="right">
        <div class="filter-group">
          <el-select
            v-model="queryParams.status"
            placeholder="发货状态"
            clearable
            class="filter-item"
            size="small"
            style="width: 120px"
          >
            <el-option label="未发货" value="未发货" />
            <el-option label="部分发货" value="部分发货" />
            <el-option label="已发货待服务" value="已发货待服务" />
          </el-select>

          <el-input
            v-model="queryParams.customerName"
            placeholder="客户名称（模糊搜索）"
            class="filter-item"
            size="small"
            style="width: 180px"
            clearable
          />

          <el-button
            type="primary"
            size="small"
            class="filter-item search-btn"
            @click="handleFilter"
            style="height: 32px; padding: 0 30px; line-height: 30px"
            >查询</el-button
          >

          <el-button
            type="text"
            icon="el-icon-download"
            @click="handleExport"
            style="
              padding: 0;
              font-size: 16px;
              color: #909399;
              margin-left: 8px;
            "
          />
        </div>
      </div>
    </div>

    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="displayData"
        style="width: 100%"
        border
        size="small"
        :height="displayData.length > 10 ? 450 : null"
        :header-cell-style="{ background: '#f5f7fa' }"
      >
        <el-table-column type="index" label="序号" width="50" align="center">
          <template slot-scope="scope">
            <span>{{
              scope.$index +
              (queryParams.pageNum - 1) * queryParams.pageSize +
              1
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="deliveryStatusName"
          label="发货状态"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag
              :type="getStatusType(scope.row.deliveryStatusName)"
              size="mini"
              effect="plain"
            >
              {{ scope.row.deliveryStatusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="customerName"
          label="客户名称"
          min-width="120"
          align="center"
        />
        <el-table-column
          prop="contractNo"
          label="合同编号"
          width="120"
          align="center"
        />
        <el-table-column
          prop="productName"
          label="货品名称"
          min-width="120"
          align="center"
        />
        <el-table-column
          prop="orderQuantity"
          label="订单量"
          width="100"
          align="center"
        />
        <el-table-column
          prop="shippedQuantity"
          label="发货量"
          width="100"
          align="center"
        />
        <el-table-column
          prop="deliveryNo"
          label="发货单号"
          width="120"
          align="center"
        />
        <el-table-column
          prop="deliveryTime"
          label="发货时间"
          width="160"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.deliveryTime || "-" }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :auto-scroll="false"
        @pagination="handlePagination"
      />
    </div>
  </el-card>
</template>

<script>
import { GetDataByName, GetDataByNames } from "@/api/common";
import Pagination from "@/components/Pagination";
import * as XLSX from "xlsx";

export default {
  name: "DeliveryStatusTable",
  components: {
    Pagination,
  },
  data() {
    return {
      loading: false,
      updateTime: "",
      total: 0,
      queryParams: {
        status: "未发货",
        customerName: "",
        pageNum: 1,
        pageSize: 10,
      },
      defaultData: [],
    };
  },
  computed: {
    displayData() {
      return this.defaultData;
    },
  },
  created() {
    this.initData();
  },
  methods: {
    getStatusType(status) {
      switch (status) {
        case "已发货":
          return "success";
        case "部分发货":
          return "warning";
        case "未发货":
          return "info";
        default:
          return "info";
      }
    },
    async initData() {
      this.loading = true;
      try {
        await this.fetchTableData();
        this.updateTime = this.formatDateTime(new Date());
      } catch (error) {
        this.$message.error("数据加载失败：" + error.message);
      } finally {
        this.loading = false;
      }
    },
    formatDateTime(date) {
      const pad = (num) => String(num).padStart(2, "0");
      return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(
        date.getDate()
      )} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
    },
    async fetchTableData() {
      const params = {
        name: "getContractDeliveryStatus",
        page: this.queryParams.pageNum,
        offset: this.queryParams.pageNum,
        pagecount: this.queryParams.pageSize,
        returntype: "Map",
        parammaps: {
          statusName: this.queryParams.status || "",
          customerName: this.queryParams.customerName || "",
        },
      };

      try {
        const response = await GetDataByName(params);
        if (response && response.data) {
          this.defaultData = response.data.list || [];
          this.total = response.data.total || 0;
        } else {
          throw new Error("接口返回数据格式错误");
        }
      } catch (error) {
        console.error("获取数据失败:", error);
        throw error;
      }
    },
    async handleFilter() {
      this.queryParams.pageNum = 1;
      this.loading = true;
      try {
        await this.fetchTableData();
      } catch (error) {
        this.$message.error("查询失败：" + error.message);
      } finally {
        this.loading = false;
      }
    },
    async handlePagination(val) {
      this.loading = true;
      try {
        this.queryParams.pageNum = val.page;
        this.queryParams.pageSize = val.limit;
        await this.fetchTableData();
      } catch (error) {
        this.$message.error("获取数据失败：" + error.message);
      } finally {
        this.loading = false;
      }
    },
    // 获取格式化的日期时间
    getFormattedDateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");
      return `${year}${month}${day}${hours}${minutes}${seconds}`;
    },
    // 导出功能
    async handleExport() {
      try {
        let excelData = [];
        const params = {
          name: "getContractDeliveryStatus",
          returntype: "Map",
          parammaps: {},
        };

        const response = await GetDataByName(params);
        if (response && response.data) {
          excelData = response.data.list || [];
        }

        if (excelData.length === 0) {
          this.$message.warning("暂无数据可导出");
          return;
        }

        // 定义表头
        const headers = [
          "序号",
          "发货状态",
          "客户名称",
          "合同编号",
          "货品名称",
          "订单量",
          "发货量",
          "发货单号",
          "发货时间",
        ];

        // 格式化数据
        const rows = excelData.map((item, index) => [
          index + 1,
          item.deliveryStatusName || "",
          item.customerName || "",
          item.contractNo || "",
          item.productName || "",
          item.orderQuantity || 0,
          item.shippedQuantity || 0,
          item.deliveryNo || "",
          item.deliveryTime || "-",
        ]);

        // 创建工作簿
        const wb = XLSX.utils.book_new();

        // 组合表头和数据
        const wsData = [headers, ...rows];

        // 创建工作表
        const ws = XLSX.utils.aoa_to_sheet(wsData);

        // 设置列宽
        const colWidths = [
          { wch: 8 }, // 序号
          { wch: 12 }, // 发货状态
          { wch: 20 }, // 客户名称
          { wch: 15 }, // 合同编号
          { wch: 30 }, // 货品名称
          { wch: 10 }, // 订单量
          { wch: 10 }, // 发货量
          { wch: 15 }, // 发货单号
          { wch: 20 }, // 发货时间
        ];
        ws["!cols"] = colWidths;

        // 添加工作表到工作簿
        XLSX.utils.book_append_sheet(wb, ws, "发货状态");

        // 生成文件名
        const fileName = `发货状态_${this.getFormattedDateTime()}.xlsx`;

        // 导出文件
        XLSX.writeFile(wb, fileName);

        this.$message.success("导出成功");
      } catch (error) {
        console.error("导出失败:", error);
        this.$message.error("导出失败");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.box-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  margin-top: 24px;
  min-height: 200px;
  height: auto;

  .header-container {
    margin-bottom: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left {
      display: flex;
      align-items: center;
      min-width: 200px;

      .title {
        font-size: 13px;
        color: #333;
      }

      .update-time {
        margin-left: 8px;
        font-size: 13px;
        color: #666;
      }
    }

    .right {
      flex: 1;
      display: flex;
      justify-content: flex-start;
      padding-left: 40px;

      .filter-group {
        display: flex;
        align-items: center;

        .filter-item {
          margin-left: 8px;
          &:first-child {
            margin-left: 0;
          }
        }

        .search-btn {
          font-size: 12px;
          border-radius: 3px;
          background: linear-gradient(to right, #409eff, #3a8ee6);
          border: none;
          transition: all 0.3s ease;

          &:hover {
            background: linear-gradient(to right, #66b1ff, #409eff);
            transform: translateY(-1px);
          }

          &:active {
            transform: translateY(0);
          }
        }
      }
    }
  }

  :deep(.el-card__body) {
    padding: 15px;
  }

  :deep(.el-select .el-input__inner) {
    height: 32px;
    line-height: 32px;
  }

  :deep(.el-input__inner) {
    height: 32px;
    line-height: 32px;
    font-size: 12px;
  }
}

.table-container {
  position: relative;
}

:deep(.el-table) {
  font-size: 12px;

  .el-table__header-wrapper {
    position: sticky;
    top: 0;
    z-index: 1;
  }

  .el-table__header th {
    padding: 8px 0;
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 500;
  }

  .el-table__body td {
    padding: 8px 0;
  }

  .el-table__body tr:hover > td {
    background-color: #f5f7fa !important;
  }
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }
  &::-webkit-scrollbar-thumb {
    border-radius: 3px;
    background: #c0c4cc;
  }
  &::-webkit-scrollbar-track {
    border-radius: 3px;
    background: #f5f7fa;
  }
}
</style>
