<template>
  <div class="app-container">
    <!-- 顶部标题栏 -->
    <div class="page-header">
      <div class="page-title">生产总览</div>
      <div class="page-time">时间：{{ currentTime }}</div>
    </div>

    <!-- 顶部统计卡片 -->
    <statistics-panel :statistics-data="statisticsPanelData" />

    <!-- 使用keep-alive缓存组件 -->
    <keep-alive>
      <div class="table-container">
        <!-- 使用v-show替代v-if -->
        <order-production-table
          ref="orderTable"
          v-show="queryType === 'order'"
          :update-time="updateTime"
          @progress-click="handleProgressClick"
          @data-loaded="handleDataLoaded"
        >
          <template #query-buttons>
            <el-button-group>
              <el-button
                type="primary"
                :plain="queryType !== 'order'"
                :loading="isLoading"
                :disabled="isLoading"
                @click="handleManualSwitch('order')"
              >
                按订单查询
              </el-button>
              <el-button
                type="primary"
                :plain="queryType !== 'product'"
                :loading="isLoading"
                :disabled="isLoading"
                @click="handleManualSwitch('product')"
              >
                按货品查询
              </el-button>
            </el-button-group>
          </template>
        </order-production-table>

        <!-- 按货品查询表格 -->
        <product-production-table
          ref="productTable"
          v-show="queryType === 'product'"
          :update-time="updateTime"
          @progress-click="handleProgressClick"
          @data-loaded="handleDataLoaded"
        >
          <template #query-buttons>
            <el-button-group>
              <el-button
                type="primary"
                :plain="queryType !== 'order'"
                :loading="isLoading"
                :disabled="isLoading"
                @click="handleManualSwitch('order')"
              >
                按订单查询
              </el-button>
              <el-button
                type="primary"
                :plain="queryType !== 'product'"
                :loading="isLoading"
                :disabled="isLoading"
                @click="handleManualSwitch('product')"
              >
                按货品查询
              </el-button>
            </el-button-group>
          </template>
        </product-production-table>
      </div>
    </keep-alive>
    <!-- 发货状态表格 -->
    <delivery-status-table />
    <!-- 货品生产情况 -->
    <!-- <production-status-chart
      :chart-data="chartData"
      @filter-change="handleFilterChange"
    />-->
  </div>
</template>

<script>
import StatisticsPanel from "./components/StatisticsPanel";
import OrderProductionTable from "./components/OrderProductionTable.vue";
import ProductProductionTable from "./components/ProductProductionTable.vue";
import DeliveryStatusTable from "./components/DeliveryStatusTable.vue";
import { GetDataByName, GetDataByNames } from "@/api/common";

