<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { registrationPackageApi } from '@/api/system.js'

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增注册套餐')
const submitLoading = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

const pagination = reactive({ page: 1, page_size: 20 })
const searchForm = reactive({ keyword: '' })

const form = reactive({
  id: null,
  name: '',
  description: '',
  role_ids: [],
  status: 1,
  sort: 0,
})

const roles = ref([])

const rules = {
  name: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }],
}

async function fetchList() {
  loading.value = true
  try {
    const res = await registrationPackageApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || []
    total.value = res.data?.total || 0
  } catch {
    //
  } finally {
    loading.value = false
  }
}

async function fetchRoles() {
  try {
    const { roleApi } = await import('@/api/system.js')
    const res = await roleApi.getList({ page_size: 200 })
    roles.value = res.data?.list || []
  } catch {
    //
  }
}

function handleSearch() {
  pagination.page = 1
  fetchList()
}

function handleAdd() {
  isEdit.value = false
  dialogTitle.value = '新增注册套餐'
  Object.assign(form, { id: null, name: '', description: '', role_ids: [], status: 1, sort: 0 })
  dialogVisible.value = true
}

function handleEdit(row) {
  isEdit.value = true
  dialogTitle.value = `编辑 — ${row.name}`
  Object.assign(form, {
    id: row.id,
    name: row.name,
    description: row.description || '',
    role_ids: row.role_ids || [],
    status: row.status,
    sort: row.sort || 0,
  })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (isEdit.value) {
        await registrationPackageApi.update(form.id, form)
        ElMessage.success('更新成功')
      } else {
        await registrationPackageApi.create(form)
        ElMessage.success('创建成功')
      }
      dialogVisible.value = false
      fetchList()
    } catch {
      //
    } finally {
      submitLoading.value = false
    }
  })
}

async function handleDelete(row) {
  await ElMessageBox.confirm(`确定删除套餐「${row.name}」？`, '删除确认', {
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
    type: 'warning',
    confirmButtonClass: 'el-button--danger',
  })
  await registrationPackageApi.delete(row.id)
  ElMessage.success('删除成功')
  fetchList()
}

onMounted(() => {
  fetchList()
  fetchRoles()
})
</script>

<template>
  <div class="p-6 space-y-4">
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center gap-3 flex-wrap">
      <el-input
        v-model="searchForm.keyword"
        placeholder="搜索套餐名称"
        style="width: 220px"
        clearable
        @keydown.enter="handleSearch"
        @clear="handleSearch"
      >
        <template #prefix><el-icon><Search /></el-icon></template>
      </el-input>
      <el-button type="primary" :icon="'Search'" @click="handleSearch">查询</el-button>
    </div>

    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="text-sm text-gray-500">
          共 {{ total }} 个套餐 · 注册时可选择的岗位配置
        </div>
        <el-button type="primary" :icon="'Plus'" @click="handleAdd">新增套餐</el-button>
      </div>

      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width: 100%">
          <el-table-column prop="sort" label="排序" width="70" align="center" />
          <el-table-column prop="name" label="套餐名称" min-width="120" />
          <el-table-column prop="description" label="说明" min-width="200" show-overflow-tooltip />
          <el-table-column label="关联角色" min-width="200">
            <template #default="{ row }">
              <el-tag
                v-for="id in (row.role_ids || [])"
                :key="id"
                size="small"
                type="info"
                style="margin: 2px"
              >
                {{ roles.find(r => r.id === id)?.name || id }}
              </el-tag>
              <span v-if="!row.role_ids?.length" class="text-gray-400 text-sm">无</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
                {{ row.status === 1 ? '启用' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" text @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="px-5 py-3 border-t border-gray-50">
        <el-pagination
          v-model:current-page="pagination.page"
          :page-size="pagination.page_size"
          :total="total"
          layout="total, prev, pager, next"
          background
          @current-change="(v) => { pagination.page = v; fetchList() }"
        />
      </div>
    </div>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="520px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="form.name" placeholder="如：销售、店长、护士" />
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="2" placeholder="注册时显示给用户的说明" />
        </el-form-item>
        <el-form-item label="关联角色" prop="role_ids">
          <el-select v-model="form.role_ids" multiple placeholder="审核通过后自动分配的角色" style="width: 100%">
            <el-option v-for="r in roles" :key="r.id" :label="r.name" :value="r.id" />
          </el-select>
          <div class="text-xs text-gray-400 mt-1">审核通过后，用户将自动获得以上角色权限</div>
        </el-form-item>
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :value="1">启用</el-radio>
                <el-radio :value="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" :max="999" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          {{ isEdit ? '保存修改' : '确认创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
