<template>
  <div class="project-management">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="custom-form">
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="项目名称" prop="projectName">
            <el-input
              v-model="formData.projectName"
              placeholder="请输入项目名称"
              :disabled="isEditing"
              class="full-width longInput"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目编码" prop="projectCode">
            <el-input v-model="formData.projectCode" class="full-width" :disabled="isEditing" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目负责人" prop="projectLeader">
            <el-input
              v-model="formData.projectLeaderName"
              placeholder="选择项目负责人"
              readonly
              :disabled="isEditing"
              @click="openProjectManagerSelect"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="项目状态" prop="projectState">
            <el-select
              v-model="formData.projectState"
              placeholder="请选择项目状态"
              :disabled="isEditing"
              class="full-width"
            >
              <el-option label="未启动" value="0" />
              <el-option label="进行中" value="1" />
              <el-option label="已完成" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预算天数" prop="budgetDate">
            <el-input v-model.number="formData.budgetDate" :min="0" :disabled="isEditing" class="full-width" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker
              v-model="formData.startDate"
              type="date"
              placeholder="选择开始日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              class="full-width"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束日期" prop="endDate">
            <el-date-picker
              v-model="formData.endDate"
              type="date"
              placeholder="选择结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              class="full-width"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="form-actions jcc">
      <el-button type="primary" @click="saveProject">保存</el-button>
      <el-button @click="cancelEdit">取消</el-button>
    </div>
    <div class="table-actions">
      <el-button type="primary" :icon="Plus" @click="addUser">新增成员</el-button>
    </div>

    <CustomTable
      :columns="columns"
      :tableData="tableData"
      :total="total"
      :show-selection="false"
      :show-index="true"
      :show-pagination="false"
      :table-height="tableHeight"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <template #name="{ row }">
        <el-input
          v-if="row.isNew"
          v-model="row.userName"
          placeholder="选择人员"
          readonly
          @click="openSelectUser(row)"
        />
        <span v-else>{{ row.userName }}</span>
      </template>
      <template #post="{ row }">
        <el-select
          v-if="row.isEditing || row.isNew"
          v-model="row.postId"
          placeholder="请选择职位"
          @change="handlePostChange(row)"
        >
          <el-option v-for="post in postOptions" :key="post" :label="post.dictLabel" :value="post.dictValue" />
        </el-select>
        <span v-else>{{ postOptions.find(post => post.dictValue === row.postId)?.dictLabel }}</span>
      </template>
      <template #operation="{ row }">
        <div class="operation-buttons">
          <template v-if="row.isNew">
            <el-button text type="primary" @click="confirmAddUser(row)">确认</el-button>
            <el-button text type="danger" @click="cancelAddUser(row)">取消</el-button>
          </template>
          <template v-else-if="row.isEditing">
            <el-button text type="primary" @click="saveUserEdit(row)">保存</el-button>
            <el-button text type="info" @click="cancelUserEdit(row)">取消</el-button>
          </template>
          <template v-else>
            <el-button text type="primary" @click="editUser(row)">编辑</el-button>
            <el-button text type="primary" @click="showTimesheet(row)">工作日志</el-button>
            <el-button text type="danger" @click="confirmDelete(row)">删除</el-button>
          </template>
        </div>
      </template>
    </CustomTable>

    <!-- 修改 SelectUser 组件 -->
    <SelectUser
      v-if="showSelectUser"
      v-model:dialogVisible="showSelectUser"
      :multi-select="false"
      :selected-users="currentSelectedUser"
      @confirm="handleUserConfirm"
      @close="closeSelectUser"
    />

    <SelectUser
      v-if="showProjectManagerSelect"
      v-model:dialogVisible="showProjectManagerSelect"
      :multi-select="false"
      :selected-users="projectManagerSelectedUser"
      @confirm="handleProjectManagerConfirm"
      @close="closeProjectManagerSelect"
    />

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="确认删除" width="30%">
      <div class="delete-confirm">
        <el-icon class="warning-icon"><WarningFilled /></el-icon>
        <p>确定要删除该成员吗？此操作不可逆。</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import CustomTable from '@/components/CustomTable.vue'
