<template>
  <el-card class="box-card">
    <div class="header-container">
      <div class="left">
        <span class="title">服务概况</span>
        <span class="update-time" v-if="updateTime">{{ this.updateTime }}</span>
      </div>
      <div class="right">
        <div class="filter-group">
          <slot name="query-buttons"></slot>
          <el-button
            type="primary"
            size="small"
            :loading="exportLoading"
            @click="handleExport"
          >
            <i class="el-icon-download" />
            导出
          </el-button>
        </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 ViewDialog from "@/views/productManagement/installationOrder/components/ViewDialog.vue";
import { GetDataByName } from "@/api/common";
import * as XLSX from "xlsx";

export default {
  name: "OrderInstallationTable",
  components: {
    ViewDialog,
  },
  // props: {
  //   updateTime: {
  //     type: String,
  //     default: "",
  //   },
  // },
  data() {
    return {
      loading: false,
      exportLoading: false,
      tableData: [],
      dialogVisible: false,
      currentRow: null,
      personnelOptions: [],
      projectOptions: [],
      currentTime: "",
      selectedOrder: null,
      orderLoading: false,
      orderOptions: [],
    };
  },
  created() {
    this.getTableData();
  },
  methods: {
    updateCurrentTime() {
      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");
      const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      this.updateTime = formattedTime;
    },
    async getTableData() {
      try {
        this.loading = true;
        const response = await GetDataByName({
          name: "getInstallOrderOverview",
          offset: 0,
          pagecount: 0,
          parammaps: {},
        });
        if (response.data && response.data.list) {
          this.tableData = response.data.list;
          this.updateCurrentTime();
        }
      } catch (error) {
        console.error("获取数据失败:", error);
        this.$message.error("获取数据失败");
      } finally {
        this.loading = false;
      }
    },
    handleProgressClick(row) {
      this.$emit("progress-click", row);
    },
    handleView(row) {
      this.currentRow = row;
      this.dialogVisible = true;
    },
    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";
    },
    handleSortChange({ prop, order }) {
      // 处理排序逻辑
      console.log("排序变更:", prop, order);
    },
    async handleExport() {
      try {
        this.exportLoading = true;
        const response = await GetDataByName({
          name: "exportInstallOrderOverview",
          offset: 0,
          pagecount: 0,
          parammaps: {},
        });

        if (response.data && response.data.list) {
          const data = response.data.list;
          const header = {
            orderNo: "服务单号",
            customerName: "客户名称",
            projectName: "项目名称",
            goodsName: "货品名称",
            serviceStaffNames: "服务人员",
            statusName: "单据状态",
            orderQuantity: "计划量",
            shippedQuantity: "已完成量",
            unshippedQuantity: "未完成量",
            yesterdayFinished: "昨日完成量",
            todayFinished: "今日完成量",
            rate: "完成率",
            remainingTime: "距离完成时间还剩",
          };

          // 创建工作表
          const ws = XLSX.utils.json_to_sheet([]);
          // 添加表头
          XLSX.utils.sheet_add_json(ws, [header], {
            header: Object.keys(header),
            skipHeader: true,
          });
          // 添加数据
          XLSX.utils.sheet_add_json(ws, data, {
            origin: "A2",
            skipHeader: true,
          });

          // 设置列宽
          const colWidths = Object.keys(header).map(() => ({ wch: 15 }));
          ws["!cols"] = colWidths;

          // 创建工作簿
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, "订单安装概况");

          // 导出文件
          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");
          const timestamp = `${year}${month}${day}${hours}${minutes}${seconds}`;
          XLSX.writeFile(wb, `订单安装概况_${timestamp}.xlsx`);
        }
      } catch (error) {
        console.error("导出失败:", error);
        this.$message.error("导出失败");
      } finally {
        this.exportLoading = false;
      }
    },
  },
};
</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;
  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;
        gap: 10px;
      }
    }
  }
}

.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(.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) {
  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;
  }

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

.order-no-text {
  color: #409eff;
  cursor: pointer;
  &:hover {
    color: #66b1ff;
  }
}

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

  :deep(.el-button) {
    height: 32px;
    padding: 0 15px;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: center;

    .el-icon-download,
    .el-icon-search {
      margin-right: 5px;
    }
  }

  :deep(.el-select) {
    margin-right: 10px;

    .el-input {
      .el-input__inner {
        height: 32px;
        line-height: 32px;
      }
    }
  }
}
</style>
