/*
 * @Author: cclu
 * @Date: 2022-04-28 10:47:35
 * @LastEditTime: 2025-03-25 15:37:36
 * @LastEditors: cclu 1106109051@qq.com
 * @Description: 用户个人信息设置
 * @FilePath: \cloud-platform\src\pages\account\setting\components\BaseView.tsx
 */
import { connect } from "umi"
import { useEffect, useState } from "react"
import ProForm, { ProFormText } from "@ant-design/pro-form"
import { Avatar, Button, message, Upload } from "antd"
import IconFont from "@/components/IconFont"
import SecurityView from "./SecurityView"

import type { CurrentUser, Dispatch } from "umi";
import type { CloudChangeUserModel } from "../data"
import type { ConnectState } from "@/models/connect"

import { changeUserHeadImg, modifyUserInfo } from "../sevice"
import { UploadOutlined } from "@ant-design/icons"

import './BaseView.less'

// 修改用户信息
const handelModifyUserInfo = async (item: CloudChangeUserModel, callBack?: () => void) => {
    const loading = message.loading("正在提交...")
    const result = await modifyUserInfo(item)
    loading()

    if (result.Result_Code !== 100) {
        message.error(`${result.Result_Desc}` || `${result.Result_Code}:账户信息修改失败`)
        return false
    }
    message.success("账户信息修改成功！")
    if (callBack) {

        callBack.call(true)
    }
    return true
}

// 头像组件 方便以后独立，增加裁剪之类的功能
const AvatarView = ({ avatar, uploadPhoto }: { avatar: string, uploadPhoto: (info: any) => void }) => (
    <>
        <div className="avatar_title">头像</div>
        <div className="avatar">
            {avatar ? <Avatar src={avatar} alt="avatar" size={144} /> :
                <IconFont name='icon-touxiang' size="144"></IconFont>}
        </div>
        <Upload showUploadList={false}

            customRequest={uploadPhoto} >
            <div className="button_view">
                <Button>
                    <UploadOutlined />
                    更换头像
                </Button>
            </div>
        </Upload>
    </>
);
/**
 * @description: 个人信息设置主体组件
 * @param {currentUser} 用户信息
 * @param {dispatch} 更新方法
 * @return {*}
 */
const BaseView: React.FC<{ currentUser: CurrentUser | undefined, dispatch: Dispatch }> = ({ currentUser, dispatch }) => {
    const [avatar, setAvatar] = useState<string>(currentUser?.HeadImgUrl || '')

    // 更新图片
    const uploadPhoto = async (info: any) => {
        const file = info.file;
        const fileType = file.type;
        // 允许的图片类型
        const allowedTypes = ["image/jpeg", "image/jpg", "image/png"];

        // 校验文件类型
        if (!allowedTypes.includes(fileType)) {
            message.error("仅支持上传 JPG、JPEG 和 PNG 格式的图片！");
            return;
        }
        const formData = new FormData();
        formData.append('files', info.file);
        formData.append('User_Id_Encrypted', currentUser?.ID_Encrypted || '');
        if (info.filename) {
            const success = await changeUserHeadImg(formData)

            if (success && success.Result_Code === 100) {
                setAvatar(success.Result_Data?.ImageUrl)
                dispatch({ type: 'user/saveCurrentUser', payload: { ...currentUser, HeadImgUrl: success.Result_Data?.ImageUrl } })
            }
        } else {

            message.error("您上传的图片不存在.")
        }
    }
    return (
        <div className="baseView">
            <div className="left">
                <ProForm<CloudChangeUserModel>
                    onFinish={async (value) => {

                        const newValue = { ...value, USER_ID_Encrypted: currentUser?.ID_Encrypted }
                        const success = await handelModifyUserInfo(newValue as CloudChangeUserModel)

                        if (success) {
                            dispatch({ type: 'user/saveCurrentUser', payload: { ...currentUser, Name: newValue?.USER_NAME } })
                            return true
                        }
                        return false
                    }}
                    submitter={{

                        // 配置按钮的属性
                        resetButtonProps: {
                            style: {
                                // 隐藏重置按钮
                                display: 'none',
                            },
                        }
                    }}
                >
                    <ProFormText
                        label="用户名称"
                        name="USER_NAME"
                        width="md"
                        initialValue={currentUser?.Name}
                        required
                    >
                    </ProFormText>
                    <div style={{ marginTop: 40 }}></div>
                    {/* 安全配置 */}
                    <SecurityView currentUser={currentUser} />

                </ProForm>
            </div>
            <div className="right-avatar">
                <AvatarView
                    avatar={avatar}
                    uploadPhoto={uploadPhoto}
                ></AvatarView>
            </div>
        </div>
    )
}

export default connect(({ user }: ConnectState) => ({
    currentUser: user.currentUser
}))(BaseView)