<template>
  <div class="project-list">
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="项目名称" class="form-item">
          <el-input v-model="searchForm.projectName" placeholder="项目名称" />
        </el-form-item>
        <el-form-item label="负责人" class="form-item">
          <el-input
            v-model="searchForm.projectLeaderName"
            placeholder="负责人"
            readonly
            @click="openUserSelectDialog"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="项目状态" class="form-item">
          <el-select v-model="searchForm.projectState" placeholder="项目状态">
            <el-option label="未启动" value="0" />
            <el-option label="进行中" value="1" />
            <el-option label="已完成" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-actions mb10">
      <el-button type="primary" @click="addProject">+ 新建项目</el-button>
    </div>

    <CustomTable
      :columns="columns"
      :tableData="tableData"
      :total="total"
      :show-selection="false"
      :show-index="true"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <template #operation="{ row }">
        <div class="operation-buttons">
          <el-button text type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button text type="danger" @click="handleDelete(row)">删除</el-button>
        </div>
      </template>
    </CustomTable>

    <el-dialog
      v-model="deleteDialogVisible"
      title="删除项目"
      width="30%"
      :before-close="handleCloseDeleteDialog"
      class="delete-dialog"
    >
      <div class="delete-content">
        <el-icon class="warning-icon"><WarningFilled /></el-icon>
        <span>删除项目时将删除相关工作日志，此操作不可逆，请慎重考虑</span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDelete">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户选择弹框 -->
    <SelectUser
      v-model:dialogVisible="userSelectDialogVisible"
      :multiSelect="false"
      :currentSelectedUser="currentSelectedUser"
      @close="handleUserSelectClose"
      @confirm="handleUserConfirm"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import CustomTable from '@/components/CustomTable.vue'
import SelectUser from '@/components/selectUser.vue'
import { WarningFilled } from '@element-plus/icons-vue'
import { projectApi } from '@/utils/api'

const router = useRouter()

const searchForm = reactive({
  projectName: '',
  projectLeaderName: '',
  projectLeader: '',
  projectState: '',
})

const columns = [
  { prop: 'projectName', label: '项目名称' },
  { prop: 'projectCode', label: '项目编号' },
  { prop: 'projectLeaderName', label: '负责人' },
  { prop: 'budgetDate', label: '预计工时(天)' },
  {
    prop: 'startDate',
    label: '开始时间',
    type: 'status',
    callback: (data, row) => {
      return data.split(' ')[0]
    },
  },
  {
    prop: 'endDate',
    label: '结束时间',
    type: 'status',
    callback: (data, row) => {
      return data.split(' ')[0]
    },
  },
  {
    prop: 'projectState',
    label: '项目状态',
    type: 'status',
    callback: (value, row) => {
      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: 'teamNum', label: '参与项目人数' },
  { prop: 'createByName', label: '项目创建人' },
  {
    prop: 'operation',
    label: '操作',
    width: '150',
    fixed: 'right',
    className: 'operation-column',
  },
]

const tableData = ref([])
const total = ref(0)
const deleteDialogVisible = ref(false)
const currentDeleteItem = ref(null)

const pageNum = ref(1)
const pageSize = ref(10)

// 用户选择相关
const userSelectDialogVisible = ref(false)
const currentSelectedUser = ref([])

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

const handleUserSelectClose = () => {
  userSelectDialogVisible.value = false
}

const handleUserConfirm = (selectedUsers) => {
  if (selectedUsers.length > 0) {
    const selectedUser = selectedUsers[0]
    searchForm.projectLeaderName = selectedUser.nickName
    searchForm.projectLeader = selectedUser.userId
    currentSelectedUser.value = [selectedUser]
  } else {
    searchForm.projectLeaderName = ''
    searchForm.projectLeader = ''
    currentSelectedUser.value = []
  }
  userSelectDialogVisible.value = false
}

const onSearch = () => {
  // 实现搜索逻辑
  console.log('Search with:', searchForm)
  fetchProjectList()
}

const onReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  fetchProjectList()
}

const addProject = () => {
  router.push('/project/detail')
}

const handleEdit = row => {
  router.push({
    path: '/project/detail',
    query: { id: row.projectId },
    state: { projectData: row },
  })
}

const handleDelete = row => {
  currentDeleteItem.value = row
  deleteDialogVisible.value = true
}

const handleCloseDeleteDialog = () => {
  deleteDialogVisible.value = false
  currentDeleteItem.value = null
}

const confirmDelete = async () => {
  // 实现删除逻辑
  await projectApi.deleteProject(currentDeleteItem.value.projectId)
  deleteDialogVisible.value = false
  currentDeleteItem.value = null
  ElMessage.success('删除成功')
  fetchProjectList()
}

const handleSizeChange = val => {
  pageSize.value = val
  pageNum.value = 1 // 重置为第一页
  fetchProjectList()
}

const handleCurrentChange = val => {
  pageNum.value = val
  fetchProjectList()
}

const fetchProjectList = async () => {
  // 这里使用假数据，实际应该调用API
  const res = await projectApi.listProject({
    ...searchForm,
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  })
  tableData.value = res.rows
  total.value = res.total
}

onMounted(() => {
  fetchProjectList()
})
</script>

<style scoped>
.project-list {
  padding: 20px;
  background-color: white;
  height: 88vh;
  box-sizing: border-box;
  overflow: hidden;
}

.search-bar {
  margin-bottom: 20px;
}

.demo-form-inline {
  display: flex;
  flex-wrap: nowrap;
  align-items: flex-start;
}

.demo-form-inline .el-form-item {
  margin-right: 50px; /* 将间距设置为 30px */
  margin-bottom: 0;
}

.demo-form-inline .el-form-item:last-child {
  margin-right: 0; /* 移除最后一个元素的右边距 */
}

.form-item {
  flex: 1;
}

.form-item :deep(.el-form-item__content) {
  width: 100%;
}

.form-item :deep(.el-input),
.form-item :deep(.el-select) {
  width: 100%;
}

.search-buttons {
  white-space: nowrap;
}

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

.el-button.is-text {
  min-width: 32px !important;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog-footer .el-button {
  margin: 0 10px;
}

.delete-content {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.warning-icon {
  font-size: 24px;
  color: #e6a23c;
  margin-right: 10px;
}

/* 可以删除或注释掉之前的 .el-button.is-text 样式，如果不再需要的话 */
/* .el-button.is-text {
  min-width: 32px !important;
} */

/* 添加以下样式来使对话框垂直居中 */
:deep(.delete-dialog.el-dialog) {
  margin-top: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>