<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, watch } from 'vue'

import { createRole, updateRole, type Role, type CreateRoleRequest, type UpdateRoleRequest } from '@/api/adminRoles'

const props = defineProps<{
  modelValue: boolean
  role?: Role | null
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', val: boolean): void
  (e: 'saved'): void
}>()

const submitting = ref(false)
const form = ref({
  code: '',
  name: '',
  description: '',
})

const isEdit = ref(false)

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      if (props.role) {
        isEdit.value = true
        form.value = {
          code: props.role.code,
          name: props.role.name,
          description: props.role.description,
        }
      } else {
        isEdit.value = false
        form.value = { code: '', name: '', description: '' }
      }
    }
  },
  { immediate: true },
)

async function handleSave() {
  submitting.value = true
  try {
    if (isEdit.value && props.role) {
      const req: UpdateRoleRequest = {
        name: form.value.name,
        description: form.value.description,
      }
      await updateRole(props.role.id, req)
      ElMessage.success('角色已更新')
    } else {
      const req: CreateRoleRequest = {
        code: form.value.code,
        name: form.value.name,
        description: form.value.description,
      }
      await createRole(req)
      ElMessage.success('角色已创建')
    }
    emit('saved')
    emit('update:modelValue', false)
  } catch (error) {
    ElMessage.error(readError(error, '操作失败'))
  } finally {
    submitting.value = false
  }
}

function readError(error: unknown, fallback: string) {
  if (typeof error === 'object' && error && 'response' in error) {
    const response = (error as { response?: { data?: { message?: string } } }).response
    return response?.data?.message || fallback
  }
  return fallback
}
</script>

<template>
  <el-dialog
    :model-value="modelValue"
    :title="isEdit ? '编辑角色' : '新建角色'"
    width="500px"
    @update:model-value="emit('update:modelValue', $event)"
  >
    <div class="dialog-body">
      <el-form-item label="角色编码" class="full-control">
        <el-input v-model="form.code" :disabled="isEdit" placeholder="例如: cs, ops, finance" />
      </el-form-item>
      <el-form-item label="角色名称" class="full-control">
        <el-input v-model="form.name" placeholder="例如: 客服, 运营, 财务" />
      </el-form-item>
      <el-form-item label="描述" class="full-control">
        <el-input v-model="form.description" type="textarea" :rows="3" placeholder="角色描述" />
      </el-form-item>
    </div>
    <template #footer>
      <el-button @click="emit('update:modelValue', false)">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-body {
  display: grid;
  gap: 16px;
}
.full-control {
  width: 100%;
}
</style>
