<template>
  <ElDialog v-model="visible" :title="title" width="30%" align-center @close="handleClose">
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="120px">
      <ElFormItem label="从模板复制" v-if="dialogType === 'add'">
        <ElSelect
          v-model="form.copyFromTemplateId"
          placeholder="请选择模板（可选）"
          clearable
          filterable
          style="width: 100%"
        >
          <ElOption
            v-for="item in templateList"
            :key="item.templateCode"
            :label="item.name"
            :value="item.templateCode"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="角色编码" prop="code" v-if="dialogType === 'add'">
        <ElInput v-model="form.code" placeholder="请输入角色编码" />
      </ElFormItem>
      <ElFormItem label="角色名称" prop="name">
        <ElInput v-model="form.name" placeholder="请输入角色名称" />
      </ElFormItem>
      <ElFormItem label="描述" prop="description">
        <ElInput v-model="form.description" type="textarea" :rows="3" placeholder="请输入描述" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="handleClose">取消</ElButton>
      <ElButton type="primary" :loading="loading" @click="handleSubmit">提交</ElButton>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch } from 'vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import {
    fetchCreateTenantRole,
    fetchUpdateTenantRole,
    fetchUpdateTenantRolePermissions
  } from '@/api/tenant-role'
  import { fetchGetRoleTemplates, fetchGetRoleTemplatePermissions } from '@/api/role-template'
  import { fetchGetPermissionTree } from '@/api/permission'
  import { ElMessage, ElSelect, ElOption } from 'element-plus'

  type RoleDto = Api.TenantRole.RoleDto
  type RoleTemplateDto = Api.RoleTemplate.RoleTemplateDto

  interface Props {
    modelValue: boolean
    dialogType: 'add' | 'edit' | 'copy'
    roleData?: RoleDto
    tenantId?: string | number
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    dialogType: 'add',
    roleData: undefined,
    tenantId: undefined
  })

  const emit = defineEmits<Emits>()

  const formRef = ref<FormInstance>()
  const loading = ref(false)
  const templateList = ref<RoleTemplateDto[]>([])

  const title = computed(() => {
    switch (props.dialogType) {
      case 'add':
        return '新增角色'
      case 'edit':
        return '编辑角色'
      default:
        return ''
    }
  })

  /**
   * 弹窗显示状态双向绑定
   */
  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  /**
   * 表单验证规则
   */
  const rules = reactive<FormRules>({
    code: [
      { required: true, message: '请输入角色编码', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    name: [
      { required: true, message: '请输入角色名称', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    description: [] // Optional
  })

  /**
   * 表单数据
   */
  const form = reactive({
    code: '',
    name: '',
    description: '',
    copyFromTemplateId: ''
  })

  /**
   * 获取角色模板列表
   */
  const getRoleTemplates = async () => {
    try {
      const res: any = await fetchGetRoleTemplates({ Page: 1, PageSize: 100 })
      // 兼容处理分页响应结构
      if (res && res.items && Array.isArray(res.items)) {
        templateList.value = res.items
      } else if (Array.isArray(res)) {
        templateList.value = res
      } else {
        templateList.value = []
      }
    } catch (error) {
      console.error('获取角色模板失败:', error)
      templateList.value = []
    }
  }

  /**
   * 监听弹窗打开，初始化表单数据
   */
  watch(
    () => props.modelValue,
    async (val) => {
      if (val) {
        if (props.dialogType === 'edit' && props.roleData) {
          form.code = props.roleData.code
          form.name = props.roleData.name
          form.description = props.roleData.description || ''
          form.copyFromTemplateId = ''
        } else {
          // Add
          form.code = ''
          form.name = ''
          form.description = ''
          form.copyFromTemplateId = ''
          // 获取模板列表
          await getRoleTemplates()
        }
      } else {
        formRef.value?.resetFields()
      }
    }
  )

  const handleClose = () => {
    visible.value = false
  }

  const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async (valid) => {
      if (!valid) return
      if (!props.tenantId) {
        ElMessage.error('未选择租户')
        return
      }

      loading.value = true
      try {
        if (props.dialogType === 'add') {
          // 1. 创建角色
          const created = await fetchCreateTenantRole(props.tenantId, {
            code: form.code,
            name: form.name,
            description: form.description
          })

          // 2. 复制模板权限（若选择了模板）
          if (form.copyFromTemplateId) {
            // 2.1 拉模板权限（code）
            const templatePerms = await fetchGetRoleTemplatePermissions(form.copyFromTemplateId)
            const permissionCodes = Array.isArray(templatePerms)
              ? templatePerms
                  .map((p: any) => p.code || p.permissionCode)
                  .filter((code: string | undefined) => !!code)
              : []

            // 2.2 从权限树映射 code -> id
            let permissionIds: string[] = []
            if (permissionCodes.length > 0) {
              const tree = await fetchGetPermissionTree()
              const codeToId = new Map<string, string>()
              const walk = (nodes: any[]) => {
                nodes.forEach((n) => {
                  if (n.code) codeToId.set(n.code, String(n.id))
                  if (Array.isArray(n.children)) walk(n.children)
                })
              }
              if (Array.isArray(tree)) walk(tree)
              permissionIds = permissionCodes
                .map((c) => codeToId.get(c))
                .filter((id): id is string => !!id)
            }

            // 2.3 仅在存在映射时写入
            if (permissionIds.length > 0) {
              await fetchUpdateTenantRolePermissions(props.tenantId, created.id, permissionIds)
            }
          }

          ElMessage.success('新增成功')
        } else if (props.dialogType === 'edit') {
          await fetchUpdateTenantRole(props.tenantId, props.roleData!.id, {
            roleId: props.roleData!.id,
            name: form.name,
            description: form.description
          })
          ElMessage.success('编辑成功')
        }
        emit('success')
        handleClose()
      } catch (error) {
        console.error(error)
      } finally {
        loading.value = false
      }
    })
  }
</script>

<style scoped>
  /* Removed unused styles */
</style>
