<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const loading = ref(false)
const packagesLoading = ref(false)
const deptLoading = ref(false)
const packages = ref([])
const stores = ref([])
const departments = ref([])

const form = reactive({
  store_id: '',
  registration_package_id: '',
  department_id: '',
  username: '',
  password: '',
  name: '',
  phone: '',
})

const formRef = ref(null)
const rules = {
  store_id: [{ required: true, message: '请选择门店', trigger: 'change' }],
  registration_package_id: [{ required: true, message: '请选择申请岗位', trigger: 'change' }],
  username: [
    { required: true, message: '请输入登录账号', trigger: 'blur' },
    { min: 2, max: 50, message: '2-50个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码不少于6位', trigger: 'blur' },
  ],
  name: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
  ],
}

async function fetchStores() {
  try {
    const res = await axios.get('/api/v1/auth/stores')
    stores.value = res.data?.data || []
  } catch {
    //
  }
}

async function onStoreChange() {
  form.registration_package_id = ''
  form.department_id = ''
  packages.value = []
  departments.value = []
  if (!form.store_id) return

  packagesLoading.value = true
  deptLoading.value = true

  try {
    const [pkgRes, deptRes] = await Promise.all([
      axios.get('/api/v1/auth/register/packages', { params: { store_id: form.store_id } }),
      axios.get('/api/v1/auth/register/departments', { params: { store_id: form.store_id } }),
    ])
    packages.value = pkgRes.data?.data || []
    departments.value = deptRes.data?.data || []
  } catch {
    packages.value = []
    departments.value = []
  } finally {
    packagesLoading.value = false
    deptLoading.value = false
  }
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    loading.value = true
    try {
      await axios.post('/api/v1/auth/register', form)
      ElMessage.success('注册成功！请等待管理员审核后登录')
      setTimeout(() => router.push('/login'), 1500)
    } catch (e) {
      const msg = e.response?.data?.message || '注册失败，请稍后重试'
      ElMessage.error(msg)
    } finally {
      loading.value = false
    }
  })
}

onMounted(fetchStores)
</script>

<template>
  <div class="min-h-screen bg-gradient-to-br from-pink-50 to-purple-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-3xl shadow-xl w-full max-w-md p-8">
      <!-- Logo -->
      <div class="text-center mb-8">
        <div class="text-3xl mb-1">🏠</div>
        <h1 class="text-2xl font-bold text-gray-800">宫中有喜</h1>
        <p class="text-sm text-gray-400 mt-1">月子会所管理系统 · 员工注册</p>
      </div>

      <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
        <!-- 门店 -->
        <el-form-item label="所属门店" prop="store_id">
          <el-select
            v-model="form.store_id"
            placeholder="请选择门店"
            style="width: 100%"
            @change="onStoreChange"
          >
            <el-option v-for="s in stores" :key="s.id" :label="s.name" :value="s.id" />
          </el-select>
        </el-form-item>

        <!-- 申请岗位套餐 -->
        <el-form-item label="申请岗位" prop="registration_package_id">
          <el-select
            v-model="form.registration_package_id"
            placeholder="请先选择门店"
            style="width: 100%"
            :loading="packagesLoading"
            :disabled="!form.store_id"
          >
            <el-option
              v-for="p in packages"
              :key="p.id"
              :label="p.name"
              :value="p.id"
            >
              <span>{{ p.name }}</span>
              <span v-if="p.description" class="text-gray-400 text-xs ml-2">{{ p.description }}</span>
            </el-option>
            <template v-if="packages.length === 0 && form.store_id && !packagesLoading" #empty>
              <div class="text-center py-4 text-gray-400 text-sm">该门店暂无可用套餐，请联系管理员</div>
            </template>
          </el-select>
        </el-form-item>

        <!-- 所属部门 -->
        <el-form-item label="所属部门" prop="department_id">
          <el-select
            v-model="form.department_id"
            placeholder="请先选择门店"
            style="width: 100%"
            :loading="deptLoading"
            :disabled="!form.store_id"
            clearable
          >
            <el-option v-for="d in departments" :key="d.id" :label="d.name" :value="d.id" />
            <template v-if="departments.length === 0 && form.store_id && !deptLoading" #empty>
              <div class="text-center py-4 text-gray-400 text-sm">该门店暂无部门数据</div>
            </template>
          </el-select>
        </el-form-item>

        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="登录账号" prop="username">
              <el-input v-model="form.username" placeholder="字母/数字" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录密码" prop="password">
              <el-input v-model="form.password" type="password" placeholder="不少于6位" show-password />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="11位手机号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-button
          type="primary"
          style="width: 100%; margin-top: 8px"
          :loading="loading"
          @click="handleSubmit"
        >
          提交注册申请
        </el-button>
      </el-form>

      <div class="text-center mt-6 text-sm text-gray-400">
        已有账号？
        <router-link to="/login" class="text-blue-500 hover:underline">立即登录</router-link>
      </div>

      <div class="mt-4 p-3 bg-amber-50 rounded-xl text-xs text-amber-600 leading-relaxed">
        ⚠️ 注册后需管理员审核，审核通过后方可登录系统
      </div>
    </div>
  </div>
</template>
