/*
 * @Author: cclu
 * @Date: 2022-04-28 10:47:35
 * @LastEditTime: 2022-05-13 11:54:57
 * @LastEditors: cclu lkrnchocolateaaron@gmail.com
 * @Description: 安全设置组件
 * @FilePath: \cloud-platform\src\pages\account\setting\components\SecurityView.tsx
 */
import { ModalForm, ProFormCaptcha, ProFormText } from "@ant-design/pro-form";
import { List, message } from "antd";
import { useState, useRef } from "react";

import type { FormInstance } from "antd";
import type { CurrentUser } from "umi";
import type { CloudChangeUserModel, CloudChangePassword } from "../data";

import { getSMSIdentityCode, modifyUserPassword, modifyUserMobilePhone } from "../sevice";

type ChangeType = 'password' | 'phone'

// 重置账号密码请求
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

}

// 重置账号密码请求
const handleMobilePhone = async (item: CloudChangeUserModel) => {
    const loading = message.loading("正在提交...")
    const result = await modifyUserMobilePhone(item)
    loading()
    if (result.Result_Code !== 100) {
        message.error(`${result.Result_Desc}` || `${result.Result_Code}:账户手机号修改失败`)
        return false
    }
    message.success("账户手机号修改成功！")
    return true

}
/**
 * @description: 安全组件主体
 * @param {CurrentUser} 用户信息
 * @return {*} 函数组件dom
 */
const SecurityView: React.FC<{ currentUser?: CurrentUser }> = ({ currentUser }) => {
    const [modelVisible, handleModelVisible] = useState<boolean>(false) // 弹出框操作状态
    const [changeType, setChangeType] = useState<ChangeType>('password') // 修改的数据类型
    const formRef = useRef<FormInstance>()
    return (
        <>
            <div className="title">安全设置</div>
            <List
                // itemLayout="horizontal"
                style={{ width: 480 }}
                footer={
                    <div style={{ height: 200 }}>

                    </div>
                }
            >
                <List.Item
                    actions={[<a key="list-loadmore-edit" onClick={() => {
                        setChangeType('password')
                        handleModelVisible(true)
                    }}>修改</a>]}
                >
                    <List.Item.Meta

                        title="账户密码"
                        description="当前密码：****"
                    />
                </List.Item>
                <List.Item
                    actions={[<a key="list-loadmore-edit" onClick={() => {
                        setChangeType('phone')
                        handleModelVisible(true)
                    }}>修改</a>]}
                >
                    <List.Item.Meta
                        title="密保手机"
                        description={`已绑定手机：${currentUser?.UserMobilephone ? `${currentUser?.UserMobilephone.substring(0, 3)}****${currentUser?.UserMobilephone.substring(currentUser?.UserMobilephone.length - 3, currentUser?.UserMobilephone.length)}` : '-'}`}
                    />
                </List.Item>
                <List.Item></List.Item>
            </List>
            <ModalForm

                title={changeType === 'password' ? '修改密码' : '修改手机号'}
                width={600}
                visible={modelVisible}
                formRef={formRef}
                modalProps={{
                    bodyStyle: {
                        paddingLeft: 80,
                        paddingRight: 120,
                        height: 300
                    }
                }}
                onVisibleChange={(value) => {
                    handleModelVisible(value)
                    if (!value) {

                        formRef.current?.resetFields();

                    }
                }}
                onFinish={async (value) => {
                    const newValue = { ...value, USER_ID_Encrypted: currentUser?.ID_Encrypted }
                    let success = null
                    if (changeType === 'password') {
                        delete newValue.ComfirmPassword
                        
                        success = await handelResetPassWord( {...newValue, DataType: 1000} )
                    } else {
                        success = await handleMobilePhone(newValue as CloudChangeUserModel)
                    }

                    if (success) {

                        return true
                    }
                    return false
                }}
            >
                {changeType === 'password' ? (<>
                    <ProFormText.Password
                        name="OriginPassword"
                        label="请输入原密码"
                        placeholder="原密码"
                        rules={[
                            {
                                required: true,
                                message: '请输入原密码',
                            },
                        ]}
                    />
                    <ProFormText.Password
                        name="NewPassword"
                        label="请输入新密码"
                        placeholder="新密码"
                        rules={[
                            {
                                required: true,
                                message: '请输入新密码',
                            },
                        ]}
                    />
                    <ProFormText.Password
                        name="ComfirmPassword"
                        label="再次输入新密码"
                        placeholder="新密码"
                        rules={[
                            {
                                required: true,
                                message: '请再次输入新密码',
                            },
                        ]}
                    /></>) :
                    (<>
                        <ProFormText
                            name="USER_MOBILEPHONE"
                            label="请输入新手机号码"
                            placeholder="新手机号码"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入新手机号码',
                                },
                            ]}
                        />
                        <ProFormCaptcha

                            // 手机号的 name，onGetCaptcha 会注入这个值
                            label="验证码"
                            phoneName="USER_MOBILEPHONE"
                            name="IDENTITY_CODE"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入验证码',
                                },
                            ]}
                            placeholder="请输入验证码"
                            // 如果需要失败可以 throw 一个错误出来，onGetCaptcha 会自动停止
                            // throw new Error("    ")
                            onGetCaptcha={async (phone) => {
                                await getSMSIdentityCode(phone)
                                message.success(`手机号 ${phone} 验证码发送成功!`);
                            }}
                        />
                    </>)}
            </ModalForm>
        </>
    );
}

export default SecurityView;