/*
 * @Author: cclu
 * @Date: 2022-04-08 09:39:23
 * @LastEditTime: 2022-04-29 15:13:55
 * @LastEditors: Please set LastEditors
 * @Description: 注册
 * @FilePath: \cloud-platform\src\pages\User\register\index.tsx
 */
import { createPermissionProInst, registerPermissionProInst } from "@/pages/account/center/sevice";
import { getSMSIdentityCode } from "@/pages/account/setting/sevice";

import ProForm, { ProFormCaptcha, ProFormCheckbox, ProFormText, ProFormTextArea } from "@ant-design/pro-form";
import type { FormInstance } from "antd";

import { Button, Result } from "antd";
import { Card, message, Typography } from "antd";
import { useRef, useState } from "react";
import { history, Link } from "umi";
import type { PermissionProinstModel } from "@/pages/account/center/data";


const handleSubmit = async (values: PermissionProinstModel) => {

    const hide = message.loading('正在提交')

    const result = await createPermissionProInst(values as PermissionProinstModel)

    hide();
    if (result.Result_Code !== 100) {
        message.error(`${result.Result_Desc}`);
        return false;
    }
    // message.success('提交成功！请等待管理员完成审批。', 3).then(() => history.push('/user/login'));
    return true;
};
// 注册账号
const handleRegister = async (values: PermissionProinstModel) => {
    const hide = message.loading('正在提交')

    const result = await registerPermissionProInst(values as PermissionProinstModel)

    hide();
    if (result.Result_Code !== 100 && result.Result_Code !== 101) {
        message.error(`${result.Result_Desc}`);
        return false;
    }
    // message.success('提交成功！请等待管理员完成审批。', 3).then(() => history.push('/user/login'));
    return result.Result_Code;
}
/**
 * @description:  商户注册页面
 * @param {*}
 * @return {*}
 */
