<template>
  <div class="project-progress-container">
    <!-- 左侧固定列表格 -->
    <div class="content flex-col">
      <div class="shadowBox"></div>
      <div class="flex-row aic mb20">
        <h2 class="textC">项目执行表</h2>
        <div class="date-range-container">
          <span class="date-range-label">统计时间：</span>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            @change="handleDateRangeChange"
            :clearable="false"
          />
        </div>
      </div>
      <div class="f1">
        <CustomTable
          :columns="fixedColumns"
          :tableData="executionData"
          :showPagination="false"
          :showSummary="true"
          :summaryMethod="getFixedColumnsSummaries"
          tableHeight="600"
        ></CustomTable>
      </div>
    </div>

    <!-- 右侧滚动列表格 -->
  </div>
</template>

<script>
import { projectBank } from "@/utils/api";
import CustomTable from "@/components/CustomTable.vue";

export default {
  components: {
    CustomTable,
  },
  data() {
    return {
      timeRange: [],
      dateRange: this.getDefaultDateRange(),
      fixedColumns: [],
      executionData: [],
    };
  },
  methods: {
    getDefaultDateRange() {
      const startOfMonth = this.moment().startOf("month").format("YYYY-MM-DD");
      const endOfMonth = this.moment().endOf("month").format("YYYY-MM-DD");
      this.timeRange = [startOfMonth, endOfMonth];
      return [startOfMonth, endOfMonth];
    },
    handleDateRangeChange() {
      this.getProjectProgress();
    },
    async getProjectProgress() {
      const res = await projectBank.porjectProgress({
        startDate: this.dateRange[0] + " 00:00:00",
        endDate: this.dateRange[1] + " 00:00:00",
      });
      this.timeRange = [this.dateRange[0], this.dateRange[1]];
      this.executionData = res.data;
    },
    getFixedColumnsSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计工时（天）";
          return;
        }
        let values;
        if (column.property == "detailList") {
          values = data.map((item) => Number(item[column.property][index - 4]));
        } else if (column.property == "projectState") {
          values = [];
        } else {
          values = data.map((item) => Number(item[column.property]));
        }

        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            return !isNaN(value) ? prev + curr : prev;
          }, 0);
          sums[index] = Number(sums[index].toFixed(2));
        } else {
          sums[index] = "";
        }
      });
      return sums;
    },
    goToDetail(row) {
      this.$router.push({
        path: "/project/detail",
        query: {
          id: row.projectId,
        },
      });
    },
    goToUser(row) {
      this.$router.push({
        path: "/projectBank/projectUser",
        query: {
          projectId: row.projectId,
          startDate: this.dateRange[0],
          endDate: this.dateRange[1],
        },
      });
    },
  },
  watch: {
    timeRange: {
      deep: true,
      handler(newVal) {
        const days = [];
        if (newVal && newVal.length === 2) {
          const start = new Date(this.timeRange[0]);
          const end = new Date(this.timeRange[1]);
          for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
            const dayOfWeek = [
              "周日",
              "周一",
              "周二",
              "周三",
              "周四",
              "周五",
              "周六",
            ][d.getDay()];
            const dateStr = `${d.getMonth() + 1}/${d.getDate()}`;
            let index = days.length;
            days.push({
              prop: "detailList",
              label: `${dayOfWeek}\n${dateStr}`,
              minWidth: 100,
              type: "button",
              callback: (data, row) => {
                return `<span style="color:#1686d8;cursor:pointer">${data[index]}</span>`;
              },
              Event: (data, row) => {
                this.goToUser(row);
              },
            });
          }
        }
        this.fixedColumns = [
          {
            prop: "projectName",
            label: "项目",
            type: "button",
            fixed: "left",
            width: 120,
            callback: (data, row) => {
              return `<span style="color:#1686d8;cursor:pointer">${data}</span>`;
            },
            Event: (data, row) => {
              this.goToDetail(row);
            },
          },
          {
            prop: "projectState",
            label: "项目状态",
            type: "button",
            fixed: "left",
            width: 100,
            callback: (value) => {
              let status = "未知";
              let color = "";
              switch (value) {
                case "0":
                  status = "未启动";
                  color = "#909399"; // 灰色
                  break;
                case "1":
                  status = "进行中";
                  color = "#409EFF"; // 蓝色
                  break;
                case "2":
                  status = "已完成";
                  color = "#67C23A"; // 绿色
                  break;
              }
              return `<span style="color: ${color}">${status}</span>`;
            },
          },
          {
            prop: "budgetDate",
            label: "预计工时\n（天）",
            width: 100,
            fixed: "left",
          },
          {
            prop: "allWorkTime",
            label: "统计工时\n（天）",
            width: 100,
            fixed: "left",
          },
          ...days,
        ];
      },
    },
  },
  mounted() {
    this.getProjectProgress();
  },
  beforeDestroy() {},
};
</script>

<style lang="scss" scoped>
.project-progress-container {
  display: flex;
  height: 88vh;
  background-color: white;
  padding: 30px;
  position: relative;
}
.content {
  width: 100%;
}
.placeholder-header {
  height: 102px; /* 与左侧表格的标题和日期选择器高度一致 */
}
.date-range {
  margin-bottom: 20px;
}
::v-deep .el-table {
  max-height: calc(100vh - 260px) !important;
}
::v-deep .el-table__header th {
  background-color: #4a4a4a;
  color: white;
  text-align: center;
}
::v-deep .el-table__body td {
  text-align: center;
}
::v-deep .el-table__footer td {
  background-color: #c0c4cc !important;
  font-weight: bold;
  text-align: center; /* 确保合计行内容居中 */
}
::v-deep .el-table__header .cell,
::v-deep .el-table__body .cell,
::v-deep .el-table__footer .cell {
  white-space: pre-wrap;
  line-height: 1.2;
  padding: 8px 0;
}
::v-deep .el-table__body-wrapper {
  // overflow-x: hidden;
  overflow: auto;
  z-index: 0;
}
/* 确保两个表格的高度一致 */
.left-section ::v-deep .el-table,
.right-section ::v-deep .el-table {
  height: 100% !important;
}
/* 调整日期选择器样式 */
::v-deep .el-date-editor {
  width: 100%;
}
/* 调整表格内容的字体大小 */
::v-deep .el-table {
  font-size: 14px;
}
/* 调整表头的样式 */
::v-deep .el-table__header-wrapper {
  background-color: #f5f7fa;
}
.rightTab ::v-deep .el-table__header th {
  background-color: #fff;
}
::v-deep .el-table__header th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}
/* 调整合计行的样式 */
::v-deep .el-table__footer-wrapper {
  // bottom: 0;
  // position: absolute;
  // font-weight: bold;
  color: #606266;
}

.date-range-container {
  display: flex;
  align-items: center;
  width: 500px;
  margin-left: 350px;
}
.date-range-label {
  white-space: nowrap;
  margin-right: 10px;
}
::v-deep .el-date-editor.el-input__wrapper {
  flex: 1;
}
.custom-table {
  height: 100%;
}
.project-name {
  cursor: pointer;
  color: #409eff;
}
.project-name:hover {
  text-decoration: underline;
}
::v-deep thead .el-table-fixed-column--left {
  background: #d7d7d7 !important;
}
::v-deep .el-table__fixed {
  box-shadow: 5px 20px 20px rgba(7, 7, 7, 0.5) !important;


}
.shadowBox {
  // position: absolute;
  // box-shadow: 2px 10px 10px 2px rgba(7, 7, 7, 0.8) !important;
  // width: 1px;
  // height: 95%;
  // left: 450px;
  // z-index: 100;
}
</style>
