<template>
  <div class="work-log-container">
    <!-- 左侧项目列表 -->
    <div class="project-list" :class="{ collapsed: isCollapsed }">
      <div class="list-header">
        <span v-if="!isCollapsed">项目列表</span>
        <div class="collapse-button-wrapper">
          <el-button type="text" @click="toggleCollapse" class="collapse-button">
            <el-icon :size="20">
              <ArrowLeft v-if="!isCollapsed" />
              <ArrowRight v-else />
            </el-icon>
          </el-button>
        </div>
      </div>
      <CustomTable
        v-show="!isCollapsed"
        :columns="[
          { prop: 'name', label: '项目', align: 'center' },
          { prop: 'workDay', label: '工时（天）', align: 'center' },
        ]"
        :tableData="projectList"
        @row-click="handleProjectClick"
        :show-summary="true"
        :summary-method="getSummaries"
        sum-text="合计工时（h）"
        :showPagination="false"
        :highligt="true"
        ref="projectRef"
      />
    </div>

    <!-- 右侧项目信息和日历 -->
    <div class="project-info-calendar">
      <h2 class="mb20 textC">工作日志</h2>
      <!-- 项目信息表单 -->
      <el-form :model="projectInfo" label-width="100px" disabled class="project-info-form log-form">
        <el-form-item label="项目名称">
          <el-input v-model="projectInfo.projectName"></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目编号">
              <el-input v-model="projectInfo.projectCode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工时填报人">
              <el-input v-model="projectInfo.nickName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目开始时间">
              <el-date-picker v-model="projectInfo.startDate" type="date"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目结束时间">
              <el-date-picker v-model="projectInfo.endDate" type="date"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 日���选择器 -->

      <!-- 日历视图 -->
      <div class="calendar-view" v-if="projectInfo">
        <el-calendar v-model="selectedDate" @input="updateDateColors">
          <template #header="{ date }">
            <div class="calendar-header">
              <el-date-picker v-model="selectedDate" type="month" format="YYYY年MM月" :clearable="false" />
            </div>
          </template>
          <template #dateCell="{ data }">
            <div
              :key="data.day"
              :id="data.day"
              @click="openLogDialog(data)"
              :class="{
                'date-cell': true,
                'in-range': isInProjectRange(data),
                'out-range': !isInProjectRange(data),
                disabled: isFutureDate(data.date) && isInProjectRange(data),
              }"
            >
              {{ data.day.split('-')[2] }}
            </div>
          </template>
        </el-calendar>
      </div>
    </div>

    <!-- 工作日志对话框 -->
    <el-dialog v-model="logDialogVisible" title="工作日志" width="30%">
      <el-form :model="logForm" label-width="120px" class="log-form">
        <el-form-item label="工作时长(小时)">
          <el-input v-model.number="logForm.workTime"></el-input>
        </el-form-item>
        <el-form-item label="工作内容">
          <el-input v-model="logForm.workContent" type="textarea" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer" v-if="logForm.status == -1">
          <el-button @click="logDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveWorkLog">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import { workLogApi, projectApi } from '@/utils/api'
import CustomTable from '@/components/CustomTable.vue'

const isCollapsed = ref(false)
const selectedDate = ref(new Date())

// 更新项目列表，包含工时数据
const projectList = ref([])

// 当前选中的项目
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}