export default {
  name: "ProductionSummary",
  components: {
    StatisticsPanel,
    OrderProductionTable,
    ProductProductionTable,
    DeliveryStatusTable,
  },
  data() {
    return {
      currentTime: "",
      updateTime: "",
      dialogVisible: false,
      statisticsPanelData: [],
      queryType: "order", // 默认按订单查询
      isLoading: false,
      autoSwitchTimer: null, // 自动切换定时器
      switchInterval: 60 * 1000, // 1分钟
      defaultInterval: 60 * 1000, // 1分钟
      manualInterval: 300 * 1000, // 5分钟
    };
  },
  created() {
    this.updateCurrentTime();
    setInterval(this.updateCurrentTime, 1000);
    this.getTableData();
    console.log("开始自动切换，间隔：", this.switchInterval);
    this.startAutoSwitch();
  },
  beforeDestroy() {
    console.log("组件销毁，清除定时器");
    this.clearAutoSwitch();
  },
  methods: {
    updateCurrentTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = (now.getMonth() + 1).toString().padStart(2, "0");
      const day = now.getDate().toString().padStart(2, "0");
      const hours = now.getHours().toString().padStart(2, "0");
      const minutes = now.getMinutes().toString().padStart(2, "0");
      const seconds = now.getSeconds().toString().padStart(2, "0");
      this.currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    handleDataLoaded() {
      // 数据加载完成后更新时间
      const now = new Date();
      const month = (now.getMonth() + 1).toString().padStart(2, "0");
      const day = now.getDate().toString().padStart(2, "0");
      const hours = now.getHours().toString().padStart(2, "0");
      const minutes = now.getMinutes().toString().padStart(2, "0");
      const seconds = now.getSeconds().toString().padStart(2, "0");
      this.updateTime = `${month}/${day} ${hours}:${minutes}:${seconds}更新`;
    },
    handleUnassignedOrders() {
      this.getUnassignedOrders();
      this.dialogVisible = true;
    },
    async getUnassignedOrders() {
      try {
        console.log("获取未接单数据");
      } catch (error) {
        console.error("获取未接单数据失败:", error);
        this.$message.error("获取未接单数据失败");
      }
    },
    handleProgressClick(row) {
      console.log("进度条被点击:", row);
    },
    async switchQueryType(type) {
      if (this.queryType === type || this.isLoading) return;

      console.log("切换查询类型到：", type);
      this.isLoading = true;
      this.queryType = type;

      try {
        // 获取统计面板数据
        //await this.getTableData();

        // 使用ref刷新对应表格数据
        await this.$nextTick();
        if (type === "order" && this.$refs.orderTable?.initData) {
          await this.$refs.orderTable.initData();
        } else if (type === "product" && this.$refs.productTable?.initData) {
          await this.$refs.productTable.initData();
        }
      } catch (error) {
        console.error("切换查询类型失败:", error);
        this.$message.error("切换查询类型失败");
      } finally {
        this.isLoading = false;
      }
    },
    async getTableData() {
      const send_select_list = [
        {
          name: "getStatisticsPanelNumsOfProduction",
          offset: 0,
          pagecount: 0,
          parammaps: {},
        },
        // {
        //   name: "getDictListSelect",
        //   offset: 0,
        //   pagecount: 0,
        //   parammaps: {
        //     pid: "79",
        //   },
        // },
        // {
        //   name: "getInstallationOrderToDoNum",
        //   offset: 0,
        //   pagecount: 0,
        //   parammaps: {},
        // },
      ];

      try {
        const response = await GetDataByNames(send_select_list);
        this.statisticsPanelData =
          response.data.getStatisticsPanelNumsOfProduction.list || [];
      } catch (error) {
        console.error("获取数据失败:", error);
        throw error;
      }
    },
    handleFilterChange({ month, product }) {
      console.log("筛选条件变更:", month, product);
      this.getChartData(month, product);
    },
    async getChartData(month, product) {
      try {
        console.log("获取图表数据:", month, product);
      } catch (error) {
        console.error("获取图表数据失败:", error);
        this.$message.error("获取图表数据失败");
      }
    },
    // 开始自动切换
    startAutoSwitch() {
      console.log("启动自动切换定时器");
      this.clearAutoSwitch();
      this.autoSwitchTimer = setInterval(() => {
        console.log("触发自动切换");
        this.handleAutoSwitch();
      }, this.switchInterval);
    },

    // 清除自动切换定时器
    clearAutoSwitch() {
      if (this.autoSwitchTimer) {
        console.log("清除现有定时器");
        clearInterval(this.autoSwitchTimer);
        this.autoSwitchTimer = null;
      }
    },

    // 处理自动切换
    async handleAutoSwitch() {
      console.log("执行自动切换，当前类型：", this.queryType);
      let newType;
      switch (this.queryType) {
        case "order":
          newType = "product";
          break;
        case "product":
          newType = "order";
          break;
        default:
          newType = "order";
      }

      await this.switchQueryType(newType);
      this.$message.info(
        `已自动切换到${newType === "order" ? "按订单" : "按货品"}查询模式，${
          this.switchInterval / 1000
        }秒后下次切换`
      );
    },

    // 处理手动切换
    async handleManualSwitch(type) {
      if (this.queryType === type || this.isLoading) return;

      console.log("手动切换到：", type);
      this.switchInterval = this.manualInterval;
      this.clearAutoSwitch();
      this.startAutoSwitch();

      await this.switchQueryType(type);
      this.$message.success(
        `已切换到${type === "order" ? "按订单" : "按货品"}查询模式，${
          this.switchInterval / 1000
        }秒后自动切换`
      );
    },

    // 重置切换间隔
    resetSwitchInterval() {
      console.log("重置切换间隔");
      this.switchInterval = this.defaultInterval;
      this.clearAutoSwitch();
      this.startAutoSwitch();
      this.$message.info(`已重置为${this.switchInterval / 1000}秒自动切换`);
    },

    // 处理搜索
    handleSearch() {
      // 根据currentQueryType执行不同的搜索逻辑
      if (this.queryType === "order") {
        this.searchByOrder();
      } else {
        this.searchByGoods();
      }
    },

    // 按订单搜索
    searchByOrder() {
      // 实现按订单搜索的逻辑
      console.log("执行按订单搜索");
    },

    // 按货品搜索
    searchByGoods() {
      // 实现按货品搜索的逻辑
      console.log("执行按货品搜索");
    },
  },
};
</script>

<style lang="scss" scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
  border-radius: 8px;
  transition: all 0.3s ease;

  .page-title {
    font-size: 20px;
    font-weight: 600;
    color: #1f2d3d;
    position: relative;
    padding-left: 16px;

    &::before {
      content: "";
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 22px;
      background: #409eff;
      border-radius: 4px;
    }
  }

  .page-time {
    color: #606266;
    font-size: 14px;
  }
}

// 添加按钮组样式
:deep(.el-button-group) {
  .el-button {
    padding: 8px 16px;
    font-size: 13px;
    border-radius: 4px;
    transition: all 0.3s ease;

    &:first-child {
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;
    }

    &:last-child {
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
    }

    &:not(.is-plain) {
      background: linear-gradient(135deg, #409eff 0%, #3a8ee6 100%);
      border-color: #3a8ee6;
      box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);

      &:hover {
        background: linear-gradient(135deg, #66b1ff 0%, #409eff 100%);
        border-color: #409eff;
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
      }
    }

    &.is-plain {
      color: #409eff;
      background: #ecf5ff;
      border-color: #b3d8ff;

      &:hover {
        color: #fff;
        background: linear-gradient(135deg, #66b1ff 0%, #409eff 100%);
        border-color: #409eff;
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
      }
    }

    &[disabled] {
      cursor: not-allowed;
      opacity: 0.7;
      &:hover {
        transform: none;
        box-shadow: none;
      }
    }
  }
}

// 添加表格切换动画
.app-container {
  .el-card {
    animation: fadeInScale 0.3s ease-out;
  }
}

@keyframes fadeInScale {
  from {
    opacity: 0;
    transform: scale(0.98);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.table-container {
  position: relative;
  margin-bottom: 24px;
}

// 添加切换动画
.table-container {
  > * {
    transition: opacity 0.2s ease;
  }
}

.production-summary {
  .query-section {
    margin-bottom: 20px;

    .query-type-buttons {
      margin-bottom: 15px;

      .el-button-group {
        .el-button {
          padding: 8px 20px;

          &.el-button--primary {
            background-color: #409eff;
            border-color: #409eff;
            color: #fff;

            &:hover {
              background-color: #66b1ff;
              border-color: #66b1ff;
            }
          }

          &.el-button--default {
            &:hover {
              color: #409eff;
              border-color: #c6e2ff;
              background-color: #ecf5ff;
            }
          }
        }
      }
    }
  }
}
</style>