const RegisterContent: React.FC = () => {
    const [submitting, setSubmitting] = useState<boolean>()
    const registerForm = useRef<FormInstance>()
    const registerNextForm = useRef<FormInstance>()
    const [registerUserInfo, setRegisterUserInfo] = useState<any>()
    const [step, setStep] = useState<1 | 2 | 3 | 4 | 5>(1) // 1填写商户信息 2 系统内有商户匹配，注册成功 3 系统内无商户匹配， 4 完善商户信息 5 申请信息提交成功
    return (
        <div>
            <Typography.Title level={2} style={{ textAlign: 'center', paddingTop: 60, paddingBottom: 30 }}> {step === 1 || step === 4 ? '欢迎注册驿商云平台' : ''}</Typography.Title>
            <Card bordered={false} style={{ width: 910, margin: 'auto' }} bodyStyle={{ padding: 40 }}>
                {step === 1 &&
                    <ProForm
                        style={{ width: 425, margin: '0 auto' }}
                        submitter={{
                            searchConfig: {
                                submitText: '注册',
                            },
                            render: (_, dom) => dom.pop(),
                            submitButtonProps: {
                                loading: submitting,
                                size: 'large',
                                // danger: true,
                                style: {
                                    width: '100%',
                                    //   background: '#E2364B',
                                    marginTop: 24
                                },
                            },
                        }}
                        formRef={registerForm}
                        onFinish={async (values) => {

                            if (!values.isAgree || !values.isAgree.target.checked) {
                                message.error("请先同意条款后,再提交信息。")
                                return
                            }
                            setSubmitting(true)
                            const userInfo = {
                                ...values,
                                PERMISSIONAPPLY_TYPE: 1000, // 新增账户
                                // OWNERUNIT_NAME: ownerName,
                                SOURCE_PLATFORM: 0,
                                PERMISSIONAPPLY_STATE: 2000
                            }
                            setRegisterUserInfo(userInfo)
                            setSubmitting(false)
                            const data = await handleRegister({
                                PermissionApplyModel: userInfo
                            })

                            if (data === 100) {
                                registerForm.current?.resetFields();
                                setStep(2)

                            }
                            if (data === 101) {

                                setStep(4)

                            }
                        }}
                    >

                        <p style={{ textAlign: 'right' }}>
                            <Typography.Text>已有帐号？</Typography.Text>
                            <Link to="/user/login">去登录</Link>
                        </p>

                        <ProFormText
                            fieldProps={{
                                size: 'large',
                                prefix: <Typography.Text type="secondary" style={{ paddingRight: 16 }}>手机号码</Typography.Text>,
                            }}
                            name="USER_MOBILEPHONE"
                            rules={[
                                {
                                    required: true,
                                    message: ''
                                },
                                {
                                    pattern: /^1[3456789]\d{9}$/,
                                    message: '手机号不合法'
                                }
                            ]}

                            validateTrigger="onBlur"
                            hasFeedback
                            placeholder=""
                        />
                        <ProFormCaptcha
                            fieldProps={{
                                size: 'large',

                                prefix: <Typography.Text type="secondary" style={{ paddingRight: 16 }}>验证码</Typography.Text>,
                            }}
                            phoneName="USER_MOBILEPHONE"
                            name="IDENTITY_CODE"
                            captchaProps={{
                                size: 'large',
                                type: 'primary',
                                style: {
                                    backgroundColor: '#e9eff8',
                                    color: '#3591FE',
                                    borderColor: '#e9eff8',
                                }
                            }}

                            onGetCaptcha={async (phone) => {
                                await getSMSIdentityCode(phone)
                                message.success(`手机号 ${phone} 验证码发送成功!`);
                            }}
                            rules={[
                                {
                                    required: true,
                                    message: ''
                                }
                            ]}

                        />

                        <ProFormText.Password
                            fieldProps={{
                                size: 'large',
                                prefix: <Typography.Text type="secondary" style={{ paddingRight: 16 }}>设置密码</Typography.Text>,

                            }}
                            name="USER_PASSWORD"
                            rules={[
                                {
                                    required: true,
                                    message: ''
                                }
                            ]}
                            placeholder=""
                            hasFeedback
                        />
                        <ProFormText.Password
                            dependencies={['USER_PASSWORD']}
                            fieldProps={{
                                size: 'large',
                                prefix: <Typography.Text type="secondary" style={{ paddingRight: 16 }}>确认密码</Typography.Text>,

                            }}
                            hasFeedback
                            name="USER_COMFIRMPASSWORD"
                            rules={[
                                {
                                    required: true,
                                    message: ''
                                },
                                ({ getFieldValue }) => ({
                                    validator: (_, value) => {


                                        const password = getFieldValue('USER_PASSWORD')
                                        if (!value || password === value) {
                                            return Promise.resolve()
                                        }
                                        return Promise.reject(new Error('两次密码不一致'))
                                    }

                                })
                            ]}
                            placeholder=""

                        />

                        <ProFormCheckbox name="isAgree" style={{ marginTop: 24 }} >
                            我已阅读并同意遵守<Typography.Link>服务条款</Typography.Link>及<Typography.Link>隐私政策</Typography.Link>
                        </ProFormCheckbox>
                    </ProForm>
                }
                {step === 2 && <>
                    <Result
                        status="success"
                        title="注册成功，欢迎加入驿商云"
                        extra={<Button type="default" onClick={() => history.push('/user/login')}> 去登录</Button>}/>

                
                </>}
                {step === 3 && <>
                    <Result
                        status="success"
                        title="信息提交成功"
                        subTitle="您需要完善门店资料，以便加快审核进度。"
                        extra={<Button type="default" onClick={() => setStep(4)}>完善门店资料</Button>}/>

                    
                </>}
                {step === 4 && <>
                    <ProForm
                        style={{ width: 425, margin: '0 auto' }}
                        submitter={{
                            searchConfig: {
                                submitText: '注册',
                            },
                            render: (_, dom) => dom.pop(),
                            submitButtonProps: {
                                loading: submitting,
                                size: 'large',
                                // danger: true,
                                style: {
                                    width: '100%',
                                    //   background: '#E2364B',
                                    marginTop: 24
                                },
                            },
                        }}
                        formRef={registerNextForm}
                        onFinish={async (values) => {
                            setSubmitting(true)
                            const userInfo = {
                                ...values,
                                ...registerUserInfo

                            }
                            const data = await handleSubmit({
                                PermissionApplyModel: userInfo
                            })
                            if (data) {
                                setStep(5)
                                registerNextForm.current?.resetFields();
                            }
                            setSubmitting(false)
                            return data

                        }}
                    >
                        <ProFormText
                            fieldProps={{
                                size: 'large',
                                prefix: <Typography.Text type="secondary" style={{ paddingRight: 16 }}>姓名</Typography.Text>,
                            }}
                            name="USER_NAME"
                            rules={[
                                {
                                    required: true,
                                    message: ''
                                }
                            ]}
                            placeholder=""
                        />
                        <ProFormText
                            fieldProps={{
                                size: 'large',
                                prefix: <Typography.Text type="secondary" style={{ paddingRight: 16 }}>身份证</Typography.Text>,
                            }}
                            name="USER_IDCARD"
                            rules={[
                                {
                                    required: true,
                                    message: ''
                                },
                                {
                                    pattern: /^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|30|31)|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|x|X)$/,
                                    message: '身份证号不合法'
                                }
                            ]}
                            hasFeedback
                            placeholder=""
                        />
                        <ProFormText
                            fieldProps={{
                                size: 'large',
                                prefix: <Typography.Text type="secondary" style={{ paddingRight: 16 }}>省份/地区</Typography.Text>,
                            }}
                            placeholder=""
                            name="OWNERUNIT_NAME"
                            rules={[
                                {
                                    required: true,
                                    message: ''
                                }
                            ]}
                        />

                        <ProFormTextArea
                            fieldProps={{
                                size: 'large',
                                prefix: '',
                                autoSize: { minRows: 1, maxRows: 5 }
                            }}
                            name="SERVERPART_NAME"
                            placeholder="服务区"
                            rules={[
                                {
                                    required: true,
                                    message: ''
                                }
                            ]}
                        />
                        <ProFormTextArea
                            fieldProps={{
                                size: 'large',
                                prefix: '门店',
                                autoSize: { minRows: 1, maxRows: 5 }
                            }}
                            name="APPLYSHOP_NAME"
                            placeholder="门店"
                            rules={[
                                {
                                    required: true,
                                    message: ''
                                }
                            ]}
                        />
                        <ProFormTextArea
                            fieldProps={{
                                size: 'large',
                                prefix: '申请说明',
                                autoSize: { minRows: 1, maxRows: 5 }
                            }}
                            name="PERMISSIONAPPLY_REASON"
                            placeholder="申请说明"
                            rules={[
                                {
                                    required: true,
                                    message: ''
                                }
                            ]}
                        />


                    </ProForm>
                </>}
                {step === 5 && <>
                    <Result
                        status="success"
                        title="提交成功"
                        subTitle="系统已为您提交信息，请耐心等待管理员审核。审核时间：1-2个工作日。"
                        extra={<Button type="default" onClick={() => history.push('/user/login')}>去登录</Button>}
                    />

                    
                </>}
            </Card>
        </div>
    );

}

export default RegisterContent;