import React from "react";
import {Button, Col, Container, Form, FormControl, Image, Row} from "react-bootstrap";
import {Sex, User, UserEdit, UserType} from "../entity";
import {Input} from "../ui/InputGroup";
import {JSONResponse, Method, request} from "../interface";
import {
    EmptyBodyTransform,
    FindUserInfo,
    FindUserInfoTransform,
    ModifyPwdMessage,
    ModifyPwdTransform,
    SimpleMessage
} from "../result";
import {MyDialog} from "../ui/MyDialog";
import {Address} from "../ui/Address";
import {Cookies} from "react-cookie";
import {user_type_cookie} from "../account/PropCookie";
import {Api, prefix} from "../api";
import {UploadImg} from "../ui/UploadImg";

/**
 * 图片尺寸限制
 */
const maxImageSize={
    width:100,
    height:100
}

/**
 * 个人信息
 */
export class MyInfo extends React.Component<
    {
        //刷新用户信息
        refreshFun?:Function,
        //查看用户id
        userId:string;
        //查看本人
        isOwn:boolean;
        //是否添加好友
        isAdd:boolean;
        cookies?:Cookies;
    }, {
        userEdit:UserEdit,
        userInfo?:User,
        result:JSX.Element|null,
        activityImgFile?:any;
    }>{

    private ages:Array<number>

    constructor(props: Readonly<any>) {
        super(props);

        this.ages=this.createAge()

        this.state={
            userEdit:{
                contentEditable:false,
                modifyPassword:false,
                oldPassword:"",
                newPassword:"",
                confirmNewPwd:"",
            },
            result:null,
        }
    }


    createAge(){
        let age=[]
        for(let i=18;i<100;i++){
            age.push(i)
        }
        return age
    }

    /**
     * 加载用户信息
     */
    loadInfo(){

        if(!this.props.userId){
            return
        }
        let that=this

        request(Api.account.find+"/"+this.props.userId,Method.GET, {},new FindUserInfoTransform(),function(res:FindUserInfo){
            switch (res.customResult) {
                case SimpleMessage.fail:
                    that.setState({
                        result:<h3 className="text-danger text-center">获取用户信息失败，请联系管理员</h3>
                    });break
                case SimpleMessage.ok:
                    that.setState({
                        userInfo:res.info,
                        userEdit: {
                            headImg:res.info?.headImg,
                            userId:res.info?.userId,
                            name:res.info?.name,
                            age:res.info?.age,
                            mobile:+(res.info?.mobile||""),
                            email:res.info?.email,
                            serviceAddress:res.info?.serviceAddress,
                            info:res.info?.info,
                            userType:res.info?.userType,
                            sex:res.info?.sex,

                            contentEditable:false,
                            modifyPassword:false,
                            oldPassword:"",
                            newPassword:"",
                            confirmNewPwd:"",
                        }
                    })
                    break

            }
        })
    }

    componentDidMount() {
        this.loadInfo()
    }

    /**
     * 进入编辑模式
     */
    openEdit(){
        this.setState({
            userEdit:{...this.state.userEdit,...{contentEditable:true}}
        })
    }

    /**
     * 进入修改密码
     */
    openModifyPwd(){
        this.setState({
            userEdit:{...this.state.userEdit,...{ modifyPassword:true}}
        })
    }

    /**
     * 修改密码
     */
    modifyPwd(){
        this.setState({
            userEdit:{...this.state.userEdit,...{ modifyPassword:false}}
        })

        let that=this

        request(Api.account.updatePwd,Method.POST, {
            newPassword:this.state.userEdit.newPassword,
            oldPassword:this.state.userEdit.oldPassword
        },new ModifyPwdTransform(),function (res:JSONResponse<ModifyPwdMessage>) {
            switch (res.customResult) {
                case ModifyPwdMessage.fail:
                    that.setState({
                        result:<h3 className="text-danger text-center">修改密码失败，请联系管理员</h3>
                    });break
                case ModifyPwdMessage.pwd_fail:
                    that.setState({
                        result:<h3 className="text-danger text-center">修改密码失败，原密码错误</h3>
                    });break
                case ModifyPwdMessage.ok:
                    that.setState({
                        result:<h3 className="text-info text-center">修改密码成功</h3>
                    });break
            }
        })
    }

    /**
     * 保存信息
     */
    doSave(){
        this.setState({
            userEdit:{...this.state.userEdit,...{    contentEditable:false}}
        })

        let that=this

        request(Api.account.update,Method.PUT, {
            headImg:this.state.userEdit.headImg||"",
            name:this.state.userEdit.name||"",
            age:this.state.userEdit.age+""||"",
            mobile:this.state.userEdit.mobile+""||"",
            email:this.state.userEdit.email||"",
            serviceAddress:this.state.userEdit.serviceAddress||"",
            info:this.state.userEdit.info||"",
            userType:this.state.userEdit.userType||"",
            sex:this.state.userEdit.sex||"",
            activityImgFile:this.state.activityImgFile?this.state.activityImgFile:null
        },new EmptyBodyTransform(),function (res:JSONResponse<SimpleMessage>) {
            switch (res.customResult) {
                case SimpleMessage.fail:
                    that.setState({
                        result:<h3 className="text-danger text-center">更新信息失败，请联系管理员</h3>
                    });break
                case SimpleMessage.ok:
                    that.loadInfo();
                    //TODO 更新用户身份

                    that.setState({
                        result:<div className="text-center">
                            <h3 className="text-info text-center">更新信息成功</h3>
                        </div>
                    })
                    break
            }
        })

    }


    /**
     * 添加好友
     */
    addFriend(){
        let that=this
        request(Api.account.friend,Method.POST, {targetUserId:this.props.userId},new EmptyBodyTransform(),function (res:JSONResponse<SimpleMessage>) {
            switch (res.customResult) {
                case SimpleMessage.ok:
                    that.setState({
                        result:<h3 className="text-info text-center">成功发送邀请</h3>
                    });break
                case SimpleMessage.fail:
                    that.setState({
                        result:<h3 className="text-danger text-center">发送好友邀请失败,请联系管理员</h3>
                    });break
            }
        })
    }

    /**
     * 同意好友邀请
     */
    agreeFriend(){

    }


    render() {

        return (
            <Container className="overflow-auto">
                <Row>
                    <Col className="p-3 text-center">
                        {this.state.userEdit.contentEditable?
                            <UploadImg tip={"点击更新头像"} maxImageSize={maxImageSize} onChange={(value:string)=>this.setState({activityImgFile:value})} />
                            :
                            <Image className="chat-headImg" src={this.state.userInfo?.headImg?prefix.image+this.state.userInfo.headImg:""}/>}
                    </Col>
                </Row>
                {/*TODO 表单校验*/}
                <Row>
                    <Col className="border-info border p-3 d-flex justify-content-center align-items-center">
                        {this.state.userInfo?.userId}
                    </Col>
                    <Col className="border-info border p-3 text-center">
                        {this.state.userEdit.contentEditable?
                            <FormControl value={this.state.userEdit.name} onChange={(e)=>this.setState({
                                userEdit:{...this.state.userEdit,...{    name:e.target.value}}
                            })}/>
                            :this.state.userInfo?.name}</Col>
                    <Col className="border-info border p-3 text-center">
                        {this.state.userEdit.contentEditable?
                            <FormControl as={"select"} value={this.state.userEdit.age} onChange={(e)=>this.setState({
                                userEdit:{...this.state.userEdit,...{     age:+e.target.value}}
                            })}>
                                {this.ages.map(value=><option key={value} value={value}>{value}</option>)}
                            </FormControl>
                            :this.state.userInfo?.age}</Col>
                </Row>
                <Row>
                    <Col className="border-info border p-3 text-center">
                        {this.state.userEdit.contentEditable?
                            <FormControl value={this.state.userEdit.mobile} type={"number"} onChange={(e)=>this.setState({
                                userEdit:{...this.state.userEdit,...{    mobile:+e.target.value}}
                            })}/>
                            :this.state.userInfo?.mobile}
                    </Col>
                    <Col className="border-info border p-3 text-center">
                        {this.state.userEdit.contentEditable?
                            <FormControl value={this.state.userEdit.email} onChange={(e)=>this.setState({
                                userEdit:{...this.state.userEdit,...{  email:e.target.value}}
                            })}/>
                            :this.state.userInfo?.email}
                    </Col>
                    <Col className="border-info border p-3 text-center">
                        {this.state.userEdit.contentEditable?
                            <FormControl value={this.state.userEdit.sex} as={"select"} onChange={event => this.setState({
                                userEdit:{...this.state.userEdit,...{  sex:event.target.value}}
                            })}>
                                <option value={Sex.man}>男</option>
                                <option value={Sex.women}>女</option>
                            </FormControl>:this.state.userInfo?.sex===Sex.man?"男":"女"}
                    </Col>
                </Row>
                <Row>
                    <Col className="border-info border p-3 text-center">
                        {this.state.userEdit.contentEditable?
                            <Address col={12} value={this.state.userEdit.serviceAddress}  onChange={(value:string)=>this.setState({
                                userEdit:{...this.state.userEdit,...{  serviceAddress:value}}
                            })}/>:this.state.userInfo?.serviceAddress}
                    </Col>
                    <Col className="border-info border p-3 text-center">
                        {this.state.userEdit.contentEditable?
                            <FormControl value={this.state.userEdit.userType} as={"select"} onChange={(e)=>this.setState({
                                userEdit:{...this.state.userEdit,...{ userType:e.target.value}}
                            })}>
                                <option value={UserType.seekHelp}>服务发起者</option>
                                <option value={UserType.help}>服务接受者</option>
                            </FormControl>:
                            this.state.userInfo?.userType===UserType.help?"等待前往帮助":"等待接受帮助"}
                    </Col>
                </Row>
                <Row>
                    <Col className="border-info border p-3 text-center my-info-desc">
                        {this.state.userEdit.contentEditable?
                            <FormControl value={this.state.userEdit.info} as={"textarea"} onChange={(e)=>this.setState({
                                userEdit:{...this.state.userEdit,...{ info:e.target.value}}
                            })}/>
                            :this.state.userInfo?.info}
                    </Col>
                </Row>
                {this.state.userEdit.modifyPassword?
                    <Row>
                        <Col>
                            <Form>
                                <Input name="oldPassword" type={"password"} desc="旧密码" onChange={(value:string)=>this.setState({
                                    userEdit:{...this.state.userEdit,...{ oldPassword:value}}
                                })}/>

                                <Input name="newPassword" type={"password"} desc="新密码" onChange={(value:string)=>this.setState({
                                    userEdit:{...this.state.userEdit,...{newPassword:value}}
                                })}/>

                                <Input name="confirmNewPwd" type={"password"} placeholder="请确认新密码" desc="新密码" onChange={(value:string)=>this.setState({
                                    userEdit:{...this.state.userEdit,...{confirmNewPwd:value}}
                                })}/>
                            </Form>
                        </Col>
                    </Row>
                    :null
                }

                {this.props.isOwn?
                    <Row className="p-3">
                        <Col className="text-center">
                            {this.state.userEdit.contentEditable?
                                <Button variant={"primary"} onClick={()=>this.doSave()}>保存信息</Button>:
                                <Button variant={"info"} onClick={()=>this.openEdit()} disabled={this.state.userEdit.modifyPassword}>编辑信息</Button>}
                        </Col>
                        <Col className="text-center">
                            {this.state.userEdit.modifyPassword?
                                <Button variant={"light"} onClick={()=>this.modifyPwd()}>确认</Button>:
                                <Button variant={"light"} onClick={()=>this.openModifyPwd()} disabled={this.state.userEdit.contentEditable}>修改密码</Button>}
                        </Col>
                    </Row>:
                    <Row className="p-3">
                        <Col className="text-center">
                            {this.state.userInfo?.isMyFriend===undefined||this.state.userInfo.isMyFriend?null:this.props.isAdd?
                            <Button variant={"primary"} onClick={()=>this.addFriend()}>添加好友</Button>
                            :
                            <Button variant={"primary"} onClick={()=>this.agreeFriend()}>同意</Button>
                            }
                        </Col>
                    </Row>
                }

                <MyDialog content={this.state.result} open={this.state.result!==null} titleId="myinfo-dialog" menuName="用户提示" onClose={()=>{
                    this.setState({
                        result:null
                    })
                    if(this.props.cookies?.get(user_type_cookie)!==this.state.userEdit.userType&&this.props.refreshFun) {
                        this.props.refreshFun({
                            userType:this.state.userEdit.userType,

                        })
                    }
                }}/>
            </Container>
        )
    }
}
