<script lang="ts" setup>
/**
 * 企业微信应用 API「改凭证」弹窗
 * 仅保存凭证策略（平台默认 / 自定义 corp/secret/agent）；测试请到列表「测试」弹窗选人/选群
 */
import { ref } from 'vue';

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

import { Alert, message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { updateOaRobotAppCredential } from '#/views/system/oa-robot/api';
import {
  isUsePlatformCredential,
  showCustomAppCredential,
} from '#/views/system/oa-robot/config/form';

const gridApi = ref();
const robotId = ref(0);

const [Form, formApi] = useVbenForm({
  wrapperClass: 'grid-cols-12',
  commonConfig: {
    formItemClass: 'col-span-12',
    componentProps: { class: 'w-full' },
  },
  layout: 'horizontal',
  showDefaultActions: false,
  schema: [
    {
      component: 'RadioGroup',
      componentProps: {
        options: [
          { label: '使用平台默认凭证', value: 1 },
          { label: '自定义凭证', value: 0 },
        ],
      },
      defaultValue: 1,
      fieldName: 'use_platform_credential',
      label: '凭证来源',
      rules: 'selectRequired',
    },
    {
      component: 'VbenInput',
      fieldName: 'corp_id',
      label: '企业 ID',
      componentProps: { placeholder: 'corpid', autocomplete: 'off' },
      dependencies: {
        triggerFields: ['use_platform_credential'],
        show: (values: { use_platform_credential?: number }) =>
          showCustomAppCredential({
            platform_code: 'work_wechat_app',
            use_platform_credential: values.use_platform_credential,
          }),
        rules: (values: { use_platform_credential?: number }) =>
          showCustomAppCredential({
            platform_code: 'work_wechat_app',
            use_platform_credential: values.use_platform_credential,
          })
            ? 'required'
            : null,
      },
    },
    {
      component: 'VbenInputPassword',
      fieldName: 'secret',
      label: '应用 Secret',
      componentProps: {
        placeholder: '留空表示不修改；填写则覆盖',
        autocomplete: 'new-password',
      },
      dependencies: {
        triggerFields: ['use_platform_credential'],
        show: (values: { use_platform_credential?: number }) =>
          showCustomAppCredential({
            platform_code: 'work_wechat_app',
            use_platform_credential: values.use_platform_credential,
          }),
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'agent_id',
      label: '应用 AgentId',
      componentProps: { placeholder: '企业应用 agentid', min: 1, class: 'w-full' },
      dependencies: {
        triggerFields: ['use_platform_credential'],
        show: (values: { use_platform_credential?: number }) =>
          showCustomAppCredential({
            platform_code: 'work_wechat_app',
            use_platform_credential: values.use_platform_credential,
          }),
        rules: (values: { use_platform_credential?: number }) =>
          showCustomAppCredential({
            platform_code: 'work_wechat_app',
            use_platform_credential: values.use_platform_credential,
          })
            ? 'required'
            : null,
      },
    },
    {
      component: 'VbenInput',
      fieldName: 'chat_id',
      label: '默认群聊 ID',
      componentProps: {
        placeholder: '可选；场景选群为主。填写后可同步成员',
        autocomplete: 'off',
      },
    },
  ],
});

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const e = await formApi.validate();
    if (!e.valid) return;
    const values = await formApi.getValues();
    const usePlatform = Number(values.use_platform_credential ?? 1);
    // 自定义凭证时 secret 首次必填；编辑留空表示不改
    if (
      !isUsePlatformCredential({
        platform_code: 'work_wechat_app',
        use_platform_credential: usePlatform,
      }) &&
      !String(values.secret || '').trim()
    ) {
      // 编辑场景允许留空不改；若库中本无 secret 会由后端校验
    }
    modalApi.setState({ confirmLoading: true });
    try {
      await updateOaRobotAppCredential({
        id: robotId.value,
        use_platform_credential: usePlatform,
        corp_id: String(values.corp_id || ''),
        secret: String(values.secret || ''),
        agent_id: Number(values.agent_id || 0) || undefined,
        chat_id: String(values.chat_id || ''),
      });
      message.success('凭证已更新');
      gridApi.value?.query?.() || gridApi.value?.reload?.();
      modalApi.close();
    } finally {
      modalApi.setState({ confirmLoading: false });
    }
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) return;
    const data = modalApi.getData<{ row: any; gridApi: any }>() ?? {};
    gridApi.value = data.gridApi;
    const row = data.row || {};
    robotId.value = Number(row.id || 0);
    formApi.setValues({
      use_platform_credential: Number(row.use_platform_credential ?? 1),
      corp_id: row.corp_id || '',
      secret: '',
      agent_id: Number(row.agent_id || 0) || undefined,
      chat_id: row.chat_id || '',
    });
    modalApi.setState({
      title: `改凭证 - ${row.name || ''}`,
    });
  },
});
</script>

<template>
  <Modal class="w-[40%]">
    <Alert
      type="info"
      show-icon
      message="本弹窗仅保存凭证"
      description="冒烟测试请关闭后在列表点击「测试」，并选择接收员工或群聊后再发送。"
      style="margin-bottom: 16px"
    />
    <Form />
  </Modal>
</template>