import { Plus,WarningFilled } from '@element-plus/icons-vue'
import SelectUser from '@/components/SelectUser.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { projectApi, systemApi } from '@/utils/api'

const router = useRouter()
const route = useRoute()
const formRef = ref(null)

const isEditing = computed(() => !!formData.projectId)
const showSelectUser = ref(false)
const showProjectManagerSelect = ref(false)
const formData = reactive({
  projectId: null,
  projectName: '',
  projectCode: '',
  projectLeaderName: '',
  projectLeader: '',
  projectState: '',
  startDate: '',
  endDate: '',
  budgetDate: 0,
  state: 0,
})

const postOptions = ref([]) // 根据实际情况调整

const columns = [
  { prop: 'name', label: '姓名' },
  { prop: 'post', label: '项目职位' },
  { prop: 'workdays', label: '工作天数' },
  { prop: 'operation', label: '操作', width: '250px' },
]

const tableData = ref([])
const total = ref(0)
const currentEditingRow = ref(null)
const currentSelectedUser = ref([])
const projectManagerSelectedUser = ref([])

// 自动更新项目状态
watch([() => formData.startDate, () => formData.endDate], updateProjectState, { immediate: true })

function updateProjectState() {
  const now = new Date().getTime()
  const start = formData.startDate ? new Date(formData.startDate).getTime() : null
  const end = formData.endDate ? new Date(formData.endDate).getTime() : null

  if (start && end) {
    if (now < start) {
      formData.projectState = '0' // 未开始
    } else if (now >= start && now <= end) {
      formData.projectState = '1' // 进行中
    } else {
      formData.projectState = '2' // 已结束
    }
  }
}

const validateDates = (rule, value, callback) => {
  if (formData.startDate && formData.endDate) {
    const start = new Date(formData.startDate)
    const end = new Date(formData.endDate)
    if (start > end) {
      callback(new Error('开始日期不能晚于结束日期'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

const rules = {
  projectName: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { max: 200, message: '项目名称不能超过200个字符', trigger: 'blur' },
  ],
  projectCode: [
    { required: true, message: '请输入项目编码', trigger: 'blur' },
    { max: 50, message: '项目编码不能超过50个字符', trigger: 'blur' },
  ],
  projectLeader: [{ required: true, message: '请选择项目负责人', trigger: 'change' }],
  projectState: [{ required: true, message: '请选择项目状态', trigger: 'change' }],
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' },
    { validator: validateDates, trigger: 'change' },
  ],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' },
    { validator: validateDates, trigger: 'change' },
  ],
  budgetDate: [
    { required: true, message: '请输入预算天数', trigger: 'blur' },
    { type: 'number', min: 1, message: '预算天数必须大于0', trigger: 'blur' },
  ],
}

const saveProject = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    // 表单验证通过，继续保存操作
    const projectDataToSave = {
      ...formData,
      startDate: formData.startDate ? new Date(formData.startDate).getTime() : null,
      endDate: formData.endDate ? new Date(formData.endDate).getTime() : null,
    }
    if (!formData.projectId) {
      const res = await projectApi.addProject(projectDataToSave)
      formData.projectId = res.data.projectId
    } else {
      await projectApi.updateProject(projectDataToSave)
    }
    ElMessage.success('项目保存成功')
    // 如果是新建项目，保存后不要立即返回，而是停留在当前页面
  } catch (error) {
    if (error instanceof Error) {
      // 表单验证失败
      console.error('表单验证失败', error)
      ElMessage.error('请检查表单填写是否正确')
    } else {
      // API 调用失败
      console.error('保存项目失败', error)
      ElMessage.error('保存项目失败')
    }
  }
}

const cancelEdit = () => {
  router.back()
}

