<template>
  <ElDialog v-model="visible" :title="title" width="500px" align-center @close="handleClose">
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="100px" v-loading="loading">
      <ElFormItem label="模板编码" prop="templateCode" v-if="dialogType !== 'clone'">
        <ElInput
          v-model="form.templateCode"
          :disabled="dialogType === 'edit'"
          placeholder="请输入模板编码"
        />
      </ElFormItem>

      <template v-if="dialogType === 'clone'">
        <ElFormItem label="源模板编码">
          <ElInput v-model="form.sourceTemplateCode" disabled />
        </ElFormItem>
        <ElFormItem label="新模板编码" prop="newTemplateCode">
          <ElInput v-model="form.newTemplateCode" placeholder="请输入新模板编码" />
        </ElFormItem>
      </template>

      <ElFormItem label="模板名称" prop="name">
        <ElInput v-model="form.name" placeholder="请输入模板名称" />
      </ElFormItem>
      <ElFormItem label="描述" prop="description">
        <ElInput v-model="form.description" type="textarea" placeholder="请输入描述" />
      </ElFormItem>
      <ElFormItem label="状态" prop="isActive">
        <ElSwitch v-model="form.isActive" active-text="启用" inactive-text="禁用" />
      </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, computed, watch, reactive } from 'vue'
  import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
  import {
    fetchCreateRoleTemplate,
    fetchUpdateRoleTemplate,
    fetchCloneRoleTemplate
  } from '@/api/role-template'

  interface Props {
    modelValue: boolean
    dialogType: 'add' | 'edit' | 'clone'
    templateData?: Api.RoleTemplate.RoleTemplateDto
  }

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

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

  const emit = defineEmits<Emits>()

  const formRef = ref<FormInstance>()
  const loading = ref(false)

  const form = reactive({
    templateCode: '',
    sourceTemplateCode: '',
    newTemplateCode: '',
    name: '',
    description: '',
    isActive: true,
    permissionCodes: [] as string[]
  })

  const rules = reactive<FormRules>({
    templateCode: [{ required: true, message: '请输入模板编码', trigger: 'blur' }],
    newTemplateCode: [{ required: true, message: '请输入新模板编码', trigger: 'blur' }],
    name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }]
  })

  const title = computed(() => {
    const titles = {
      add: '新增角色模板',
      edit: '编辑角色模板',
      clone: '克隆角色模板'
    }
    return titles[props.dialogType]
  })

  const visible = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
  })

  watch(
    () => props.modelValue,
    (val) => {
      if (val) {
        initForm()
      }
    }
  )

  const initForm = () => {
    if (formRef.value) formRef.value.resetFields()

    if (props.dialogType === 'add') {
      form.templateCode = ''
      form.name = ''
      form.description = ''
      form.isActive = true
      form.permissionCodes = []
    } else if (props.templateData) {
      form.name = props.templateData.name
      form.description = props.templateData.description || ''
      form.isActive = props.templateData.isActive
      // Permission handling might need fetching detail if not present in row

      if (props.dialogType === 'edit') {
        form.templateCode = props.templateData.templateCode
      } else if (props.dialogType === 'clone') {
        form.sourceTemplateCode = props.templateData.templateCode
        form.newTemplateCode = ''
        form.name = props.templateData.name + ' (副本)'
      }
    }
  }

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

  const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true
        try {
          if (props.dialogType === 'add') {
            await fetchCreateRoleTemplate({
              templateCode: form.templateCode,
              name: form.name,
              description: form.description,
              isActive: form.isActive,
              permissionCodes: [] // Initially empty, add permissions via permission dialog
            })
            ElMessage.success('新增成功')
          } else if (props.dialogType === 'edit') {
            await fetchUpdateRoleTemplate(form.templateCode, {
              templateCode: form.templateCode,
              name: form.name,
              description: form.description,
              isActive: form.isActive
              // Not sending permissionCodes to preserve existing ones or handle separately
            })
            ElMessage.success('更新成功')
          } else if (props.dialogType === 'clone') {
            await fetchCloneRoleTemplate(form.sourceTemplateCode, {
              sourceTemplateCode: form.sourceTemplateCode,
              newTemplateCode: form.newTemplateCode,
              name: form.name,
              description: form.description,
              isActive: form.isActive
              // clone might copy permissions automatically if not specified
            })
            ElMessage.success('克隆成功')
          }
          emit('success')
          handleClose()
        } catch (error) {
          console.error(error)
        } finally {
          loading.value = false
        }
      }
    })
  }
</script>
