import { MyBetaModalFormProps, MyButtons, MyModalFormProps } from '@/common';
import { Apis } from '@/gen/Apis';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { Form, message } from 'antd';

export default function CompletePhone(props: MyBetaModalFormProps) {
  const [form] = Form.useForm();

  // 验证多行手机号
  const validatePhones = (_: any, value?: string) => {
    if (!value || !value.trim()) {
      return Promise.reject('请输入手机号');
    }

    const phones = value.trim().split(/\r?\n/).filter(Boolean);
    if (phones.length === 0) {
      return Promise.reject('请输入至少一个手机号');
    }

    if (phones.length > 20000) {
      return Promise.reject('最多支持20000条数据');
    }

    const phoneRegex = /^1[3-9]\d{9}$/;
    const invalidPhones = phones.filter((phone) => !phoneRegex.test(phone));

    if (invalidPhones.length > 0) {
      return Promise.reject(
        `手机号格式不正确：${invalidPhones.slice(0, 3).join(', ')}${
          invalidPhones.length > 3 ? '...等' : ''
        }`,
      );
    }

    return Promise.resolve();
  };

  return (
    <BetaSchemaForm
      {...MyModalFormProps.props}
      title="批量补全手机号"
      trigger={
        <MyButtons.Default
          title="批量补全手机号"
          type="primary"
          size="middle"
        />
      }
      wrapperCol={{ span: 24 }}
      width={600}
      key={new Date().getTime()}
      form={form}
      onOpenChange={(open: boolean) => {
        if (open) {
          form.resetFields();
        }
      }}
      onFinish={async (values: any) => {
        try {
          // 按换行分割手机号并过滤空值
          const phoneArray = values.phoneInput
            .trim()
            .split(/\r?\n/)
            .filter(Boolean);

          // 提交多行手机号
          await Apis.Company.CompanyEmployees.CompletePhone({
            phone: phoneArray,
          });

          props.reload?.();
          message.success('手机号补全成功');
          return true;
        } catch (error) {
          console.error('补全手机号失败:', error);
          message.error('补全手机号失败，请重试');
          return false;
        }
      }}
      columns={[
        {
          key: 'phoneInput',
          title:
            '请在输入框里粘贴手机号。每行一个值，不超过2000条(excel中的数据，可直接复制/粘贴)',
          valueType: 'textarea',
          fieldProps: {
            placeholder: '请输入手机号，多个【按回车键】换行隔开',
            autoSize: { minRows: 8, maxRows: 12 },
            style: { resize: 'vertical' },
          },
          colProps: { span: 24 },
          formItemProps: {
            rules: [{ validator: validatePhones }],
          },
        },
      ]}
    />
  );
}