const addUser = () => {
  if (!formData.projectId) {
    ElMessage.warning('请先保存项目信息后再添加用户')
    return
  }

  const newUser = {
    id: Date.now(),
    name: '',
    post: '',
    postId: '',
    workdays: 0,
    userId: null,
    isNew: true,
  }
  tableData.value.unshift(newUser)
  total.value = tableData.value.length
}

const handlePostChange = row => {
  // 可以在这里添加一些额外的逻辑，如果需要的话
}

const confirmAddUser = async row => {
  if (!formData.projectId) {
    ElMessage.warning('请先保存项目信息后再添加用户')
    return
  }

  if (!row.userId || !row.postId) {
    ElMessage.warning('请选择用户并指定职位')
    return
  }

  try {
    let params = {
      projectId: formData.projectId,
      userId: row.userId,
      postId: row.postId,
    }
    if (row.teamId) params.teamId = row.teamId
    await projectApi.updateProjectUser(params)
    row.isNew = false
    ElMessage.success('成员添加成功')
    getProjectUser()
  } catch (error) {
    console.error('添加成员失败', error)
    ElMessage.error('添加成员失败')
  }
}

const cancelAddUser = row => {
  const index = tableData.value.findIndex(item => item.id === row.id)
  if (index !== -1) {
    tableData.value.splice(index, 1)
    total.value = tableData.value.length
  }
}

const openSelectUser = row => {
  currentEditingRow.value = row
  currentSelectedUser.value = row.userId ? [{ id: row.userId, name: row.name }] : []
  showSelectUser.value = true
}

const handleUserConfirm = selectedUsers => {
  if (!formData.projectId) {
    ElMessage.warning('请先保存项目信息后再选择用户')
    return
  }

  if (selectedUsers.length > 0) {
    const selectedUser = selectedUsers[0]
    currentEditingRow.value.userName = selectedUser.nickName
    currentEditingRow.value.userId = selectedUser.userId
  } else {
    currentEditingRow.value.name = ''
    currentEditingRow.value.userId = null
  }
  showSelectUser.value = false
}

const closeSelectUser = () => {
  showSelectUser.value = false
  currentEditingRow.value = null
  currentSelectedUser.value = []
}

const openProjectManagerSelect = () => {
  projectManagerSelectedUser.value = formData.projectLeader
    ? [{ id: formData.projectLeaderId, name: formData.projectLeader }]
    : []
  showProjectManagerSelect.value = true
}

const handleProjectManagerConfirm = users => {
  if (users.length > 0) {
    const selectedUser = users[0]
    formData.projectLeaderName = selectedUser.nickName
    formData.projectLeader = selectedUser.userId
  } else {
    formData.projectLeaderName = ''
    formData.projectLeader = null
  }
  showProjectManagerSelect.value = false
}

const closeProjectManagerSelect = () => {
  showProjectManagerSelect.value = false
}

const handleSizeChange = val => {
  console.log('每页显示条数:', val)
}

const handleCurrentChange = val => {
  console.log('当前页:', val)
}

const showTimesheet = row => {
  router.push({
    path: '/worklog/list',
    query: { userId: row.userId, projectId: formData.projectId },
  })
}

const deleteDialogVisible = ref(false)

const confirmDelete = row => {
  ElMessageBox.confirm('确定要删除该成员吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      deleteUser(row)
    })
    .catch(() => {
      // 取消删除操作
    })
}

const deleteUser = async row => {
  try {
    await projectApi.deleteProjectUser(row.teamId)
    ElMessage.success('成员删除成功')
    getProjectUser()
  } catch (error) {
    console.error('删除成员失败', error)
    ElMessage.error('删除成员失败')
  }
}

const tableHeight = ref(400)
// 获取项目编码
const getProjectCode = async () => {
  const res = await projectApi.getProjectCode()
  formData.projectCode = res.data
}

