<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <div>
          <span style="font-size: 13px">生产概况</span>
          <span style="margin-left: 8px; font-size: 13px; color: #666">{{
            updateTime
          }}</span>
        </div>
        <div class="query-buttons">
          <el-button-group>
            <el-button
              type="primary"
              size="small"
              :plain="queryType !== 'order'"
              @click="queryType = 'order'"
            >
              按订单查询
            </el-button>
            <el-button
              type="primary"
              size="small"
              :plain="queryType !== 'product'"
              @click="queryType = 'product'"
            >
              按货品查询
            </el-button>
          </el-button-group>
        </div>
      </div>
    </div>
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="displayData"
        style="width: 100%"
        border
        size="small"
        @sort-change="handleSortChange"
      >
        <!-- 订单编号列 - 仅在订单查询时显示 -->
        <el-table-column
          v-if="queryType === 'order'"
          prop="orderNo"
          label="订单编号"
          width="110"
          align="center"
        />
        <!-- 货品名称列 -->
        <el-table-column
          prop="productName"
          label="货品名称"
          min-width="110"
          align="center"
          sortable="custom"
        />
        <!-- 工序列 - 仅在订单查询时显示 -->
        <el-table-column
          v-if="queryType === 'order'"
          prop="process"
          label="工序"
          width="100"
          align="center"
        />
        <!-- 状态列 -->
        <el-table-column
          prop="status"
          :label="queryType === 'order' ? '单据状态' : '货品状态'"
          width="100"
          align="center"
          sortable="custom"
        >
          <template slot-scope="scope">
            <el-tag
              :type="getStatusType(scope.row.status)"
              size="mini"
              effect="plain"
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 进度列 -->
        <el-table-column
          prop="progress"
          label="进度"
          width="250"
          align="center"
          sortable="custom"
        >
          <template slot-scope="scope">
            <div class="progress-wrapper">
              <div class="progress-container">
                <div class="progress-bar">
                  <el-progress
                    :percentage="(scope.row.progress / scope.row.total) * 100"
                    :stroke-width="8"
                    :show-text="false"
                    :color="getProgressColor(scope.row.status)"
                  />
                </div>
                <div class="progress-info">
                  <span
                    class="finished-number"
                    @click="$emit('progress-click', scope.row)"
                    style="cursor: pointer; color: #409eff; margin-right: 2px"
                  >
                    {{ scope.row.progress }}
                  </span>
                  <span style="color: #909399">/</span>
                  <span
                    class="total-number"
                    style="color: #606266; margin-left: 2px"
                    >{{ scope.row.total }}</span
                  >
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- 计划量列 -->
        <el-table-column
          prop="total"
          label="计划量"
          width="75"
          align="center"
        />
        <!-- 已完成量列 -->
        <el-table-column
          prop="finished"
          label="已完成量"
          width="85"
          align="center"
        />
        <!-- 未完成量列 -->
        <el-table-column
          prop="unfinished"
          label="未完成量"
          width="85"
          align="center"
        />
        <!-- 昨日完成量列 -->
        <el-table-column
          prop="yesterdayFinished"
          label="昨日完成量"
          width="95"
          align="center"
        />
        <!-- 今日完成量列 -->
        <el-table-column
          prop="todayFinished"
          label="今日完成量"
          width="95"
          align="center"
        />
        <!-- 完成率列 -->
        <el-table-column
          prop="rate"
          label="完成率"
          width="100"
          align="center"
          sortable="custom"
        >
          <template slot-scope="scope">
            {{
              ((scope.row.finished / scope.row.total) * 100).toFixed(1) + "%"
            }}
          </template>
        </el-table-column>
        <!-- 生产人员列 - 仅在订单查询时显示 -->
        <el-table-column
          v-if="queryType === 'order'"
          prop="producer"
          label="生产人员"
          width="100"
          align="center"
        />
        <!-- 剩余时间列 - 仅在订单查询时显示 -->
        <el-table-column
          v-if="queryType === 'order'"
          prop="remainingDays"
          label="距离完成时间还剩"
          width="130"
          align="center"
        >
          <template slot-scope="scope">
            <span
              :style="{ color: scope.row.remainingDays < 0 ? '#F56C6C' : '' }"
            >
              {{
                scope.row.remainingDays > 0
                  ? scope.row.remainingDays + "天"
                  : "超期" + Math.abs(scope.row.remainingDays) + "天"
              }}
            </span>
          </template>
        </el-table-column>
      </el-table>
      <div class="expand-button" v-if="tableData.length > 5">
        <el-button
          type="text"
          @click="isExpanded = !isExpanded"
          class="expand-btn"
        >
          <div class="button-content">
            <i :class="['el-icon-arrow-' + (isExpanded ? 'up' : 'down')]"></i>
            <span class="expand-text">{{
              isExpanded ? "收起" : "展开更多"
            }}</span>
          </div>
        </el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
// import { getProductionList, getUnassignedCount } from '@/api/production' // 后续需要添加此API

