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

    <!-- 顶部统计卡片 -->
    <statistics-panel />
    <!-- 服务概况表格 -->
    <!-- <installation-table
      :table-data.sync="tableData"
      :update-time.sync="updateTime"
      @unassigned-click="handleUnassignedOrders"
      @progress-click="handleProgressClick"
    /> -->
    <!-- 使用keep-alive缓存组件 -->
    <keep-alive>
      <div class="table-container">
        <!-- 按订单查询表格 -->
        <order-installation-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 !== 'customer'"
                :loading="isLoading"
                :disabled="isLoading"
                @click="handleManualSwitch('customer')"
              >
                按客户查询
              </el-button>
              <el-button
                type="primary"
                :plain="queryType !== 'staff'"
                :loading="isLoading"
                :disabled="isLoading"
                @click="handleManualSwitch('staff')"
              >
                按人员查询
              </el-button>
            </el-button-group>
          </template>
        </order-installation-table>

        <!-- 按客户查询表格 -->
        <customer-installation-table
          ref="customerTable"
          v-show="queryType === 'customer'"
          :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 !== 'customer'"
                :loading="isLoading"
                :disabled="isLoading"
                @click="handleManualSwitch('customer')"
              >
                按客户查询
              </el-button>
              <el-button
                type="primary"
                :plain="queryType !== 'staff'"
                :loading="isLoading"
                :disabled="isLoading"
                @click="handleManualSwitch('staff')"
              >
                按人员查询
              </el-button>
            </el-button-group>
          </template>
        </customer-installation-table>

        <!-- 按人员查询表格 -->
        <staff-installation-table
          ref="staffTable"
          v-show="queryType === 'staff'"
          :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 !== 'customer'"
                :loading="isLoading"
                :disabled="isLoading"
                @click="handleManualSwitch('customer')"
              >
                按客户查询
              </el-button>
              <el-button
                type="primary"
                :plain="queryType !== 'staff'"
                :loading="isLoading"
                :disabled="isLoading"
                @click="handleManualSwitch('staff')"
              >
                按人员查询
              </el-button>
            </el-button-group>
          </template>
        </staff-installation-table>
      </div>
    </keep-alive>

    <!-- 已安装统计表格 -->
    <!-- <installation-statistics :update-time="updateTime" /> -->

    <!-- 货品安装情况 -->
    <!-- <installation-status-chart @filter-change="handleFilterChange" /> -->
  </div>
</template>

<script>
import StatisticsPanel from "./components/StatisticsPanel";
import OrderInstallationTable from "./components/OrderInstallationTable";
import CustomerInstallationTable from "./components/CustomerInstallationTable";
import StaffInstallationTable from "./components/StaffInstallationTable";
import InstallationStatusChart from "./components/InstallationStatusChart";
import InstallationTable from "./components/InstallationTable";
import { GetDataByName, GetDataByNames } from "@/api/common";

export default {
  name: "InstallationSummary",
  components: {
    StatisticsPanel,
    OrderInstallationTable,
    CustomerInstallationTable,
    StaffInstallationTable,
    InstallationStatusChart,
    InstallationTable,
  },
  data() {
    return {
      currentTime: "",
      updateTime: "",
      dialogVisible: false,
      tableData: [],
      unassignedOrders: [],
      queryType: "order", // 默认按订单查询
      isLoading: false,
      autoSwitchTimer: null, // 自动切换定时器
      switchInterval: 60 * 1000, // 1分钟
      defaultInterval: 60 * 1000, // 1分钟
      manualInterval: 300 * 1000, // 5分钟
      chartData: {
        labels: [
          "智能膜环",
          "智能喷淋",
          "精准阉割",
          "奶牛称重",
          "车载控制器",
          "大屏",
        ],
        datasets: [
          {
            label: "计划量",
            data: [900, 850, 900, 700, 500, 30],
            backgroundColor: "#409EFF",
            order: 2,
          },
          {
            label: "完成量",
            data: [800, 820, 850, 680, 200, 20],
            backgroundColor: "#FF9F43",
            order: 2,
          },
          {
            label: "完成率",
            data: [88.9, 96.5, 94.4, 97.1, 40.0, 66.7],
            type: "line",
            borderColor: "#67C23A",
            borderWidth: 2,
            fill: false,
            yAxisID: "percentage",
            order: 1,
          },
        ],
      },
    };
  },
  created() {
    this.updateCurrentTime();
    setInterval(this.updateCurrentTime, 1000);
    this.getUpdateTime();
    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}`;
    },
    async getUpdateTime() {
      try {
        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}更新`;
      } catch (error) {
        console.error("获取更新时间失败:", error);
      }
    },
    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 getTableData() {
      let apiName = "";
      switch (this.queryType) {
        case "order":
          apiName = "getInstallOrderOverview";
          break;
        case "customer":
          apiName = "getInstallCustomerOverview";
          break;
        case "staff":
          apiName = "getInstallStaffOverview";
          break;
      }

      const send_select_list = {
        name: apiName,
        offset: 0,
        pagecount: 0,
        parammaps: {},
      };

      try {
        console.log(`获取${this.getQueryTypeName(this.queryType)}数据`);
        this.isLoading = true;
        const response = await GetDataByName(send_select_list);
        this.tableData = response.data.list || [];
      } catch (error) {
        console.error("获取表格数据失败:", error);
        this.$message.error("获取表格数据失败");
      } finally {
        this.isLoading = false;
      }
    },
    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);
      const types = ["order", "customer", "staff"];
      const currentIndex = types.indexOf(this.queryType);
      const nextIndex = (currentIndex + 1) % types.length;
      const newType = types[nextIndex];

      await this.switchQueryType(newType);
      this.$message.info(
        `已自动切换到${this.getQueryTypeName(newType)}查询模式，${
          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(
        `已切换到${this.getQueryTypeName(type)}查询模式，${
          this.switchInterval / 1000
        }秒后自动切换`
      );
    },

    // 切换查询类型
    async switchQueryType(type) {
      if (this.queryType === type || this.isLoading) return;

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

      try {
        // 获取对应类型的数据
        await this.getTableData();
      } catch (error) {
        console.error("切换查询类型失败:", error);
        this.$message.error("切换查询类型失败");
      } finally {
        this.isLoading = false;
      }
    },

    // 获取查询类型名称
    getQueryTypeName(type) {
      const typeNames = {
        order: "按订单",
        customer: "按客户",
        staff: "按人员",
      };
      return typeNames[type] || type;
    },

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

    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}更新`;
    },
  },
};
</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;
  }
}

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

  > * {
    transition: opacity 0.2s ease;
  }
}

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