<template>
  <div class="project-progress-container">
    <!-- 左侧固定列表格 -->
    <div class="left-section">
      <h3 class="mb20 ml10 textl">人员项目表</h3>
      <div class="user-select-container">
        <span>选择人员</span>
        <el-input v-model="selectedUserName" placeholder="请选择用户" readonly @click="openUserSelectDialog"></el-input>
      </div>
      <CustomTable
        :columns="fixedColumns"
        :tableData="executionData"
        :showPagination="false"
        :maxHeight="tableHeight"
        :showSummary="true"
        :summaryMethod="getFixedColumnsSummaries"
        :border="true"
      >
        <template #name="{ row }">
          <span class="project-name" @click="goToDetail(row)">{{ row.name }}</span>
        </template>
      </CustomTable>
    </div>

    <!-- 右侧滚动列表格 -->
    <div class="right-section">
      <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="结束日期"
          @change="handleDateRangeChange"
        />
      </div>
      <CustomTable
        :columns="scrollableColumns"
        :tableData="executionData"
        :showPagination="false"
        :maxHeight="tableHeight"
        :showSummary="true"
        :summaryMethod="getScrollableColumnsSummaries"
      />
    </div>

    <!-- 用户选择对话框 -->
    <SelectUser
      v-model:dialogVisible="userSelectDialogVisible"
      :multiSelect="false"
      :currentSelectedUser="selectedUser ? [selectedUser] : []"
      @confirm="handleUserSelect"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import CustomTable from '@/components/CustomTable.vue'
import SelectUser from '@/components/selectUser.vue'

const router = useRouter()

const dateRange = ref(getDefaultDateRange())
const tableHeight = ref('100%')
const userSelectDialogVisible = ref(false)
const selectedUser = ref(null)
const selectedUserName = computed(() => (selectedUser.value ? selectedUser.value.name : ''))

function getDefaultDateRange() {
  const now = new Date()
  const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
  const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0)
  return [startOfMonth, endOfMonth]
}

const fixedColumns = [
  { prop: 'name', label: '项目', slot: 'name' },
  { prop: 'presetDays', label: '统计工时\n（天）' },
]

const scrollableColumns = computed(() => {
  if (dateRange.value && dateRange.value.length === 2) {
    const start = new Date(dateRange.value[0])
    const end = new Date(dateRange.value[1])
    const days = []
    for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
      const dayOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][d.getDay()]
      const dateStr = `${d.getMonth() + 1}/${d.getDate()}`
      days.push({
        prop: dateStr,
        label: `${dayOfWeek}\n${dateStr}`,
        minWidth: 100,
      })
    }
    return days
  }
  return []
})

const executionData = computed(() => {
  const projectList = [
    { id: 1, name: '项目1', presetDays: 20 },
    { id: 2, name: '项目2', presetDays: 20 },
    { id: 3, name: '项目3', presetDays: 20 },
    { id: 4, name: '项目4', presetDays: 20 },
    { id: 5, name: '项目5', presetDays: 20 },
  ]

  return projectList.map(project => {
    const data = {
      ...project,
    }
    if (dateRange.value && dateRange.value.length === 2) {
      const start = new Date(dateRange.value[0])
      const end = new Date(dateRange.value[1])
      for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
        const dateStr = `${d.getMonth() + 1}/${d.getDate()}`
        data[dateStr] = Math.floor(Math.random() * 8) // 随机生成0-8的工时据
      }
    }
    return data
  })
})

const handleDateRangeChange = () => {
  // 日期范围变化时，可以在这里添加额外的逻辑
}

const getFixedColumnsSummaries = param => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计工时（天）'
      return
    }
    const values = data.map(item => Number(item[column.property]))
    if (!values.every(value => isNaN(value))) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
      sums[index] = Number(sums[index].toFixed(2))
    } else {
      sums[index] = ''
    }
  })
  return sums
}

