<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userApi, roleApi, departmentApi, storeApi } from '@/api/system.js'
import { useUserStore } from '@/stores/user.js'

const userStore = useUserStore()
const isSuper = computed(() => userStore.userInfo?.is_super)

// ─── State ───────────────────────────────────────────────────────────────────

const tableData = ref([])
const stores = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增用户')
const submitLoading = ref(false)
const resetPwdVisible = ref(false)
const currentUserId = ref(null)

const roles = ref([])
const departments = ref([])

const searchForm = reactive({
  keyword: '',
  department_id: '',
  status: ''
})

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

// ─── Form ─────────────────────────────────────────────────────────────────────

const formRef = ref(null)
const form = reactive({
  id: null,
  username: '',
  name: '',
  phone: '',
  email: '',
  department_id: '',
  position_id: '',
  role_ids: [],
  status: 1,
  password: '',
  password_confirm: '',
  store_id: ''
})

const isEdit = ref(false)

const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 50, message: '用户名长度 2-50 个字符', trigger: 'blur' }
  ],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    {
      validator: (rule, value, callback) => {
        if (!isEdit.value && !value) {
          callback(new Error('请输入密码'))
        } else if (value && value.length < 6) {
          callback(new Error('密码不少于 6 位'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// ─── Reset password form ──────────────────────────────────────────────────────

const resetPwdFormRef = ref(null)
const resetPwdForm = reactive({ new_password: '', confirm_password: '' })

const resetPwdRules = {
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码不少于 6 位', trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetPwdForm.new_password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// ─── Methods ──────────────────────────────────────────────────────────────────

function flattenDeptTree(nodes, result = []) {
  for (const n of nodes) {
    result.push({ id: n.id, name: n.name })
    if (n.children?.length) flattenDeptTree(n.children, result)
  }
  return result
}

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

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

async function fetchDepartments() {
  try {
    const res = await departmentApi.getList({ per_page: 500 })
    // API returns tree array directly in res.data, flatten it for selects
    const raw = Array.isArray(res.data) ? res.data : (res.data?.list || res.data?.data || [])
    departments.value = flattenDeptTree(raw)
  } catch {
    //
  }
}

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

function handleReset() {
  Object.assign(searchForm, { keyword: '', department_id: '', status: '' })
  handleSearch()
}

function handleAdd() {
  isEdit.value = false
  dialogTitle.value = '新增用户'
  Object.assign(form, {
    id: null, username: '', name: '', phone: '', email: '',
    department_id: '', position_id: '', role_ids: [], status: 1,
    password: '', password_confirm: '', store_id: ''
  })
  dialogVisible.value = true
}

async function handleEdit(row) {
  isEdit.value = true
  dialogTitle.value = '编辑用户'
  const res = await userApi.getDetail(row.id)
  const user = res.data
  Object.assign(form, {
    id: user.id,
    username: user.username,
    name: user.name,
    phone: user.phone || '',
    email: user.email || '',
    department_id: user.department_id || '',
    position_id: user.position_id || '',
    role_ids: user.roles?.map((r) => r.id) || [],
    status: user.status,
    password: '',
    password_confirm: ''
  })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      const payload = { ...form }
      if (isEdit.value) {
        delete payload.password
        delete payload.password_confirm
        await userApi.update(form.id, payload)
        ElMessage.success('用户信息已更新')
      } else {
        await userApi.create(payload)
        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 userApi.delete(row.id)
  ElMessage.success('删除成功')
  fetchList()
}

async function handleApprove(row) {
  await userApi.approve(row.id)
  ElMessage.success('已审核通过，用户可登录系统')
  fetchList()
}

async function handleReject(row) {
  await ElMessageBox.confirm(`确定拒绝「${row.name}」的注册申请？`, '拒绝确认', {
    confirmButtonText: '确定拒绝',
    cancelButtonText: '取消',
    type: 'warning',
    confirmButtonClass: 'el-button--danger'
  })
  await userApi.reject(row.id)
  ElMessage.success('已拒绝注册申请')
  fetchList()
}

async function handleStatusChange(row) {
  const newStatus = row.status === 1 ? 0 : 1
  try {
    await userApi.updateStatus(row.id, newStatus)
    row.status = newStatus
    ElMessage.success(newStatus === 1 ? '已启用' : '已禁用')
  } catch {
    //
  }
}

function openResetPassword(row) {
  currentUserId.value = row.id
  Object.assign(resetPwdForm, { new_password: '', confirm_password: '' })
  resetPwdVisible.value = true
}

async function submitResetPassword() {
  if (!resetPwdFormRef.value) return
  await resetPwdFormRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      await userApi.resetPassword(currentUserId.value, {
        new_password: resetPwdForm.new_password
      })
      ElMessage.success('密码重置成功')
      resetPwdVisible.value = false
    } catch {
      //
    }
  })
}

function handlePageChange(val) {
  pagination.page = val
  fetchList()
}

function handleSizeChange(val) {
  pagination.page_size = val
  pagination.page = 1
  fetchList()
}

onMounted(() => {
  fetchList()
  fetchRoles()
  fetchDepartments()
  if (isSuper.value) {
    storeApi.getList({ page_size: 200 }).then(res => {
      stores.value = res.data?.list || []
    }).catch(() => {})
  }
})
</script>

<template>
  <div class="p-6 space-y-4">
    <!-- Search Bar -->
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center flex-wrap gap-3">
      <el-input
        v-model="searchForm.keyword"
        placeholder="搜索用户名/姓名/手机号"
        style="width: 240px"
        clearable
        @keydown.enter="handleSearch"
      >
        <template #prefix><el-icon><Search /></el-icon></template>
      </el-input>
      <el-tree-select
        v-model="searchForm.department_id"
        :data="departments"
        :props="{ label: 'name', value: 'id', children: 'children' }"
        placeholder="选择部门"
        clearable
        style="width: 180px"
      />
      <el-select v-model="searchForm.status" placeholder="状态" clearable style="width: 130px">
        <el-option label="正常" :value="1" />
        <el-option label="禁用" :value="0" />
        <el-option label="待审核" :value="2" />
      </el-select>
      <el-button type="primary" :icon="'Search'" @click="handleSearch">查询</el-button>
      <el-button :icon="'Refresh'" @click="handleReset">重置</el-button>
      <!-- 快捷：待审核 -->
      <el-button
        type="warning"
        plain
        @click="searchForm.status = 2; handleSearch()"
      >
        待审核注册
      </el-button>
    </div>

    <!-- Table -->
    <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="flex items-center gap-3"></div>
        <el-button type="primary" :icon="'Plus'" @click="handleAdd">新增用户</el-button>
      </div>
      <div class="px-2">
        <el-table
          v-loading="loading"
          :data="tableData"
          row-key="id"
          style="width: 100%"
        >
          <el-table-column prop="username" label="用户名" min-width="120" />
          <el-table-column prop="name" label="姓名" min-width="100" />
          <el-table-column prop="phone" label="手机号" min-width="130" />
          <el-table-column prop="department.name" label="部门" min-width="120" />
          <el-table-column label="角色" min-width="160">
            <template #default="{ row }">
              <el-tag
                v-for="role in row.roles"
                :key="role.id"
                size="small"
                type="info"
                style="margin: 2px"
              >
                {{ role.name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag
                :type="row.status === 1 ? 'success' : row.status === 2 ? 'warning' : 'danger'"
                size="small"
              >
                {{ row.status === 1 ? '正常' : row.status === 2 ? '待审核' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" min-width="160" />
          <el-table-column label="操作" width="260" fixed="right" align="center">
            <template #default="{ row }">
              <!-- 待审核状态：显示通过/拒绝 -->
              <template v-if="row.status === 2">
                <el-button size="small" type="success" text @click="handleApprove(row)">通过</el-button>
                <el-button size="small" type="danger" text @click="handleReject(row)">拒绝</el-button>
              </template>
              <el-button size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
              <template v-if="row.status !== 2">
                <el-button
                  size="small"
                  :type="row.status === 1 ? 'warning' : 'success'"
                  text
                  @click="handleStatusChange(row)"
                >
                  {{ row.status === 1 ? '禁用' : '启用' }}
                </el-button>
              </template>
              <el-button size="small" type="info" text @click="openResetPassword(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"
          v-model:page-size="pagination.page_size"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- Add/Edit Dialog -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="90px"
        label-position="right"
      >
        <el-row :gutter="16">
          <el-col v-if="isSuper && !isEdit" :span="24">
            <el-form-item label="所属门店" prop="store_id">
              <el-select v-model="form.store_id" placeholder="超管可指定门店（不选则为当前门店）" clearable style="width:100%">
                <el-option v-for="s in stores" :key="s.id" :label="s.name" :value="s.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名" :disabled="isEdit" />
            </el-form-item>
          </el-col>
          <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="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="department_id">
              <el-select v-model="form.department_id" placeholder="选择部门" clearable style="width:100%">
                <el-option v-for="d in departments" :key="d.id" :label="d.name" :value="d.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="role_ids">
              <el-select
                v-model="form.role_ids"
                multiple
                placeholder="选择角色"
                style="width: 100%"
              >
                <el-option
                  v-for="role in roles"
                  :key="role.id"
                  :label="role.name"
                  :value="role.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <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>
          <template v-if="!isEdit">
            <el-col :span="12">
              <el-form-item label="密码" prop="password">
                <el-input
                  v-model="form.password"
                  type="password"
                  placeholder="请输入初始密码"
                  show-password
                />
              </el-form-item>
            </el-col>
          </template>
        </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>

    <!-- Reset Password Dialog -->
    <el-dialog v-model="resetPwdVisible" title="重置密码" width="420px" destroy-on-close>
      <el-form
        ref="resetPwdFormRef"
        :model="resetPwdForm"
        :rules="resetPwdRules"
        label-width="90px"
      >
        <el-form-item label="新密码" prop="new_password">
          <el-input
            v-model="resetPwdForm.new_password"
            type="password"
            placeholder="请输入新密码（不少于6位）"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirm_password">
          <el-input
            v-model="resetPwdForm.confirm_password"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetPwdVisible = false">取消</el-button>
        <el-button type="primary" @click="submitResetPassword">确认重置</el-button>
      </template>
    </el-dialog>
  </div>
</template>
