import React, { useEffect, useState } from 'react';
import styles from './index.less';
import {
  ResultPage,
  Button,
  Form,
  Input,
  Radio,
  Space,
  Steps,
  TextArea,
  Checkbox,
  Toast,
  Card,
  Result,
} from 'antd-mobile/es';
import { useRequest } from '@@/plugin-request/request';
import { getEnrollInfo, pay, sign, submit } from '@/services/enroll';
import {
  ENROLL_STATUS_AGREED,
  ENROLL_STATUS_COMMENTED,
  ENROLL_STATUS_CREATED,
  ENROLL_STATUS_FINISHED,
  ENROLL_STATUS_PAY_AGREED,
  ENROLL_STATUS_PAY_REJECT,
  ENROLL_STATUS_REJECTED,
  ENROLL_STATUS_SIGNED,
  ENROLL_STATUS_SUBMIT_INFO,
  ENROLL_STATUS_SUBMIT_PAY,
} from '@/services/constants';
import { FormInstance } from 'antd';
import Cookies from 'js-cookie';
import AliyunOSSUpload from '@/components/Oss/AliyunOSSUpload';
import { getPageQuery } from '@/utils/utils';

const { Step } = Steps;

const Detail: React.FC = () => {
  const submitInfoFormRef = React.createRef<FormInstance>();
  const submitPayFormRef = React.createRef<FormInstance>();

  const [sourceType, setSourceType] = useState(-1);
  const [idCard, setIdCard] = useState('');
  const [agree, setAgree] = useState(true);
  const id = getPageQuery().id;

  const token = Cookies.get('et');
  if (!token) {
    window.location.href = '/enroll/login?id=' + (id || 1);
    return;
  }

  const onSubmitInfo = async (values: any) => {
    const response = await submit({
      ...values,
      token: Cookies.get('et'),
    });
    if (response.code === 200) {
      await run();
      return;
    }
    Toast.show({
      icon: 'fail',
      content: response.message,
    });
  };

  const onSubmitPayInfo = async (values: any) => {
    const response = await pay(
      Cookies.get('et') as string,
      values.payInfo,
      values.taxNumber,
      values.taxInstitutionName,
      values.taxInstitutionAddress,
      values.taxBank,
      values.taxBankAccount,
      values.taxPhone,
    );
    if (response.code === 200) {
      await run();
      return;
    }
    Toast.show({
      icon: 'fail',
      content: response.message,
    });
  };

  const onSign = async (idCard) => {
    const response = await sign(Cookies.get('et') as string, idCard);
    if (response.code === 200) {
      await run();
      return;
    }
    Toast.show({
      icon: 'fail',
      content: response.message,
    });
  };

  const getStatus = () => {
    if (
      enrollInfo?.status == ENROLL_STATUS_CREATED ||
      enrollInfo?.status == ENROLL_STATUS_SUBMIT_INFO ||
      enrollInfo?.status == ENROLL_STATUS_REJECTED
    ) {
      return 0;
    } else if (enrollInfo?.status == ENROLL_STATUS_AGREED) {
      return 1;
    } else if (
      enrollInfo?.status == ENROLL_STATUS_SIGNED ||
      enrollInfo?.status == ENROLL_STATUS_SUBMIT_PAY ||
      enrollInfo?.status == ENROLL_STATUS_PAY_REJECT
    ) {
      return 2;
    } else if (
      enrollInfo?.status == ENROLL_STATUS_PAY_AGREED ||
      enrollInfo?.status == ENROLL_STATUS_FINISHED ||
      enrollInfo?.status == ENROLL_STATUS_COMMENTED
    ) {
      return 3;
    } else {
      return 0;
    }
  };

  const { data: enrollInfo, run } = useRequest(() => {
    return getEnrollInfo(Cookies.get('et') as string);
  });

  return (
    <div className={styles.container}>
      <div>
        <div className={styles.step}>
          <Steps current={getStatus()}>
            <Step title="报名信息" />
            <Step title="签署协议" />
            <Step title="费用支付" />
            <Step title="完成报名" />
          </Steps>
        </div>
        <div className={styles.content}>
          {enrollInfo?.status == ENROLL_STATUS_CREATED && (
            <div>
              <Form
                ref={submitInfoFormRef}
                name="form"
                // layout='horizontal'
                onFinish={onSubmitInfo}
                footer={null}
                className={styles.form}
              >
                <Form.Item
                  name="name"
                  label="姓名"
                  rules={[
                    { required: true, message: '姓名不能为空' },
                    { max: 50 },
                  ]}
                >
                  <Input placeholder="请输入姓名" />
                </Form.Item>
                <Form.Item
                  name="email"
                  label="公司邮箱"
                  rules={[
                    { required: true, message: '公司邮箱不能为空' },
                    { max: 50 },
                    {
                      pattern:
                        /^[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$/,
                      message: '邮箱格式错误',
                    },
                  ]}
                >
                  <Input placeholder="请输入公司邮箱" />
                </Form.Item>
                <Form.Item
                  name="institution"
                  label="公司名字全称"
                  rules={[
                    { required: true, message: '公司名字全称不能为空' },
                    { max: 50 },
                  ]}
                >
                  <Input placeholder="请输入公司名字全称" />
                </Form.Item>
                <Form.Item
                  name="business"
                  label="公司主营业务"
                  rules={[
                    { required: true, message: '公司主营业务不能为空' },
                    { max: 50 },
                  ]}
                >
                  <Input placeholder="请输入公司主营业务" />
                </Form.Item>
                <Form.Item
                  name="revenue"
                  label="公司营收规模"
                  rules={[{ required: true, message: '公司营收规模不能为空' }]}
                >
                  <Radio.Group>
                    <Space direction="vertical">
                      <Radio value="5亿以下" style={{ marginTop: 12 }}>
                        5亿以下
                      </Radio>
                      <Radio value="5亿-10亿">5亿-10亿</Radio>
                      <Radio value="10亿-50亿">10亿-50亿</Radio>
                      <Radio value="50亿-100亿">50亿-100亿</Radio>
                      <Radio value="100亿-500亿">100亿-500亿</Radio>
                      <Radio value="500亿-1000亿">500亿-1000亿</Radio>
                      <Radio value="1000亿以上">1000亿以上</Radio>
                    </Space>
                  </Radio.Group>
                </Form.Item>
                <Form.Item
                  name="numberOfPeople"
                  label="公司人数"
                  rules={[{ required: true, message: '公司人数不能为空' }]}
                >
                  <Radio.Group>
                    <Space direction="vertical">
                      <Radio value="1-50" style={{ marginTop: 12 }}>
                        1-50
                      </Radio>
                      <Radio value="50-100">50-100</Radio>
                      <Radio value="100-500">100-500</Radio>
                      <Radio value="500-1000">500-1000</Radio>
                      <Radio value="1000-5000">1000-5000</Radio>
                      <Radio value="5000-10000">5000-10000</Radio>
                      <Radio value="10000人以上">10000人以上</Radio>
                    </Space>
                  </Radio.Group>
                </Form.Item>
                <Form.Item
                  name="department"
                  label="所在部门"
                  rules={[
                    { required: true, message: '所在部门不能为空' },
                    { max: 50 },
                  ]}
                >
                  <Input placeholder="请输入所在部门" />
                </Form.Item>
                <Form.Item
                  name="position"
                  label="职务或角色"
                  rules={[
                    { required: true, message: '职务或角色不能为空' },
                    { max: 50 },
                  ]}
                >
                  <Input placeholder="请输入职务或角色" />
                </Form.Item>
                <Form.Item
                  name="source"
                  label="获取信息来源"
                  rules={[{ required: true, message: '获取信息来源不能为空' }]}
                >
                  <Radio.Group
                    onChange={(value) => {
                      setSourceType(value);
                    }}
                  >
                    <Space direction="vertical">
                      <Radio value="1" style={{ marginTop: 12 }}>
                        高潜公众号
                      </Radio>
                      <Radio value="2">战略解码公众号</Radio>
                      <Radio value="3">朋友推荐</Radio>
                      <Radio value="0">其他来源</Radio>
                    </Space>
                  </Radio.Group>
                </Form.Item>
                {sourceType == 3 && (
                  <Form.Item
                    name="sourceRemark"
                    label="朋友姓名"
                    rules={[
                      { required: true, message: '朋友姓名不能为空' },
                      { max: 50 },
                    ]}
                  >
                    <Input placeholder="请输入朋友姓名" />
                  </Form.Item>
                )}

                {sourceType == 0 && (
                  <Form.Item
                    name="sourceRemark"
                    label="其他来源"
                    rules={[
                      { required: true, message: '其他来源不能为空' },
                      { max: 50 },
                    ]}
                  >
                    <Input placeholder="请输入其他来源" />
                  </Form.Item>
                )}
                <Form.Item
                  name="remark"
                  label="其他备注信息"
                  rules={[{ max: 200 }]}
                >
                  <TextArea
                    placeholder="请输入其他备注信息"
                    maxLength={200}
                    rows={2}
                    showCount
                  />
                </Form.Item>
              </Form>

              <Button
                block
                shape="rounded"
                type="submit"
                color="primary"
                size="middle"
                className={styles.submit}
                onClick={() => {
                  submitInfoFormRef.current?.submit();
                }}
              >
                提交
              </Button>
            </div>
          )}
          {enrollInfo?.status == ENROLL_STATUS_SUBMIT_INFO && (
            <div className={styles.auditWrapper}>
              <Result
                status="waiting"
                title="等待审核"
                description="您已经提交成功，等待后台审核中"
              />
            </div>
          )}
          {enrollInfo?.status == ENROLL_STATUS_REJECTED && (
            <div className={styles.auditWrapper}>
              <Result
                status="error"
                title="报名未通过"
                description="您未通过报名，请联系顾问后再试"
              />
            </div>
          )}
          {enrollInfo?.status == ENROLL_STATUS_AGREED && (
            <div>
              <div className={styles.agreementWrapper}>
                <div className={styles.title}>学员承诺书</div>
                <div className={styles.content}>
                  {enrollInfo.agreementContent}
                </div>
                <div className={styles.signName}>
                  <Input
                    value={enrollInfo.name}
                    readOnly
                    style={{ '--text-align': 'right' }}
                  />
                  <Input
                    value={idCard}
                    placeholder="请输入身份证号"
                    style={{ '--text-align': 'right', marginTop: 12 }}
                    onChange={(val) => {
                      setIdCard(val);
                    }}
                  />
                </div>
                <div>
                  <Checkbox
                    defaultChecked
                    onChange={(v) => {
                      setAgree(v);
                    }}
                  >
                    我同意
                  </Checkbox>
                </div>
              </div>

              <Button
                block
                shape="rounded"
                type="submit"
                color="primary"
                size="middle"
                className={styles.submit}
                onClick={() => {
                  if (!agree) {
                    Toast.show('请先同意承诺书');
                    return;
                  }
                  if (!idCard) {
                    Toast.show('请输入身份证号');
                    return;
                  }

                  onSign(idCard);
                }}
              >
                下一步
              </Button>
            </div>
          )}
          {enrollInfo?.status == ENROLL_STATUS_SIGNED && (
            <div>
              <div className={styles.payWrapper}>
                <div className={styles.cardWrapper}>
                  <Card title="支付信息">
                    <div className={styles.payInfo}>
                      公司名称: 高潜(北京)咨询有限公司
                    </div>
                    <div className={styles.payInfo}>
                      开户行: 中国银行北京国际贸易中心支行
                    </div>
                    <div className={styles.payInfo}>账号: 325958901163</div>
                    <div className={styles.payInfo}>
                      (汇款请备注：姓名+手机号+单位)
                    </div>
                  </Card>
                </div>

                <div className={styles.payForm}>
                  <Form
                    ref={submitPayFormRef}
                    name="form"
                    // layout='horizontal'
                    onFinish={onSubmitPayInfo}
                    footer={null}
                    className={styles.form}
                  >
                    <Form.Item
                      name="payInfo"
                      label="支付截图"
                      rules={[{ required: true, message: '支付截图不能为空' }]}
                    >
                      <div style={{ paddingTop: 8 }}>
                        <AliyunOSSUpload
                          uploaded={(url: string) => {
                            submitPayFormRef.current?.setFieldsValue({
                              payInfo: url,
                            });
                          }}
                          isImg={true}
                        />
                      </div>
                    </Form.Item>
                    <Form.Header>如需开票，请提供您的开票信息</Form.Header>
                    <Form.Item
                      name="taxNumber"
                      label="纳税人识别号"
                      rules={[{ max: 50 }]}
                    >
                      <Input placeholder="请输入纳税人识别号" />
                    </Form.Item>
                    <Form.Item
                      name="taxInstitutionName"
                      label="公司名称"
                      rules={[{ max: 50 }]}
                    >
                      <Input placeholder="请输入公司名称" />
                    </Form.Item>
                    <Form.Item
                      name="taxInstitutionAddress"
                      label="公司地址"
                      rules={[{ max: 50 }]}
                    >
                      <Input placeholder="请输入公司地址" />
                    </Form.Item>
                    <Form.Item
                      name="taxBank"
                      label="开户行名称"
                      rules={[{ max: 50 }]}
                    >
                      <Input placeholder="请输入开户行名称" />
                    </Form.Item>
                    <Form.Item
                      name="taxBankAccount"
                      label="账号"
                      rules={[{ max: 50 }]}
                    >
                      <Input placeholder="请输入账号" />
                    </Form.Item>
                    <Form.Item
                      name="taxPhone"
                      label="电话"
                      rules={[{ max: 50 }]}
                    >
                      <Input placeholder="请输入电话" />
                    </Form.Item>
                  </Form>
                </div>
              </div>

              <Button
                block
                shape="rounded"
                type="submit"
                color="primary"
                size="middle"
                className={styles.submit}
                onClick={() => {
                  submitPayFormRef.current?.submit();
                }}
              >
                提交
              </Button>
            </div>
          )}

          {enrollInfo?.status == ENROLL_STATUS_SUBMIT_PAY && (
            <div className={styles.auditWrapper}>
              <Result
                status="waiting"
                title="等待确认支付"
                description="您的支付信息已经提交，等待后台审核中"
              />
            </div>
          )}
          {enrollInfo?.status == ENROLL_STATUS_PAY_REJECT && (
            <div className={styles.auditWrapper}>
              <Result
                status="error"
                title="支付未通过"
                description="您的支付未通过审核，请联系顾问后再试"
              />
            </div>
          )}

          {enrollInfo?.status == ENROLL_STATUS_PAY_AGREED && (
            <div>
              <div className={styles.courseWrapper}>
                <div className={styles.title}>课前通知</div>
                <div className={styles.content}>
                  {enrollInfo?.course?.notice}
                </div>
                <a
                  href={enrollInfo?.course?.pdfUrl}
                  className={styles.downloadPdf}
                >
                  会议指南PDF下载
                </a>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default Detail;
