import React, { useEffect, useState, useRef } from 'react';
import {
  Banner,
  Button,
  Form,
  Row,
  Col,
  Typography,
  Spin,
} from '@douyinfe/semi-ui';
const { Text } = Typography;
import {
  API,
  removeTrailingSlash,
  showError,
  showSuccess,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';

export default function SettingsPaymentGatewayWechat(props) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [inputs, setInputs] = useState({
    WechatPayAppID: '',
    WechatPayMchID: '',
    WechatPayAPIv3Key: '',
    WechatPaySerialNo: '',
    WechatPayPubKeyID: '',
    WechatPayNotifyURL: '',
    WechatPayKeyPath: '',
    WechatPayPubKeyPath: '',
    WechatPayKeyB64: '',
    WechatPayPubKeyB64: '',
    WechatPayMinTopUp: 1,
    WechatPayUnitPrice: 7.0,
  });
  const [originInputs, setOriginInputs] = useState({});
  const formApiRef = useRef(null);

  useEffect(() => {
    if (props.options && formApiRef.current) {
      const currentInputs = {
        WechatPayAppID: props.options.WechatPayAppID || '',
        WechatPayMchID: props.options.WechatPayMchID || '',
        WechatPayAPIv3Key: props.options.WechatPayAPIv3Key || '',
        WechatPaySerialNo: props.options.WechatPaySerialNo || '',
        WechatPayPubKeyID: props.options.WechatPayPubKeyID || '',
        WechatPayNotifyURL: props.options.WechatPayNotifyURL || '',
        WechatPayKeyPath: props.options.WechatPayKeyPath || '',
        WechatPayPubKeyPath: props.options.WechatPayPubKeyPath || '',
        WechatPayKeyB64: props.options.WechatPayKeyB64 || '',
        WechatPayPubKeyB64: props.options.WechatPayPubKeyB64 || '',
        WechatPayMinTopUp:
          props.options.WechatPayMinTopUp !== undefined
            ? parseFloat(props.options.WechatPayMinTopUp)
            : 1,
        WechatPayUnitPrice:
          props.options.WechatPayUnitPrice !== undefined
            ? parseFloat(props.options.WechatPayUnitPrice)
            : 7.0,
      };
      setInputs(currentInputs);
      setOriginInputs({ ...currentInputs });
      formApiRef.current.setValues(currentInputs);
    }
  }, [props.options]);

  const handleFormChange = (values) => {
    setInputs(values);
  };

  const submitWechatSetting = async () => {
    if (props.options.ServerAddress === '') {
      showError(t('请先填写服务器地址'));
      return;
    }

    setLoading(true);
    try {
      const fields = [
        'WechatPayAppID',
        'WechatPayMchID',
        'WechatPayAPIv3Key',
        'WechatPaySerialNo',
        'WechatPayPubKeyID',
        'WechatPayNotifyURL',
        'WechatPayKeyPath',
        'WechatPayPubKeyPath',
        'WechatPayKeyB64',
        'WechatPayPubKeyB64',
      ];

      const options = [];

      for (const key of fields) {
        const value = inputs[key];
        if (value !== undefined && value !== originInputs[key]) {
          options.push({ key, value: value || '' });
        }
      }

      if (
        inputs.WechatPayUnitPrice !== undefined &&
        inputs.WechatPayUnitPrice !== null &&
        inputs.WechatPayUnitPrice !== originInputs.WechatPayUnitPrice
      ) {
        options.push({
          key: 'WechatPayUnitPrice',
          value: inputs.WechatPayUnitPrice.toString(),
        });
      }
      if (
        inputs.WechatPayMinTopUp !== undefined &&
        inputs.WechatPayMinTopUp !== null &&
        inputs.WechatPayMinTopUp !== originInputs.WechatPayMinTopUp
      ) {
        options.push({
          key: 'WechatPayMinTopUp',
          value: inputs.WechatPayMinTopUp.toString(),
        });
      }

      const requestQueue = options.map((opt) =>
        API.put('/api/option/', {
          key: opt.key,
          value: opt.value,
        }),
      );

      const results = await Promise.all(requestQueue);
      const errorResults = results.filter((res) => !res.data.success);
      if (errorResults.length > 0) {
        errorResults.forEach((res) => {
          showError(res.data.message);
        });
      } else {
        showSuccess(t('更新成功'));
        setOriginInputs({ ...inputs });
        props.refresh?.();
      }
    } catch (error) {
      showError(t('更新失败'));
    }
    setLoading(false);
  };

  return (
    <Spin spinning={loading}>
      <Form
        initValues={inputs}
        onValueChange={handleFormChange}
        getFormApi={(api) => (formApiRef.current = api)}
      >
        <Form.Section text={t('微信支付设置')}>
          <Text>
            微信支付 Native（扫码支付）V3 API 设置。请前往
            <a
              href='https://pay.weixin.qq.com/'
              target='_blank'
              rel='noreferrer'
            >
              微信支付商户平台
            </a>
            获取相关参数。
          </Text>
          <Banner
            type='info'
            description={`Webhook 填：${props.options.ServerAddress ? removeTrailingSlash(props.options.ServerAddress) : t('网站地址')}/api/wechat/pay/webhook`}
          />
          <Row gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }}>
            <Col xs={24} sm={24} md={8} lg={8} xl={8}>
              <Form.Input
                field='WechatPayAppID'
                label={t('AppID')}
                placeholder={t('微信公众号/小程序 AppID')}
              />
            </Col>
            <Col xs={24} sm={24} md={8} lg={8} xl={8}>
              <Form.Input
                field='WechatPayMchID'
                label={t('商户号')}
                placeholder={t('微信支付商户号')}
              />
            </Col>
            <Col xs={24} sm={24} md={8} lg={8} xl={8}>
              <Form.Input
                field='WechatPayAPIv3Key'
                label={t('APIv3 密钥')}
                placeholder={t('APIv3 密钥')}
                type='password'
              />
            </Col>
          </Row>
          <Row gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }}>
            <Col xs={24} sm={24} md={8} lg={8} xl={8}>
              <Form.Input
                field='WechatPaySerialNo'
                label={t('商户证书序列号')}
                placeholder={t('商户 API 证书序列号')}
              />
            </Col>
            <Col xs={24} sm={24} md={8} lg={8} xl={8}>
              <Form.Input
                field='WechatPayPubKeyID'
                label={t('微信支付公钥 ID')}
                placeholder={t('微信支付平台公钥 ID')}
              />
            </Col>
            <Col xs={24} sm={24} md={8} lg={8} xl={8}>
              <Form.Input
                field='WechatPayNotifyURL'
                label={t('回调通知 URL')}
                placeholder={t('支付成功后的回调地址')}
              />
            </Col>
          </Row>
          <Text style={{ marginTop: 16, display: 'block' }}>
            私钥/公钥支持文件路径和 Base64 两种方式（二选一）
          </Text>
          <Row gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }}>
            <Col xs={24} sm={24} md={8} lg={8} xl={8}>
              <Form.Input
                field='WechatPayKeyPath'
                label={t('商户私钥文件路径')}
                placeholder={t('如：/certs/apiclient_key.pem')}
              />
            </Col>
            <Col xs={24} sm={24} md={8} lg={8} xl={8}>
              <Form.Input
                field='WechatPayPubKeyPath'
                label={t('微信公钥文件路径')}
                placeholder={t('如：/certs/wechat_pub.pem')}
              />
            </Col>
          </Row>
          <Row gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }}>
            <Col xs={24} sm={24} md={8} lg={8} xl={8}>
              <Form.TextArea
                field='WechatPayKeyB64'
                label={t('商户私钥 Base64')}
                placeholder={t('私钥文件的 Base64 编码（与文件路径二选一）')}
                rows={3}
              />
            </Col>
            <Col xs={24} sm={24} md={8} lg={8} xl={8}>
              <Form.TextArea
                field='WechatPayPubKeyB64'
                label={t('微信公钥 Base64')}
                placeholder={t('公钥文件的 Base64 编码（与文件路径二选一）')}
                rows={3}
              />
            </Col>
          </Row>
          <Row gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }}>
            <Col xs={24} sm={24} md={8} lg={8} xl={8}>
              <Form.InputNumber
                field='WechatPayUnitPrice'
                precision={2}
                label={t('充值单价（元/配额单位）')}
                placeholder={t('例如：7，就是7元/配额单位')}
              />
            </Col>
            <Col xs={24} sm={24} md={8} lg={8} xl={8}>
              <Form.InputNumber
                field='WechatPayMinTopUp'
                label={t('最低充值数量')}
                placeholder={t('例如：1')}
              />
            </Col>
          </Row>
          <Button onClick={submitWechatSetting}>{t('更新微信支付设置')}</Button>
        </Form.Section>
      </Form>
    </Spin>
  );
}
