<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item label="分组名称" prop="groupName">
        <el-input
          v-model="queryParams.groupName"
          class="!w-240px"
          clearable
          placeholder="请输入分组名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button plain type="primary" @click="openForm('create')">
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" style="width: 100%">
      <!-- <el-table-column label="ID" align="center" prop="id" width="80" /> -->
      <el-table-column label="分组名称" align="center" prop="groupName" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row)"> 编辑 </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 (可选，根据实际需求添加) -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="500px"
    append-to-body
    @closed="handleDialogClosed"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
      <el-form-item label="分组名称" prop="groupName">
        <!-- <el-input v-model="formData.groupName" placeholder="请输入分组名称" /> -->
        <lang-input v-model="formData.groupName" placeholder="请输入分组名称" />
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input-number
          v-model="formData.sort"
          :min="0"
          controls-position="right"
          class="!w-100%"
        />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm" :loading="submitLoading"> 确 定 </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Icon } from '@/components/Icon'
// 假设你有这些工具组件，如果没有请根据实际情况调整
import Pagination from '@/components/Pagination/index.vue'
import { formatDate } from '@/utils/formatTime'
import { createGroup, getGroupList, updateGroup, deleteGroup } from '@/api/flow'

// --- 响应式数据 ---
const loading = ref(false)
const list = ref([])
const total = ref(0)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  groupName: undefined
})
const queryFormRef = ref(null)

// 表单相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const submitLoading = ref(false)
const formData = reactive({
  groupName: '',
  sort: 0,
  remark: ''
})

const formRules = reactive({
  groupName: [{ required: true, message: '请输入分组名称', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
})

// --- 方法 ---

const getList = async () => {
  loading.value = true

  console.log('queryParams>>>>>>>>>>>>>>>>>..', queryParams)
  try {
    const res = await getGroupList(queryParams)
    list.value = res.list
    total.value = res.total
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1

  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

const openForm = (type, row) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '新增分组' : '编辑分组'

  if (type === 'create') {
    formData.groupName = ''
    formData.sort = 0
    formData.remark = ''
  } else {
    // 编辑模式：深拷贝，避免直接修改表格数据
    Object.assign(formData, JSON.parse(JSON.stringify(row)))
  }

  // 清除校验状态
  formRef.value?.clearValidate()
}

// 对话框关闭时重置表单
const handleDialogClosed = () => {
  formRef.value?.resetFields()
}

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

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const submitData = { ...formData }

        if (formData.id) {
          await updateGroup(submitData)
          ElMessage.success('修改成功')
        } else {
          await createGroup(submitData)
          ElMessage.success('新增成功')
        }

        dialogVisible.value = false
        await getList()
      } catch (error) {
        console.error(error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该项吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteGroup(id)
    ElMessage.success('删除成功')
    await getList()
  } catch (error) {
    // ignore
  }
}

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

<style scoped></style>