const fetchProjectData = async id => {
  try {
    const response = await projectApi.getProjectDetail(id)
    const projectData = response.data
    // 将时间戳转换为日期字符串
    formData.startDate = projectData.startDate ? new Date(projectData.startDate).toISOString().split('T')[0] : ''
    formData.endDate = projectData.endDate ? new Date(projectData.endDate).toISOString().split('T')[0] : ''
    // 复制其他字段
    Object.assign(formData, {
      ...projectData,
      startDate: formData.startDate,
      endDate: formData.endDate,
    })
    updateProjectState() // 更新项目状态
  } catch (error) {
    console.error('获取项目数据失败', error)
    ElMessage.error('获取项目数据失败')
  }
}
// 获取数据字典
const getDictData = async () => {
  const res = await systemApi.getDictData('business_positions')
  postOptions.value = res.data
}
// 获取项目人员
const getProjectUser = async () => {
  await getDictData()
  const res = await projectApi.getProjectUser(formData.projectId)
  tableData.value = res.data
}

const editUser = row => {
  row.isEditing = true
  row.originalPost = row.postId // 保存原始职位，以便取消时恢复
}

const saveUserEdit = async row => {
  if (!formData.projectId) {
    ElMessage.warning('请先保存项目信息')
    return
  }

  try {
    await projectApi.updateProjectUser({
      projectId: formData.projectId,
      userId: row.userId,
      postId: row.postId,
      teamId: row.teamId,
    })
    row.isEditing = false
    delete row.originalPost
    ElMessage.success('用户信息更新成功')
  } catch (error) {
    console.error('更新用户信息失败', error)
    ElMessage.error('更新用户信息失败')
  }
}

const cancelUserEdit = row => {
  row.postId = row.originalPost
  row.isEditing = false
  delete row.originalPost
}

onMounted(() => {
  const projectId = route.params.id || route.query.id
  formData.projectId = projectId
  if (projectId) {
    fetchProjectData(projectId)
    getProjectUser()
  } else {
    updateProjectState() // 对于新项目，也要初始化状态
    getProjectCode()
  }
})
</script>

<style scoped>
.project-management {
  padding: 20px;
  background-color: white;
  height: 88vh;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.custom-form {
  width: 80%;
  margin-bottom: 20px;
}
.form-container {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
  margin-bottom: 20px;
}

.custom-form :deep(.el-form-item) {
  margin-bottom: 25px; /* 增加表单行间距 */
}

.custom-form :deep(.el-form-item__content) {
  margin-left: auto !important;
  width: 80%;
}
.custom-form :deep(.el-input) {
  height: 42px; /* 调高输入框高度 */
}
:deep(.el-form-item__label) {
  height: 42px; /* 调高输入框高度 */
  line-height: 42px;
}
.custom-form :deep(.el-input__wrapper),
.custom-form :deep(.el-date-editor.el-input),
.custom-form :deep(.el-input-number) {
  height: 42px; /* 调高输入框高度 */
}
.custom-form :deep(.el-select) {
  width: 100%;
}
.custom-form :deep(.el-input__wrapper),
.custom-form :deep(.el-select .el-input__wrapper),
.custom-form :deep(.el-date-editor.el-input .el-input__wrapper),
.custom-form :deep(.el-input-number .el-input__wrapper) {
  height: 100%;
}

.content-container {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.table-actions {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.form-actions {
  display: flex;
  gap: 10px;
}

:deep(.el-table) {
  width: 100%;
}

.operation-buttons {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

:deep(.operation-buttons .el-button) {
  padding: 4px 8px;
  margin: 0 2px;
}

:deep(.operation-column) {
  background-color: #fff;
  box-shadow: -2px 0 5px rgba(0, 0, 0, 0.1);
}

/* 添加以下样式以使日期选择器宽度一致 */
:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-date-editor.el-input .el-input__wrapper) {
  width: 100%;
}
:deep(.longInput) {
  width: 100% !important;
}
.el-button.is-text {
  min-width: 32px !important;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-select .el-input__wrapper) {
  height: 32px;
}

.delete-confirm {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.warning-icon {
  width: 64px;
  height: 64px;
  margin-bottom: 16px;
}
</style>
