<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="100" show-word-limit />
      </el-form-item>
      <el-form-item label="应用编码">
        <el-input v-model="form.appCode" placeholder="自动生成" disabled />
      </el-form-item>
      <el-form-item label="应用描述" prop="appDesc">
        <el-input
          v-model="form.appDesc"
          type="textarea"
          placeholder="请输入应用描述"
          :rows="3"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="联系人" prop="contactPerson">
        <el-input v-model="form.contactPerson" placeholder="请输入联系人" maxlength="50" />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="form.contactPhone" placeholder="请输入联系电话" maxlength="20" />
      </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="apiCodes">
        <el-checkbox-group v-model="form.apiCodes">
          <el-checkbox
            v-for="item in apiList"
            :key="item.apiCode"
            :label="item.apiCode"
          >
            {{ item.apiName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
/**
 * 应用管理 - 新增/编辑弹窗
 * @author pangu
 */
import { addApplication, getApplicationApiList, getApplicationDetail, updateApplication } from '@/api/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 apiList = ref([])

const form = reactive({
  appId: null,
  appName: '',
  appCode: '',
  appDesc: '',
  contactPerson: '',
  contactPhone: '',
  status: '0',
  apiCodes: []
})

const rules = {
  appName: [
    { required: true, message: '请输入应用名称', trigger: 'blur' },
    { max: 100, message: '应用名称长度不能超过100个字符', trigger: 'blur' }
  ],
  contactPhone: [
    { pattern: /^1[3-9]\d{9}$|^$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

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

// 加载API接口列表（用于授权勾选）
const loadApiList = async () => {
  try {
    const res = await getApplicationApiList()
    if (res.code === 200 && res.data) {
      apiList.value = res.data
    }
  } catch (e) {
    console.error('加载接口列表失败:', e)
  }
}

// 打开弹窗
const open = async (row = null) => {
  visible.value = true
  await loadApiList()

  if (row && (row.appId || row.id)) {
    isEdit.value = true
    const appId = row.appId ?? row.id
    try {
      const res = await getApplicationDetail(appId)
      if (res.code === 200 && res.data) {
        const data = res.data
        Object.assign(form, {
          appId: data.appId ?? data.id,
          appName: data.appName,
          appCode: data.appCode,
          appDesc: data.appDesc || '',
          contactPerson: data.contactPerson || '',
          contactPhone: data.contactPhone || '',
          status: data.status || '0',
          apiCodes: (data.apis || []).map(a => a.apiCode)
        })
      }
    } catch (e) {
      console.error('加载应用详情失败:', e)
      nextTick(() => {
        Object.assign(form, {
          appId: row.appId ?? row.id,
          appName: row.appName,
          appCode: row.appCode,
          appDesc: row.appDesc || '',
          contactPerson: row.contactPerson || '',
          contactPhone: row.contactPhone || '',
          status: row.status || '0',
          apiCodes: (row.apis || []).map(a => a.apiCode)
        })
      })
    }
  } else {
    isEdit.value = false
    nextTick(() => {
      Object.assign(form, {
        appId: null,
        appName: '',
        appCode: '',
        appDesc: '',
        contactPerson: '',
        contactPhone: '',
        status: '0',
        apiCodes: []
      })
    })
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true

    const payload = {
      appName: form.appName,
      appDesc: form.appDesc,
      contactPerson: form.contactPerson,
      contactPhone: form.contactPhone,
      status: form.status,
      apiCodes: form.apiCodes
    }
    if (isEdit.value) {
      payload.appId = form.appId
    }

    const api = isEdit.value ? updateApplication : addApplication
    const res = await api(payload)

    if (res.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      visible.value = false
      emit('success')
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (e) {
    if (e?.message) {
      // 校验未通过等
    }
  } finally {
    submitLoading.value = false
  }
}

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

defineExpose({ open })
</script>
