<template>
  <my-layout>
    <!-- 查询区 -->
    <el-card class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
      <el-form :inline="true" label-width="auto" :model="state.filter" class="demo-form-inline" @submit.stop.prevent>
        <el-form-item label="关键字">
          <el-input v-model="state.filter.keyWord" placeholder="请输入关键字" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="ele-Search" @click="handleQuery"> 查询 </el-button>
          <el-button v-auth="'api:admin:project:add'" type="primary" icon="ele-Plus" @click="handleAdd"> 新增 </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区 -->
    <el-card class="my-fill mt8" shadow="never">
      <div class="my-tools-box mb8 my-flex my-flex-between">
        <!-- 可添加工具栏内容，如批量操作等 -->
      </div>
      <el-table v-loading="loading" :data="state.projectList" style="width: 100%" border row-key="projectNo">
        <el-table-column prop="projectNo" label="项目编号" />
        <el-table-column prop="projectName" label="项目名称" />
        <el-table-column prop="createdUserName" label="创建人" />
        <el-table-column prop="createdTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right" header-align="center" align="center">
          <template #default="{ row }">
            <el-button v-auth="'api:admin:project:update'" icon="ele-EditPen" size="small" text type="primary"
              @click="handleEdit(row)">编辑</el-button>
            <el-button v-auth="'api:admin:project:soft-delete'" icon="ele-Delete" size="small" text type="danger"
              @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="my-flex my-flex-end" style="margin-top: 10px">
        <el-pagination v-model:current-page="state.pageInput.currentPage" v-model:page-size="state.pageInput.pageSize"
          :total="state.total" :page-sizes="[10, 20, 50, 100]" size="small" background @size-change="handleSizeChange"
          @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper" />
      </div>
    </el-card>

    <project-form ref="formRef" :title="state.formTitle" @ok="getList" />
  </my-layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, defineAsyncComponent } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ProjectApi } from '../../../api/admin/ProjectApi'
import { OrgApi } from '/@/api/admin/Org'
import type { ProjectPageInput, ProjectDto } from '/@/api/types/projectType'
import eventBus from '/@/utils/mitt'

const ProjectForm = defineAsyncComponent(() => import('./components/project-form.vue'))

const loading = ref(false)
const formRef = ref()

const state = reactive({
  loading: false,
  formTitle: '',
  total: 0,
  filter: {
    keyWord: '',
  },
  pageInput: {
    currentPage: 1,
    pageSize: 20,
  } as ProjectPageInput,
  projectList: [] as Array<ProjectDto>
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  state.pageInput.filter = state.filter
  try {
    const res = await new ProjectApi().getPage(state.pageInput)
    state.projectList = res.data?.list || []
    state.total = res.data?.total || 0
  } catch (error) {
    console.error('获取列表失败:', error)
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  state.pageInput.currentPage = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  state.filter = {
    keyWord: '',
  }
  handleQuery()
}

/** 新增按钮操作 */
const handleAdd = () => {
  state.formTitle = '新增项目'
  formRef.value?.open()
}

/** 修改按钮操作 */
const handleEdit = (row: ProjectDto) => {
  state.formTitle = '编辑项目'
  formRef.value?.open(row.id)
}

/** 删除按钮操作 */
const handleDelete = (row: ProjectDto) => {
  ElMessageBox.confirm('确认要删除该记录吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await new ProjectApi().softDelete({ id: row.id! })
      if (res.success) {
        ElMessage.success('删除成功')
        getList()
      }
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

/** 每页条数改变 */
const handleSizeChange = (val: number) => {
  state.pageInput.pageSize = val
  getList()
}

/** 当前页改变 */
const handleCurrentChange = (val: number) => {
  state.pageInput.currentPage = val
  getList()
}

onMounted(() => {
  getList()
  eventBus.on('refreshProject', getList)
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 