const logData = ref([])
const handleProjectClick = async row => {
  const res = await projectApi.getProjectDetail(row.projectId)
  projectInfo.value.projectName = res.data.projectName
  projectInfo.value.projectId = res.data.projectId
  projectInfo.value.projectCode = res.data.projectCode
  projectInfo.value.startDate = res.data.startDate
  projectInfo.value.endDate = res.data.endDate.split(' ')[0] + ' 23:59:59'

  // 更新日历的选中日期和当前月份
  selectedDate.value = new Date(projectInfo.value.startDate) // 设置为项目开始时间
  // 获取日历日志数据

  const res2 = await workLogApi.getLogData({
    projectId: projectInfo.value.projectId,
    startDate: projectInfo.value.startDate,
    endDate: projectInfo.value.endDate,
    userId: projectInfo.value.userId,
  })
  logData.value = res2.data
  initDateColor()
}
// 渲染日期颜色
const initDateColor = () => {
  logData.value.map(item => {
    var ele = document.getElementById(item.date.split(' ')[0])
    if (ele) {
      if (item.state == -1) {
        ele.style = 'background:#ecf5ff'
      } else if (item.state == 0) {
        ele.style = 'background:#409eff;color:#fff'
      } else if (item.state == 1) {
        ele.style = 'background:#f5dc58;color:#fff'
      }
    }
  })
}
const openLogDialog = async data => {
  if (!projectInfo.value) {
    ElMessage.warning('请先选择一个项目')
    return
  }
  handleProjectClick(projectInfo.value)
  // 使用 data.day 而不是 data.date
  const clickedDate = new Date(data.day)
  const currentDate = new Date()

  // 将两个日期都设置为当天的开始时间（UTC）
  clickedDate.setUTCHours(0, 0, 0, 0)
  currentDate.setUTCHours(0, 0, 0, 0)

  if (
    clickedDate.getTime() > currentDate.getTime() &&
    clickedDate.getTime() < new Date(projectInfo.value.endDate).getTime()
  ) {
    ElMessage.warning('不可编辑未来日期')
    return
  }

  const date = new Date(data.day)
  const start = new Date(projectInfo.value.startDate)
  const end = new Date(projectInfo.value.endDate)
  // 使用 getTime() 进行比较，这样可以准确比较日期
  let flag = date.getTime() >= start.getTime() && date.getTime() <= end.getTime()

  if (!flag) {
    ElMessage.warning('该日期不在项目范围内')
    return
  }
  // 这里可以添加打开日志对话框的逻辑
  logForm.value.loggerDate = data.day + ' 00:00:00'
  let logTime = logData.value.find(ele => ele.date == logForm.value.loggerDate) || {}
  logForm.value.status = logTime.state
  if (logForm.value.status != -1) {
    const res = await workLogApi.getLogDataDetail({
      userId: projectInfo.value.userId,
      projectId: projectInfo.value.projectId,
      loggerDate: logForm.value.loggerDate,
    })
    logForm.value.workTime = res.data.workTime
    logForm.value.workContent = res.data.workContent
  } else {
    logForm.value.workTime = ''
    logForm.value.workContent = ''
  }
  logDialogVisible.value = true
}

const isInProjectRange = data => {
  if (!projectInfo.value) return false
  const date = new Date(data.day)
  const start = new Date(projectInfo.value.startDate)
  const end = new Date(projectInfo.value.endDate)
  // 使用 getTime() 进行比较，这样可以准确比较日期
  return date.getTime() >= start.getTime() && date.getTime() <= end.getTime()
}

const isFutureDate = date => {
  const clickedDate = new Date(date)
  const currentDate = new Date()
  return clickedDate.getTime() > currentDate.getTime()
}

const getSummaries = param => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计工时（h）'
      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 * 24
        } else {
          return prev
        }
      }, 0)
    } else {
      sums[index] = 'N/A'
    }
  })
  if (sums[1] != 'N/A') sums[1] = Number(sums[1]).toFixed(2)
  return sums
}

const logForm = ref({
  loggerDate: '',
  workContent: '',
  workTime: '',
  status: -1,
})
// 项目信息
const projectInfo = ref({})

// 工作日志对话框
const logDialogVisible = ref(false)
const workLog = ref({
  hours: 0,
  content: '',
})

// 保存工作日志
const saveWorkLog = async () => {
  // 这里添加保存工作日志的逻辑
  // 判断是否为补填
  let state = new Date(logForm.value.loggerDate).getTime() == $moment().startOf('day').valueOf() ? 0 : 1
  await workLogApi.addLog({
    ...logForm.value,
    projectId: projectInfo.value.projectId,
    state,
    userId: projectInfo.value.userId,
  })
  logDialogVisible.value = false
  ElMessage.success('添加成功')
  handleProjectClick(projectInfo.value)
}

const route = useRoute()

// 获取用户项目
const projectRef = ref(null)
const fetchUserProjects = async () => {
  try {
    const response = await workLogApi.userProject(projectInfo.value.userId)
    projectList.value = response.data // 假设返回的数���结构中有 projects 数组
    if (projectList.value.length) {
      handleProjectClick(projectList.value[0])
      projectRef.value.setCurrentRow(projectList.value[0])
    }
  } catch (error) {}
}
const updateDateColors = () => {
  initDateColor() // 重新渲染日期颜色
}
onMounted(() => {
  if (route.params.userId) {
    projectInfo.value.userId = route.params.userId
    projectInfo.value.nickName = route.params.nickName
  } else {
    let userInfo =
      sessionStorage.getItem('userInfo') !== 'undefined' && sessionStorage.getItem('userInfo')
        ? JSON.parse($utils.decryptByDES.CBC(sessionStorage.getItem('userInfo'))).user
        : {}
    projectInfo.value.userId = userInfo.userId
    projectInfo.value.nickName = userInfo.nickName
  }
  //获取项目列表
  fetchUserProjects()
})
</script>

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

.project-list {
  width: 300px;
  border-right: 1px solid #dcdfe6;
  transition: all 0.3s;
  overflow: hidden;
  position: relative;
  height: 100%;
}

.project-list.collapsed {
  width: 50px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 1px solid #dcdfe6;
  position: relative;
  height: 40px;
  flex: 1;
}

