import type { VbenFormProps } from '#/adapter/form';

/**
 * 机器人表单 Schema 拆分说明
 *
 * - createFormSchema：新增用，按 platform_code / use_platform_credential 切换字段
 * - editFormSchema：编辑基础信息（不含密钥）；应用 API 可改 chat_id
 *
 * 注意：secret 字段全局唯一（webhook 加签与应用 Secret 复用同一 fieldName）
 */

/** 是否应用 API 平台 */
export function isWorkWechatApp(platformCode?: string) {
  return platformCode === 'work_wechat_app';
}

/** 是否使用平台默认凭证（1=是） */
export function isUsePlatformCredential(values: {
  platform_code?: string;
  use_platform_credential?: number;
}) {
  return (
    isWorkWechatApp(values.platform_code) &&
    Number(values.use_platform_credential ?? 1) === 1
  );
}

/** 是否展示自定义凭证字段（应用 API + 自定义） */
export function showCustomAppCredential(values: {
  platform_code?: string;
  use_platform_credential?: number;
}) {
  return (
    isWorkWechatApp(values.platform_code) &&
    Number(values.use_platform_credential ?? 1) === 0
  );
}

const baseSchema = [
  {
    component: 'VbenInput',
    fieldName: 'id',
    label: 'ID',
    formItemClass: 'col-span-6',
    dependencies: {
      show: false,
      triggerFields: ['id'],
    },
  },
  {
    component: 'RadioGroup',
    componentProps: {
      options: [],
    },
    fieldName: 'platform_code',
    label: '所属平台',
    rules: 'selectRequired',
  },
  {
    component: 'VbenInput',
    componentProps: {
      placeholder: '请输入机器人名称（便于识别）',
    },
    fieldName: 'name',
    label: '机器人名称',
    rules: 'required',
  },
  {
    component: 'RadioGroup',
    componentProps: {
      options: [
        { label: '启用', value: 1 },
        { label: '禁用', value: 0 },
      ],
    },
    defaultValue: 1,
    fieldName: 'status',
    label: '状态',
  },
  {
    component: 'Textarea',
    componentProps: {
      placeholder: '可选，备注说明（如：财务群-企业微信）',
      rows: 3,
    },
    fieldName: 'remark',
    label: '备注',
  },
];

/** 新增时的凭证字段（按平台 + 凭证策略切换展示） */
const createCredentialSchema = [
  {
    // 仅新增态展示：选择同平台已有机器人，回填凭证策略与 chat_id 等
    component: 'Select',
    componentProps: {
      placeholder: '可选，选择后回填凭证与群聊（不含名称）',
      allowClear: true,
      showSearch: true,
      optionFilterProp: 'label',
      options: [],
    },
    fieldName: 'clone_from_id',
    label: '克隆机器人',
    dependencies: {
      triggerFields: ['platform_code'],
      show: (values: { platform_code?: string }) =>
        isWorkWechatApp(values.platform_code),
    },
  },
  {
    component: 'RadioGroup',
    componentProps: {
      options: [
        { label: '使用平台默认凭证', value: 1 },
        { label: '自定义凭证', value: 0 },
      ],
    },
    defaultValue: 1,
    fieldName: 'use_platform_credential',
    label: '凭证来源',
    dependencies: {
      triggerFields: ['platform_code'],
      show: (values: { platform_code?: string }) =>
        isWorkWechatApp(values.platform_code),
      rules: (values: { platform_code?: string }) =>
        isWorkWechatApp(values.platform_code) ? 'selectRequired' : null,
    },
  },
  {
    component: 'VbenInputPassword',
    componentProps: {
      placeholder: '请粘贴 webhook URL',
      autocomplete: 'new-password',
    },
    fieldName: 'webhook_url',
    label: 'Webhook 地址',
    dependencies: {
      triggerFields: ['platform_code'],
      show: (values: { platform_code?: string }) =>
        !isWorkWechatApp(values.platform_code),
      rules: (values: { platform_code?: string }) =>
        isWorkWechatApp(values.platform_code) ? null : 'required',
    },
  },
  {
    component: 'VbenInput',
    componentProps: {
      placeholder: '企业微信企业 ID（corpid）',
      autocomplete: 'off',
    },
    fieldName: 'corp_id',
    label: '企业 ID',
    dependencies: {
      triggerFields: ['platform_code', 'use_platform_credential'],
      show: (values: {
        platform_code?: string;
        use_platform_credential?: number;
      }) => showCustomAppCredential(values),
      rules: (values: {
        platform_code?: string;
        use_platform_credential?: number;
      }) => (showCustomAppCredential(values) ? 'required' : null),
    },
  },
  {
    // webhook 加签密钥 / 应用 Secret 共用 fieldName=secret
    component: 'VbenInputPassword',
    componentProps: {
      placeholder: '钉钉/应用API自定义必填；企微 webhook、飞书选填',
      autocomplete: 'new-password',
    },
    fieldName: 'secret',
    label: '密钥',
    dependencies: {
      triggerFields: ['platform_code', 'use_platform_credential'],
      show: (values: {
        platform_code?: string;
        use_platform_credential?: number;
      }) => {
        if (isWorkWechatApp(values.platform_code)) {
          return showCustomAppCredential(values);
        }
        return true;
      },
      rules: (values: {
        platform_code?: string;
        use_platform_credential?: number;
      }) => {
        if (showCustomAppCredential(values)) return 'required';
        if (values.platform_code === 'dingtalk') return 'required';
        return null;
      },
    },
  },
  {
    component: 'InputNumber',
    componentProps: {
      placeholder: '企业应用 agentid',
      min: 1,
      class: 'w-full',
    },
    fieldName: 'agent_id',
    label: '应用 AgentId',
    dependencies: {
      triggerFields: ['platform_code', 'use_platform_credential'],
      show: (values: {
        platform_code?: string;
        use_platform_credential?: number;
      }) => showCustomAppCredential(values),
      rules: (values: {
        platform_code?: string;
        use_platform_credential?: number;
      }) => (showCustomAppCredential(values) ? 'required' : null),
    },
  },
  {
    component: 'VbenInput',
    componentProps: {
      placeholder: '可选；兼容旧数据。新流程请在场景中选群',
      autocomplete: 'off',
    },
    fieldName: 'chat_id',
    label: '默认群聊 ID',
    dependencies: {
      triggerFields: ['platform_code'],
      show: (values: { platform_code?: string }) =>
        isWorkWechatApp(values.platform_code),
    },
  },
];

/** 编辑态可改 chat_id（应用 API）；改凭证走独立弹窗 */
const editAppChatSchema = [
  {
    component: 'VbenInput',
    componentProps: {
      placeholder: '可选；场景选群为主。填写后可同步成员',
      autocomplete: 'off',
    },
    fieldName: 'chat_id',
    label: '默认群聊 ID',
    dependencies: {
      triggerFields: ['platform_code'],
      show: (values: { platform_code?: string }) =>
        isWorkWechatApp(values.platform_code),
    },
  },
];

export const createFormSchema = [...baseSchema, ...createCredentialSchema];
export const editFormSchema = [...baseSchema, ...editAppChatSchema];

export const modalFormProps: VbenFormProps = {
  wrapperClass: 'grid-cols-12',
  commonConfig: {
    formItemClass: 'col-span-12',
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  schema: createFormSchema,
  showDefaultActions: false,
};
