/*
 * @Author: cclu lkrnchocolateaaron@gmail.com
 * @Date: 2022-05-13 10:18:06
 * @LastEditors: cclu lkrnchocolateaaron@gmail.com
 * @LastEditTime: 2022-05-13 14:47:47
 * @FilePath: \cloud-platform\src\pages\User\forgetPassword\index.tsx
 * @Description: 商户忘记密码页面
 */

import { getSMSIdentityCode, handleModifyPasswordByPassport, modifyUserPassword } from "@/pages/account/setting/sevice";

import ProForm, { ProFormCaptcha, ProFormText } 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 } from "umi";

import type { CloudChangePassword } from "@/pages/account/setting/data";

const handelResetPassWord = async (item: CloudChangePassword) => {
    const loading = message.loading("正在提交...")
    const result = await modifyUserPassword(item)
    loading()
    if (result.Result_Code !== 100) {
        message.error(`${result.Result_Desc}` || `${result.Result_Code}:账户密码重置失败`)
        return false
    }
    message.success("账户密码重置成功！")
    return true

}
/**
 * @description:  商户忘记密码页面
 * @param {*}
 * @return {*}
 */
const ForgetPasswordContent: React.FC = () => {
    const [submitting, setSubmitting] = useState<boolean>()
    const newPasswordForm = useRef<FormInstance>()

    const [step, setStep] = useState<1 | 2>(1) // 1填写信息 2 修改成功
    return (
        <div>
            <Typography.Title level={2} style={{ textAlign: 'center', paddingTop: 60, paddingBottom: 30 }}> {step === 1 ? '驿商云重置密码' : ''}</Typography.Title>
            <Card bordered={false} style={{ width: 910, margin: 'auto', height: 560 }} bodyStyle={{ padding: 80 }}>
                {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={newPasswordForm}
                        onFinish={async (values) => {
                            setSubmitting(true)
                            const newValue = { ...values, DataType: 2000 }
                            let success = null

                            delete newValue.USER_COMFIRMPASSWORD

                            console.log('newValue', newValue);


                            success = await handleModifyPasswordByPassport({ ...newValue })
                            console.log('success', success);
                            if (success.Result_Code === 100) {
                                message.success(success.Result_Data)
                                setStep(2)
                                return true
                            } else {
                                message.error(success.Result_Desc)
                                return false
                            }
                            // success = await handelResetPassWord({ ...newValue })
                            // setSubmitting(false)
                            // if (success) {

                            //     setStep(2)
                            //     return true
                            // }
                            // return false
                        }}
                    >
                        {/* 原手机号验证方式 - 已注释
                        <ProFormText
                            fieldProps={{
                                size: 'large',
                                prefix: <Typography.Text type="secondary" style={{ paddingRight: 16 }}>手机号</Typography.Text>,
                            }}
                            name="UserMobilephone"
                            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="UserMobilephone"
                            name="IdentityCode"
                            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
                            fieldProps={{
                                size: 'large',
                                prefix: <Typography.Text type="secondary" style={{ paddingRight: 16 }}>账号</Typography.Text>,
                            }}
                            name="PassportName"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入账号'
                                }
                            ]}

                            validateTrigger="onBlur"
                            hasFeedback
                            placeholder="请输入账号"
                        />
                        <ProFormText.Password
                            fieldProps={{
                                size: 'large',
                                prefix: <Typography.Text type="secondary" style={{ paddingRight: 16 }}>原密码</Typography.Text>,
                            }}
                            name="OriPassword"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入原密码'
                                }
                            ]}
                            placeholder="请输入原密码"
                        />

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

                            }}
                            name="NewPassword"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入新密码'
                                },
                                {
                                    min: 8,
                                    message: '密码长度至少8位'
                                },
                                {
                                    validator: (_, value) => {
                                        if (!value) return Promise.resolve();

                                        // 检查密码复杂度：数字、大小写字母、特殊字符中的2种以上组成
                                        const hasNumber = /\d/.test(value);
                                        const hasLowercase = /[a-z]/.test(value);
                                        const hasUppercase = /[A-Z]/.test(value);
                                        const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value);

                                        const typeCount = [hasNumber, hasLowercase, hasUppercase, hasSpecialChar].filter(Boolean).length;

                                        if (typeCount < 2) {
                                            return Promise.reject(new Error('密码不符合安全要求，请设置长度8位以上，由数字、大小写字母、特殊字符中的2种以上组成'));
                                        }

                                        return Promise.resolve();
                                    }
                                }
                            ]}
                            placeholder=""
                            hasFeedback
                            extra={
                                <Typography.Text type="secondary" style={{ fontSize: '12px' }}>
                                    密码规则：长度8位以上，由数字、大小写字母、特殊字符中的2种以上组成
                                </Typography.Text>
                            }
                        />
                        <ProFormText.Password
                            dependencies={['NewPassword']}
                            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('NewPassword')
                                        if (!value || password === value) {
                                            return Promise.resolve()
                                        }
                                        return Promise.reject(new Error('两次密码不一致'))
                                    }

                                })
                            ]}
                            placeholder=""

                        />


                    </ProForm>
                }
                {step === 2 && <>
                    <Result
                        status="success"
                        title="密码重置成功"
                        extra={<Button type="default" onClick={() => history.push('/user/login')}> 去登录</Button>} />


                </>}



            </Card>
        </div>
    );

}

export default ForgetPasswordContent;