.collapse-button-wrapper {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 40px; /* 固定宽度 */
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.project-list.collapsed .collapse-button-wrapper {
  width: 100%;
}

.collapse-button {
  padding: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.collapse-button:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.collapse-button :deep(.el-icon) {
  font-size: 20px;
  color: #606266;
}

.project-info-calendar {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  padding-bottom: 0;
}

.calendar-picker {
  margin-bottom: 0;
}

.calendar-view :deep(.el-calendar-day) {
  padding: 4px; /* 恢复默认内边距 */
}

.calendar-view :deep(.el-calendar-day:hover) {
  cursor: pointer;
  background-color: #f2f6fc;
}

.calendar-view :deep(.date-cell) {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.calendar-view :deep(.in-range) {
  background-color: #ecf5ff;
}
.calendar-view :deep(.out-range) {
  background-color: rgba(0, 0, 0, 0.05) !important;
}

.calendar-view :deep(.disabled) {
  background-color: #fff !important;
  color: #c0c4cc;
  cursor: not-allowed;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.project-list :deep(.el-table .cell) {
  text-align: center;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.calendar-view :deep(.el-form-item) {
  margin-bottom: 20px;
}

.calendar-view :deep(.el-input__inner) {
  height: 40px;
}

.calendar-view :deep(.el-textarea__inner) {
  min-height: 100px;
}

.calendar-view :deep(.el-calendar-header) {
  display: flex;
  justify-content: center;
  padding: 0;
}

.log-form :deep(.el-form-item) {
  margin-bottom: 30px;
}

.log-form :deep(.el-input__wrapper) {
  height: 50px;
}

.log-form :deep(.el-input__inner) {
  height: 50px;
  line-height: 50px;
  font-size: 16px;
}

.log-form :deep(.el-textarea__inner) {
  min-height: 150px;
  font-size: 16px;
  line-height: 1.5;
  padding: 12px 15px;
}

.log-form :deep(.el-input__wrapper) {
  height: 50px;
  width: 100% !important;
}
:deep(.el-date-editor--date) {
  width: 100% !important;
}

.log-form :deep(.el-input__inner) {
  height: 50px;
  line-height: 50px;
  font-size: 16px;
}

.log-form :deep(.el-textarea__inner) {
  min-height: 150px;
  font-size: 16px;
  line-height: 1.5;
  padding: 12px 15px;
}

/* 增加 el-form-item__label 的高度和行高 */
:deep(.el-form-item__label) {
  height: 42px; /* 默认通常是 32px，所以增加 10px ��变为 42px */
  line-height: 42px; /* 行高与高度相同，确保文字垂直居中 */
}

/* 保持 el-form-item__content 的一致性 */
:deep(.el-form-item__content) {
  min-height: 42px;
  display: flex;
  align-items: center;
}

/* 调整输入框的高度以匹配增加的空间 */
:deep(.el-input__wrapper) {
  height: 42px;
}

:deep(.el-input__inner) {
  height: 42px;
  line-height: 42px;
}

/* 对于 textarea，可能需要单独调整 */
:deep(.el-textarea__inner) {
  min-height: 42px;
}

:deep(.el-calendar__header) {
  justify-content: center !important;
}
:deep(.el-calendar__body) {
  padding-bottom: 0;
}

.calendar-view {
  flex: 1;
  padding: 20px;
  font-size: 14px; /* 缩小字体大小 */
}

.calendar-view :deep(.el-calendar) {
  --el-calendar-cell-width: 40px; /* 缩小日历单元格宽度 */
}

.calendar-view :deep(.el-calendar__header) {
  padding: 10px 0; /* 减小头部内边距 */
}

.calendar-view :deep(.el-calendar__body) {
  padding: 10px 0; /* 减小主体内边距 */
}

.calendar-view :deep(.el-calendar__week) {
  background-color: #4a4a4a; /* 深灰色背景 */
  color: white; /* 白色文字 */
  padding: 5px 0; /* 增加一些内边距 */
}

.calendar-view :deep(.el-calendar-day) {
  height: 65px; /* 增加日期单元格高度（原高度 + 5px） */
  padding-top: 5px;
  padding-bottom: 5px;
}

.project-list :deep(.el-table) {
  width: 100% !important;
}

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

.project-list :deep(.el-table .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
:deep(.el-dialog__body) {
  padding-bottom: 0 !important;
}

.date-cell {
  cursor: pointer;
}

.date-cell.disabled {
  cursor: not-allowed;
}
:deep(.el-table__footer-wrapper) {
  background-color: #f5f7fa;
}

:deep(.el-table__footer td) {
  background-color: #f5f7fa !important;
  font-weight: bold;
  color: #606266;
}
:deep(.el-table__row) {
  cursor: pointer;
}
:deep(tr.el-table__row:hover .el-table__cell) {
  background: #409eff !important;
  color: #fff;
}
:deep(tr.el-table__row.current-row .el-table__cell) {
  background-color: #409eff !important;
  color: #fff;
}
</style>