export default {
  name: "ProductionTable",
  data() {
    return {
      loading: false,
      unassignedCount: 0,
      isExpanded: true,
      queryType: "order", // 查询类型：order-按订单，product-按货品
      localTableData: [], // 本地数据
      sortConfig: {
        prop: "", // 排序的字段
        order: "", // 排序的方向
      },
      // 按货品查询的示例数据
      productDefaultData: [],
      // 原有的按订单查询数据改名为 orderDefaultData
      orderDefaultData: [],
    };
  },
  props: {
    updateTime: {
      type: String,
      required: true,
    },
  },
  computed: {
    tableData() {
      // 根据查询类型返回不同的数据
      const sourceData =
        this.queryType === "order"
          ? this.localTableData.length > 0
            ? this.localTableData
            : this.orderDefaultData
          : this.productDefaultData;

      let data = [...sourceData];

      // 如果有排序配置，进行排序
      if (this.sortConfig.prop && this.sortConfig.order) {
        const { prop, order } = this.sortConfig;
        data = data.sort((a, b) => {
          let aValue = a[prop];
          let bValue = b[prop];

          // 特殊处理完成率字段
          if (prop === "rate") {
            aValue = (a.finished / a.total) * 100;
            bValue = (b.finished / b.total) * 100;
          }

          // 根据排序方向返回比较结果
          if (order === "ascending") {
            return aValue > bValue ? 1 : -1;
          } else {
            return aValue < bValue ? 1 : -1;
          }
        });
      }

      return data;
    },
    displayData() {
      return this.isExpanded ? this.tableData : this.tableData.slice(0, 5);
    },
  },
  created() {
    this.initData();
  },
  methods: {
    getStatusType(status) {
      switch (status) {
        case "进行中":
          return "primary";
        case "已超期":
          return "danger";
        case "未开始":
          return "info";
        default:
          return "info";
      }
    },
    getProgressColor(status) {
      switch (status) {
        case "进行中":
          return "#409EFF";
        case "已超期":
          return "#F56C6C";
        case "未开始":
          return "#909399";
        default:
          return "#909399";
      }
    },
    async initData() {
      try {
        await Promise.all([this.fetchTableData(), this.fetchUnassignedCount()]);
      } catch (error) {
        console.error("初始化数据失败:", error);
      }
    },
    async fetchTableData() {
      try {
        this.loading = true;
        // TODO: 后端接口完成后替换此处
        // const { data } = await getProductionList()
        // this.localTableData = data

        // 模拟接口调用
        await new Promise((resolve) => setTimeout(resolve, 1000));
        this.localTableData = this.orderDefaultData;
      } catch (error) {
        console.error("获取生产列表失败:", error);
        this.$message.error("获取生产列表失败");
      } finally {
        this.loading = false;
      }
    },
    async fetchUnassignedCount() {
      try {
        // TODO: 后端接口完成后替换此处
        // const { data } = await getUnassignedCount()
        // this.unassignedCount = data

        // 模拟接口调用
        await new Promise((resolve) => setTimeout(resolve, 500));
        this.unassignedCount = 7;
      } catch (error) {
        console.error("获取未接单数量失败:", error);
      }
    },
    handleSortChange({ prop, order }) {
      this.sortConfig = { prop, order };
    },
  },
};
</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;

  .el-card__header {
    padding: 16px 20px;
    border-bottom: 1px solid #ebeef5;
  }

  :deep(.el-card__body) {
    padding: 16px;
    transition: all 0.3s ease;
  }

  .query-buttons {
    .el-button-group {
      .el-button {
        padding: 8px 15px;

        &.is-plain {
          &:hover {
            color: #409eff;
            border-color: #c6e2ff;
            background-color: #ecf5ff;
          }
        }
      }
    }
  }
}

.table-container {
  position: relative;
  padding-bottom: 0;
}

.expand-button {
  text-align: center;
  border-top: 1px solid #ebeef5;
  margin-top: -1px;

  .el-button {
    font-size: 13px;
    color: #909399;
    padding: 8px;

    .button-content {
      display: inline-flex;
      align-items: center;
      position: relative;

      i {
        font-size: 12px;
        color: #c0c4cc;
        transition: all 0.3s;
      }

      .expand-text {
        max-width: 0;
        overflow: hidden;
        white-space: nowrap;
        transition: all 0.3s ease-in-out;
        opacity: 0;
      }
    }

    &:hover {
      color: #409eff;

      .button-content {
        i {
          color: #409eff;
          margin-right: 4px;
        }

        .expand-text {
          max-width: 100px;
          opacity: 1;
        }
      }
    }
  }
}

.progress-wrapper {
  padding: 6px 0;

  .progress-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;

    .progress-bar {
      width: 100%;
      padding: 0 12px;
    }

    .progress-info {
      font-size: 12px;
      font-weight: 500;

      .finished-number {
        &:hover {
          opacity: 0.8;
        }
      }
    }
  }
}

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

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

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

  // 添加表格行的hover效果
  .el-table__body tr:hover > td {
    background-color: #f5f7fa !important;
  }
}

// 添加表格内容的过渡效果
:deep(.el-table__body-wrapper) {
  transition: max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
</style>
