<script setup lang="ts">
import type { Rule } from 'ant-design-vue/es/form';

import { onMounted, reactive, ref } from 'vue';

import { Page } from '@vben/common-ui';

import {
  Alert,
  Button,
  Card,
  Divider,
  Form,
  FormItem,
  Input,
  InputPassword,
  message,
  Space,
  Switch,
  Textarea,
} from 'ant-design-vue';
import { LinkOutlined } from '@ant-design/icons-vue';

import { getWecomConfig, saveWecomConfig, testWecomConfig } from '#/api/system/wecom-config';

const saving = ref(false);
const testing = ref(false);
const formRef = ref();

const formState = reactive({
  corpid: '',
  corpsecret: '',
  agentId: '',
  callbackToken: '',
  callbackAesKey: '',
  enabled: false,
  remark: '',
});

const rules: Record<string, Rule[]> = {
  corpid: [{ required: true, message: '请输入企业ID', trigger: 'blur' }],
  corpsecret: [{ required: true, message: '请输入应用密钥', trigger: 'blur' }],
};

async function loadConfig() {
  try {
    const data = await getWecomConfig();
    if (data) {
      formState.corpid = data.corpid || '';
      formState.corpsecret = data.corpsecret || '';
      formState.agentId = data.agentId || '';
      formState.callbackToken = data.callbackToken || '';
      formState.callbackAesKey = data.callbackAesKey || '';
      formState.enabled = data.enabled === '1';
      formState.remark = data.remark || '';
    }
  } catch {
    // ignore
  }
}

async function handleSave() {
  try {
    await formRef.value?.validate();
  } catch {
    return;
  }
  saving.value = true;
  try {
    await saveWecomConfig({
      ...formState,
      enabled: formState.enabled ? '1' : '0',
    });
    message.success('保存成功');
  } catch {
    message.error('保存失败');
  } finally {
    saving.value = false;
  }
}

async function handleTest() {
  if (!formState.corpid || !formState.corpsecret) {
    message.error('企业ID和应用密钥不能为空');
    return;
  }
  testing.value = true;
  try {
    const result = await testWecomConfig(formState.corpid, formState.corpsecret);
    message.success(result || '连接成功');
  } catch {
    message.error('测试失败');
  } finally {
    testing.value = false;
  }
}

function openWeComHelp() {
  window.open('https://work.weixin.qq.com/wework_admin/frame#profile', '_blank');
}

onMounted(() => {
  loadConfig();
});
</script>

<template>
  <Page>
    <div style="overflow-y: auto; padding: 16px">
      <Card title="企业微信配置" :bordered="false" style="max-width: 720px">
        <template #extra>
          <Button type="link" @click="openWeComHelp">
            <template #icon><LinkOutlined /></template>
            如何获取？
          </Button>
        </template>

        <Alert
          message="请在企业微信管理后台获取企业ID和应用密钥"
          type="info"
          show-icon
          style="margin-bottom: 24px"
        />

        <Form ref="formRef" :model="formState" layout="vertical" style="max-width: 480px">
          <FormItem label="企业ID（corpid）" name="corpid" :rules="rules.corpid">
            <Input v-model:value="formState.corpid" placeholder="从企业微信管理后台获取" />
          </FormItem>

          <FormItem label="应用密钥（corpsecret）" name="corpsecret" :rules="rules.corpsecret">
            <InputPassword v-model:value="formState.corpsecret" placeholder="自建应用的Secret" />
          </FormItem>

          <FormItem label="应用 AgentID" name="agentId">
            <Input v-model:value="formState.agentId" placeholder="可选，应用管理页面获取" />
          </FormItem>

          <Divider>回调配置（可选）</Divider>

          <FormItem label="回调 Token" name="callbackToken">
            <Input v-model:value="formState.callbackToken" placeholder="审批回调URL验证Token" />
          </FormItem>

          <FormItem label="回调 EncodingAESKey" name="callbackAesKey">
            <InputPassword v-model:value="formState.callbackAesKey" placeholder="消息加密密钥" />
          </FormItem>

          <FormItem label="启用状态" name="enabled">
            <Switch v-model:checked="formState.enabled" checked-children="已启用" un-checked-children="未启用" />
          </FormItem>

          <FormItem label="备注" name="remark">
            <Textarea v-model:value="formState.remark" :rows="2" placeholder="备注信息" />
          </FormItem>

          <FormItem>
            <Space>
              <Button :loading="testing" @click="handleTest">
                测试连接
              </Button>
              <Button type="primary" :loading="saving" @click="handleSave">
                保存配置
              </Button>
            </Space>
          </FormItem>
        </Form>
      </Card>
    </div>
  </Page>
</template>
