<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span style="font-weight: bold;">员工账号管理</span>
          <el-button type="primary" @click="handleCreate">
            + 新增员工
          </el-button>
        </div>
      </template>

      <el-table
          v-loading="tableLoading"
          :data="tableData"
          border
          style="width: 100%"
      >
        <el-table-column prop="username" label="用户名" width="150" />

        <el-table-column prop="department" label="所属部门" width="150">
          <template #default="scope">
            <el-tag>{{ scope.row.department }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="role" label="系统角色" width="180">
          <template #default="scope">
            {{ formatRole(scope.row.role) }}
          </template>
        </el-table-column>

        <el-table-column prop="email" label="邮箱" min-width="200" />

        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button
                link
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>

            <el-popconfirm
                title="确定要删除该用户吗？此操作无法撤销。"
                @confirm="handleDelete(scope.row)"
            >
              <template #reference>
                <el-button link type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑员工账号' : '新增员工账号'"
        width="500px"
        @close="resetForm"
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="form.username"
              placeholder="登录账号 (英文)"
              :disabled="isEdit"
          />
        </el-form-item>

        <el-form-item
            label="密码"
            prop="password"
        >
          <el-input
              v-model="form.password"
              type="password"
              show-password
              :placeholder="isEdit ? '不修改请留空' : '设置初始密码'"
          />
        </el-form-item>

        <el-form-item label="所属部门" prop="department">
          <el-select
              v-model="form.department"
              placeholder="请输入或选择部门"
              style="width: 100%"
              filterable
              allow-create
              default-first-option
          >
            <el-option
                v-for="item in departmentOptions"
                :key="item"
                :label="item"
                :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="系统角色" prop="role">
          <el-select v-model="form.role" placeholder="授予权限" style="width: 100%">
            <el-option label="主管" value="supervisor" />
            <el-option label="财务" value="finance" />
            <el-option label="库管" value="warehouse_manager" />
            <el-option label="入库员" value="inbound" />
            <el-option label="出库员" value="outbound" />
            <el-option label="采购员" value="purchaser" />
            <el-option label="销售" value="sales" />
          </el-select>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="可选填" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit" :loading="submitLoading">
            {{ isEdit ? '确认修改' : '确认创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue'
import { createUser, updateUser, getUserList, deleteUser } from '@/api/auth'
import { ElMessage } from 'element-plus'

// --- 状态定义 ---
const tableLoading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const tableData = ref<any[]>([])
const departmentOptions = ref<string[]>([])
const formRef = ref()

// [新增] 区分编辑/创建模式
const isEdit = ref(false)
const currentId = ref<number | null>(null)

const form = reactive({
  username: '',
  password: '',
  department: '',
  role: '',
  email: ''
})

// [关键] 动态规则：编辑模式下密码不是必填项
const rules = computed(() => {
  const commonRules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    role: [{ required: true, message: '请选择角色', trigger: 'change' }],
    department: [{ required: true, message: '请输入或选择部门', trigger: ['blur', 'change'] }]
  }

  // 如果是创建模式，密码必填
  if (!isEdit.value) {
    return {
      ...commonRules,
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码至少6位', trigger: 'blur' }
      ]
    }
  } else {
    // 如果是编辑模式，密码选填（只有输入了才校验长度）
    return {
      ...commonRules,
      password: [
        { min: 6, message: '密码至少6位', trigger: 'blur' }
      ]
    }
  }
})

// --- 逻辑方法 ---

const getList = async () => {
  tableLoading.value = true
  try {
    const res = await getUserList()
    tableData.value = res.data || []
    extractDepartments(tableData.value)
  } catch (error) {
    console.error('Fetch users failed:', error)
  } finally {
    tableLoading.value = false
  }
}

const extractDepartments = (data: any[]) => {
  const deptSet = new Set<string>()
  if (data && data.length > 0) {
    data.forEach(user => {
      if (user.department && user.department.trim() !== '') {
        deptSet.add(user.department)
      }
    })
  }
  departmentOptions.value = Array.from(deptSet)
}

// 2. 打开新增弹窗
const handleCreate = () => {
  isEdit.value = false
  currentId.value = null
  resetFormState() // 清空数据
  dialogVisible.value = true
}

// [新增] 打开编辑弹窗
const handleEdit = (row: any) => {
  isEdit.value = true
  currentId.value = row.id

  // 回填数据
  form.username = row.username
  form.department = row.department
  form.role = row.role
  form.email = row.email || ''
  form.password = '' // 编辑时不回显密码，留空表示不修改

  dialogVisible.value = true
}

// 3. 提交 (兼容创建和修改)
const onSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (isEdit.value && currentId.value) {
          // 编辑逻辑
          await updateUser(currentId.value, form)
          ElMessage.success(`用户 ${form.username} 修改成功！`)
        } else {
          // 创建逻辑
          await createUser(form)
          ElMessage.success(`用户 ${form.username} 创建成功！`)
        }

        dialogVisible.value = false
        getList()
      } catch (error) {
        // 错误已处理
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 4. 重置表单
const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  resetFormState()
}

const resetFormState = () => {
  form.username = ''
  form.password = ''
  form.department = ''
  form.role = ''
  form.email = ''
}

// 5. 删除用户
const handleDelete = async (row: any) => {
  try {
    await deleteUser(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    // 错误处理
  }
}

// --- 辅助显示方法 ---

const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  return dateStr.replace('T', ' ').substring(0, 19)
}

const formatRole = (val: string) => {
  const map: Record<string, string> = {
    'supervisor': '主管',
    'finance': '财务',
    'warehouse_manager': '库管',
    'inbound': '入库员',
    'outbound': '出库员',
    'purchaser': '采购员',
    'sales': '销售',
    'super_admin': '超级管理员'
  }
  return map[val] || val
}

// --- 初始化 ---
onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.dialog-footer {
  text-align: right;
  margin-top: 20px;
}
</style>