<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="600px"
    :close-on-click-modal="false"
    destroy-on-close
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="应用名称" prop="appName">
        <el-input v-model="form.appName" placeholder="请输入应用名称" maxlength="50" />
      </el-form-item>
      <el-form-item label="应用编码" prop="appCode">
        <el-input v-model="form.appCode" placeholder="保存后自动生成" disabled />
      </el-form-item>
      <el-form-item label="应用描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          placeholder="请输入应用描述"
          :rows="3"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="联系人" prop="contactName">
        <el-input v-model="form.contactName" placeholder="请输入联系人" maxlength="20" />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="form.contactPhone" placeholder="请输入联系电话" maxlength="11" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch
          v-model="form.status"
          active-value="0"
          inactive-value="1"
          active-text="正常"
          inactive-text="停用"
        />
      </el-form-item>
      <el-form-item label="接口授权" prop="apiAuth">
        <el-checkbox-group v-model="form.apiAuth">
          <el-checkbox
            v-for="item in apiAuthOptions"
            :key="item.value"
            :label="item.value"
          >
            {{ item.label }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
/**
 * 应用管理 - 新增/编辑弹窗
 * @author pangu
 */
import { addApplication, getApiAuthOptions, updateApplication } from '@/api/pangu/application'
import { ElMessage } from 'element-plus'
import { computed, nextTick, reactive, ref } from 'vue'

const emit = defineEmits(['success'])

const visible = ref(false)
const submitLoading = ref(false)
const formRef = ref(null)
const isEdit = ref(false)
const apiAuthOptions = ref([])

const form = reactive({
  id: null,
  appName: '',
  appCode: '',
  description: '',
  contactName: '',
  contactPhone: '',
  status: '0',
  apiAuth: []
})

const rules = {
  appName: [
    { required: true, message: '请输入应用名称', trigger: 'blur' }
  ],
  contactPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const dialogTitle = computed(() => isEdit.value ? '编辑应用' : '新增应用')

// 加载接口授权选项
const loadAuthOptions = async () => {
  try {
    const res = await getApiAuthOptions()
    if (res.code === 200) {
      apiAuthOptions.value = res.data
    }
  } catch (error) {
    console.error('加载接口授权选项失败:', error)
  }
}

// 打开弹窗
const open = (row = null) => {
  visible.value = true
  loadAuthOptions()
  
  if (row) {
    isEdit.value = true
    nextTick(() => {
      Object.assign(form, {
        id: row.id,
        appName: row.appName,
        appCode: row.appCode,
        description: row.description || '',
        contactName: row.contactName || '',
        contactPhone: row.contactPhone || '',
        status: row.status || '0',
        apiAuth: row.apiAuth || []
      })
    })
  } else {
    isEdit.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    const api = isEdit.value ? updateApplication : addApplication
    const res = await api(form)
    
    if (res.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      visible.value = false
      emit('success')
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    console.error('表单验证失败或提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 关闭弹窗后重置表单
const handleClosed = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    id: null,
    appName: '',
    appCode: '',
    description: '',
    contactName: '',
    contactPhone: '',
    status: '0',
    apiAuth: []
  })
}

defineExpose({ open })
</script>