const getScrollableColumnsSummaries = param => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    const values = data.map(item => Number(item[column.property]))
    if (!values.every(value => isNaN(value))) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
      sums[index] = Number(sums[index].toFixed(2))
    } else {
      sums[index] = ''
    }
  })
  return sums
}

const updateTableHeight = () => {
  nextTick(() => {
    const container = document.querySelector('.project-execution-table')
    if (container) {
      const containerHeight = container.clientHeight
      const otherElementsHeight =
        container.querySelector('h2').offsetHeight + container.querySelector('.date-range').offsetHeight
      tableHeight.value = `${containerHeight - otherElementsHeight - 40}px` // 40px for margins and paddings
    }
  })
}

const goToDetail = row => {
  router.push({
    name: 'ProjectDetail',
    params: { id: row.id },
    query: {
      startDate: dateRange.value[0].toISOString().split('T')[0],
      endDate: dateRange.value[1].toISOString().split('T')[0],
    },
  })
}

const openUserSelectDialog = () => {
  userSelectDialogVisible.value = true
}

const handleUserSelect = users => {
  if (users.length > 0) {
    selectedUser.value = users[0]
  } else {
    selectedUser.value = null
  }
}

onMounted(() => {
  window.addEventListener('resize', updateTableHeight)
  updateTableHeight()
})

onUnmounted(() => {
  window.removeEventListener('resize', updateTableHeight)
})
</script>

<style scoped>
.project-progress-container {
  display: flex;
  height: 88vh;
  background-color: white;
}

.left-section,
.right-section {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.left-section {
  width: 400px; /* 根据固定列的总宽度调整 */
  padding-top: 34px;
  padding-bottom: 20px;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.5); /* 添加右侧阴影 */
  z-index: 1; /* 确保左侧在右侧之上 */
  margin-right: 5px;
  position: relative;
}

.right-section {
  flex: 1;
  overflow-x: auto;
  padding: 20px;
  padding-left: 0; /* 移除左侧内边距，与左侧部分紧密相连 */
}

.placeholder-header {
  height: 102px; /* 与左侧表格的标题和日期选择器高度一致 */
}

.date-range {
  margin-bottom: 20px;
}

:deep(.el-table) {
  /* border: 1px solid #dcdfe6; */
  height: 100% !important;
}

:deep(.el-table__header th) {
  background-color: #4a4a4a;
  color: white;
  text-align: center;
}

:deep(.el-table__body td) {
  text-align: center;
}

:deep(.el-table__footer td) {
  background-color: #f5f7fa;
  font-weight: bold;
  text-align: center; /* 确保合计行内容居中 */
}

:deep(.el-table__header .cell),
:deep(.el-table__body .cell),
:deep(.el-table__footer .cell) {
  white-space: pre-wrap;
  line-height: 1.2;
  padding: 8px 0;
}

:deep(.el-table__body-wrapper) {
  overflow-x: hidden;
}

/* 确保两个表格的高度一致 */
.left-section :deep(.el-table),
.right-section :deep(.el-table) {
  height: 100% !important;
}

/* 调整日期选择器样式 */
:deep(.el-date-editor) {
  width: 100%;
}

/* 调整表���内容的字体大小 */
:deep(.el-table) {
  font-size: 14px;
}

/* 调整表头的样式 */
:deep(.el-table__header-wrapper) {
  background-color: #f5f7fa;
}
.rightTab :deep(.el-table__header th) {
  background-color: #fff;
}
:deep(.el-table__header th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

/* 调整合计行的样式 */
:deep(.el-table__footer-wrapper) {
  background-color: #f5f7fa;
}

:deep(.el-table__footer td) {
  background-color: #f5f7fa !important;
  font-weight: bold;
  color: #606266;
}

.date-range-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  width: 500px;
  margin-left: 20px;
}

.date-range-label {
  white-space: nowrap;
  margin-right: 10px;
}

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

.user-select-container {
  position: absolute;
  top: 25px;
  right: 10px;
  width: 220px;
  z-index: 2;
  display: flex;
  align-items: center;
  flex-direction: row;
  gap:10px;
  span{
    width: 100px;
  }
}
</style>
