<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 style="display: flex; gap: 16px">
          <el-button
            type="text"
            title="刷新"
            icon="el-icon-refresh"
            @click="handleRefresh"
            style="padding: 0; font-size: 16px; color: #909399"
          />
          <el-button
            type="text"
            title="导出"
            icon="el-icon-download"
            @click="handleExport"
            style="padding: 0; font-size: 16px; color: #909399"
          />
        </div>
      </div>
    </div>
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        size="small"
        :height="tableData.length > 10 ? 450 : null"
        :header-cell-style="{ background: '#f5f7fa' }"
        @sort-change="handleSortChange"
      >
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column
          prop="orderNo"
          label="服务单号"
          min-width="120"
          align="center"
          sortable
        >
          <template slot-scope="scope">
            <span class="order-no-text" @click="handleView(scope.row)">
              {{ scope.row.orderNo }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="customerName"
          label="客户名称"
          min-width="150"
          align="center"
          sortable
        />
        <el-table-column
          prop="projectName"
          label="项目名称"
          min-width="110"
          align="center"
          sortable
        />
        <el-table-column
          prop="goodsName"
          label="货品名称"
          min-width="110"
          align="center"
          sortable
        />
        <el-table-column
          prop="serviceStaffNames"
          label="服务人员"
          width="150"
          align="center"
        >
          <template slot-scope="scope">
            <div class="product-tags">
              <template v-if="scope.row.serviceStaffNames">
                <el-tag
                  v-for="(item, index) in scope.row.serviceStaffNames.split(
                    ','
                  )"
                  :key="index"
                  size="mini"
                  :type="['success', 'warning', 'danger', 'primary'][index % 4]"
                  effect="light"
                  :class="{ 'long-text': item.length > 10 }"
                >
                  {{ item }}
                </el-tag>
              </template>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="statusName"
          label="单据状态"
          width="110"
          sortable
          align="center"
        >
          <template slot-scope="scope">
            <el-tag
              :type="getStatusType(scope.row.statusName)"
              size="mini"
              effect="plain"
            >
              {{ scope.row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="progress"
          label="进度"
          width="250"
          align="center"
        >
          <template slot-scope="scope">
            <div class="progress-wrapper">
              <div class="progress-container">
                <div class="progress-bar">
                  <div class="custom-progress">
                    <div
                      class="progress-inner"
                      :style="{
                        width: Math.min(Math.round(scope.row.rate), 100) + '%',
                        backgroundColor: getProgressColor(scope.row.statusName),
                      }"
                    >
                      <span
                        class="progress-text"
                        v-if="scope.row.shippedQuantity > 0"
                      >
                        {{ scope.row.shippedQuantity }}
                      </span>
                    </div>
                    <span class="total-text">
                      {{
                        scope.row.rate === 0
                          ? scope.row.orderQuantity
                          : scope.row.orderQuantity
                      }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="orderQuantity" label="计划量" align="center" />
        <el-table-column
          prop="shippedQuantity"
          label="已完成量"
          align="center"
        />
        <el-table-column
          prop="unshippedQuantity"
          label="未完成量"
          align="center"
        />
        <el-table-column
          prop="yesterdayFinished"
          label="昨日完成量"
          align="center"
        />
        <el-table-column
          prop="todayFinished"
          label="今日完成量"
          align="center"
        />
        <el-table-column prop="rate" label="完成率" align="center">
          <template slot-scope="scope">
            {{ parseInt(scope.row.rate) + "%" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="remainingDays"
          label="距离完成时间还剩"
          width="130"
          align="center"
        >
          <template slot-scope="scope">
            <template
              v-if="
                scope.row.remainingTime !== null &&
                scope.row.remainingTime !== undefined
              "
            >
              <span
                :class="{
                  'normal-time':
                    scope.row.remainingTime > 3 && !scope.row.earlyDays,
                  'warning-time':
                    scope.row.remainingTime >= 0 &&
                    scope.row.remainingTime <= 3 &&
                    !scope.row.earlyDays,
                  'overdue-time':
                    (scope.row.remainingTime < 0 && !scope.row.earlyDays) ||
                    (scope.row.earlyDays && scope.row.earlyDays < 0),
                  'early-time': scope.row.earlyDays && scope.row.earlyDays > 0,
                }"
              >
                <template
                  v-if="
                    scope.row.earlyDays !== null &&
                    scope.row.earlyDays !== undefined
                  "
                >
                  <template v-if="scope.row.earlyDays > 0">
                    提前 {{ scope.row.earlyDays }} 天完成
                  </template>
                  <template v-else-if="scope.row.earlyDays < 0">
                    延期 {{ Math.abs(scope.row.earlyDays) }} 天完成
                  </template>
                  <template v-else> 按时完成 </template>
                </template>
                <template v-else>
                  <template v-if="scope.row.remainingTime < 0">
                    已逾期 {{ Math.abs(scope.row.remainingTime) }} 天
                  </template>
                  <template v-else> {{ scope.row.remainingTime }} 天 </template>
                </template>
              </span>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <view-dialog
      :visible.sync="dialogVisible"
      :row-data="currentRow"
      :installer-options="personnelOptions"
      :project-options="projectOptions"
      :check-button-permission="() => false"
      :is-current-user-in-service-staff="() => false"
    />
  </el-card>
</template>

<script>
import * as XLSX from "xlsx";
// import { getInstallationList, getUnassignedCount } from '@/api/productManagement/installation' // 后续需要添加此API
import { GetDataByName, GetDataByNames } from "@/api/common";
import ViewDialog from "@/views/productManagement/installationOrder/components/ViewDialog.vue";

export default {
  name: "InstallationTable",
  components: {
    ViewDialog,
  },
  props: {
    tableData: {
      type: Array,
      required: true,
    },
    updateTime: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      loading: false,
      isExpanded: false,
      localTableData: [], // 本地数据
      sortConfig: {
        prop: "", // 排序的字段
        order: "", // 排序的方向
      },
      // 示例数据
      defaultData: [],
      dialogVisible: false,
      currentRow: null,
      personnelOptions: [],
      projectOptions: [],
    };
  },
  computed: {
    displayData() {
      // 如果props中的tableData为空，使用默认数据
      let data =
        this.tableData.length > 0 ? [...this.tableData] : [...this.defaultData];

      // 应用排序
      if (this.sortConfig.prop && this.sortConfig.order) {
        const { prop, order } = this.sortConfig;
        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 this.isExpanded ? data : data.slice(0, 10);
    },
  },
  created() {
    this.initData();
  },
  methods: {
    getStatusType(statusName) {
      const statusMap = {
        未接单: "info",
        处理中: "primary",
        已完成: "success",
        已完成未验收: "warning",
        接单驳回: "danger",
      };
      return statusMap[statusName] || "info";
    },
    getProgressColor(statusName) {
      // 根据状态返回对应的颜色
      const statusColorMap = {
        未接单: "#909399", // 灰色
        处理中: "#409eff", // 蓝色
        已完成未验收: "#e6a23c", // 橙色
        已完成: "#67c23a", // 绿色
        接单驳回: "#f56c6c", // 红色
      };

      return statusColorMap[statusName] || "#909399";
    },
    async initData() {
      this.defaultData = this.tableData;
    },
    handleSortChange({ prop, order }) {
      this.sortConfig = { prop, order };
    },
    // 获取格式化的日期时间
    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 {
        if (this.tableData.length === 0) {
          this.$message.warning("暂无数据可导出");
          return;
        }

        // 定义表头
        const headers = [
          "客户名称",
          "项目名称",
          "货品名称",
          "服务人员",
          "单据状态",
          "进度",
          "计划量",
          "已完成量",
          "未完成量",
          "昨日完成量",
          "今日完成量",
          "完成率",
          "距离完成时间还剩",
        ];

        // 格式化数据
        const rows = this.tableData.map((item) => [
          item.customerName || "",
          item.projectName || "",
          item.goodsName || "",
          item.serviceStaffNames || "",
          item.statusName || "",
          item.rate ? `${parseInt(item.rate)}%` : "0%",
          item.orderQuantity || 0,
          item.shippedQuantity || 0,
          item.unshippedQuantity || 0,
          item.yesterdayFinished || 0,
          item.todayFinished || 0,
          `${parseInt(item.rate)}%`,
          this.formatRemainingTime(item),
        ]);

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

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

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

        // 设置列宽
        const colWidths = [
          { wch: 20 }, // 客户名称
          { wch: 15 }, // 项目名称
          { wch: 30 }, // 货品名称
          { wch: 15 }, // 服务人员
          { wch: 12 }, // 单据状态
          { wch: 10 }, // 进度
          { wch: 10 }, // 计划量
          { wch: 10 }, // 已完成量
          { wch: 10 }, // 未完成量
          { wch: 12 }, // 昨日完成量
          { wch: 12 }, // 今日完成量
          { wch: 10 }, // 完成率
          { 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("导出失败");
      }
    },

    // 格式化剩余时间
    formatRemainingTime(row) {
      if (row.remainingTime === null || row.remainingTime === undefined) {
        return "";
      }

      if (row.earlyDays !== null && row.earlyDays !== undefined) {
        if (row.earlyDays > 0) {
          return `提前 ${row.earlyDays} 天完成`;
        } else if (row.earlyDays < 0) {
          return `延期 ${Math.abs(row.earlyDays)} 天完成`;
        } else {
          return "按时完成";
        }
      } else {
        if (row.remainingTime < 0) {
          return `已逾期 ${Math.abs(row.remainingTime)} 天`;
        } else {
          return `${row.remainingTime} 天`;
        }
      }
    },
    async getUpdateTime() {
      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");
      return `${month}/${day} ${hours}:${minutes}:${seconds}更新`;
    },
    async handleRefresh() {
      try {
        this.loading = true;
        // 调用获取数据的接口
        const send_select_list = {
          name: "getInstallOrderOverview",
          parammaps: {},
        };

        const response = await GetDataByName(send_select_list);
        // 使用 emit 更新父组件的数据
        this.$emit("update:tableData", response.data.list || []);

        // 更新时间
        const newUpdateTime = await this.getUpdateTime();
        this.$emit("update:updateTime", newUpdateTime);

        this.$message.success("刷新成功");
      } catch (error) {
        console.error("刷新失败:", error);
        this.$message.error("刷新失败");
      } finally {
        this.loading = false;
      }
    },
    async handleView(row) {
      this.currentRow = row;
      this.dialogVisible = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.box-card {
  margin-bottom: 20px;
}

.table-container {
  position: relative;
}

// .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;
    align-items: center;
    justify-content: center;

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

      .custom-progress {
        width: 100%;
        height: 12px;
        background-color: #ebeef5;
        border-radius: 100px;
        overflow: visible;
        position: relative;

        .progress-inner {
          height: 100%;
          transition: all 0.3s ease;
          border-radius: 100px;
          position: relative;

          .progress-text {
            position: absolute;
            right: 6px;
            top: 50%;
            transform: translateY(-50%);
            color: #fff;
            font-size: 10px;
            line-height: 1;
            text-shadow: 0 0 1px rgba(0, 0, 0, 0.2);
            white-space: nowrap;
          }
        }

        .total-text {
          position: absolute;
          right: 6px;
          top: 50%;
          transform: translateY(-50%);
          color: #606266;
          font-size: 10px;
          line-height: 1;
          white-space: nowrap;
        }
      }
    }
  }
}

: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;
  }

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

  // 添加表格行的hover效果
  .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;
  }
}

:deep(.normal-time) {
  color: #606266;
  font-size: 13px;
}

:deep(.warning-time) {
  color: #f56c6c;
  font-size: 15px;
  font-weight: bold;
}

:deep(.overdue-time) {
  color: #f56c6c;
  font-size: 15px;
  font-weight: bold;
}

:deep(.early-time) {
  color: #67c23a;
  font-size: 15px;
  font-weight: bold;
}

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

.el-button [class*="el-icon-"] + span {
  margin-left: 0;
}

.el-button--text {
  &:hover {
    color: #409eff !important;
  }
  &:focus {
    color: #909399;
  }
}

.order-no-text {
  color: #409eff;
  cursor: pointer;
  &:hover {
    text-decoration: underline;
  }
}
</style>
