import React from "react";
import {Button, Form, Image, Tab, Table, Tabs} from "react-bootstrap";
import {UserEntity, UserType} from "./entity";
import {Input} from "./ui/InputGroup";
import {JSONResponse, Method, request} from "./interface";
import {API, prefix} from "./api";
import {EmptyBodyTransform, FindUserRes, FindUserTransform, PageDataMessage, SimpleMessage} from "./result";
import {MyDialog} from "./ui/MyDialog";
import {Address} from "./ui/Address";

class EditUser extends React.Component<{
    user:UserEntity;
    modifyUser:Function;
}, {
        user:UserEntity;
    }>{

    private ages:Array<number>

    constructor(props: Readonly<{ user: UserEntity ,modifyUser:Function;}>) {
        super(props);

        this.ages=this.createAge()

        this.state={
            user:this.props.user
        }
    }

    render() {
        return (
            <Form>
                <Input name="name" desc="姓名" value={this.state.user.name} onChange={(value:string)=>
                    this.setState({
                    user:{...this.state.user,...{name:value}}
                })} valid={{check:this.isNotEmpty(this.state.user.name)}}/>

                <Input col={4} name="age" desc="年龄" value={this.state.user.age+""} onChange={(value:string)=>
                    this.setState({
                        user:{...this.state.user,...{age:+value}}
                    })
                } as={"select"} options={this.ages.map(value=><option key={value} value={value}>{value}</option>)}/>

                <Input col={4} name="sex" desc="性别" as="select" value={this.state.user.sex} onChange={(value:string)=>{
                    this.setState({
                        user:{...this.state.user,...{sex:value}}
                    })
                }}
                       options={[
                           <option value="" key={"sex"+0}>请选择性别</option>,
                           <option value="man" key={"sex"+1}>男</option>,
                           <option value="women" key={"sex"+2}>女</option>]}/>

                <Input name="address" desc="住址" value={this.state.user.address} onChange={(value:string)=>this.setState({
                    user:{...this.state.user,...{address:value}}
                })} valid={{check:this.isNotEmpty(this.state.user.address)}}/>

                <div className="mt-3">
                    <Address value={this.state.user.serviceAddress} onChange={(value:string)=>
                        this.setState({
                            user:{...this.state.user,...{serviceAddress:value}}
                        })
                    }/>
                </div>

                <Input col={4} name="userType" desc="用户身份" as="select" value={this.state.user.userType} onChange={(value:string)=>
                    this.setState({
                        user:{...this.state.user,...{userType:value}}
                    })
                }
                       options={[<option value="" key={"userType0"}>请选择用户身份</option>,
                           <option key={"userType1"} value={UserType.seekHelp}>服务发起者</option>,
                           <option key={"userType2"} value={UserType.help}>服务接收者</option>]}/>

                <Input col={4} name="mobile" desc="电话" value={this.state.user.mobile} onChange={(value:string)=>
                    this.setState({
                        user:{...this.state.user,...{mobile:value}}
                    })
                } valid={{check:this.checkMobile()}}/>

                <Input col={4} name="email" value={this.state.user.email} desc="邮箱" onChange={(value:string)=>
                    this.setState({
                        user:{...this.state.user,...{email:value}}
                    })
                } valid={{check:this.checkEmail()}}/>

                <Input col={7} name="info" desc="简介" value={this.state.user.info} as={"textarea"} onChange={(value:string)=>
                    this.setState({
                    user:{...this.state.user,...{info:value}}
                })
                }
                valid={{check:this.isNotEmpty(this.state.user.info)}}/>



                <Button variant="info" block={true} disabled={!this.check()} className={"ml-auto mr-auto mt-3 col-3"} onClick={()=>this.props.modifyUser(this.state.user)}>确认修改</Button>

            </Form>
        );
    }

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

    /**
     * 检查手机号
     */
    checkMobile(){
        return  /1[3456789]\d{9}/g.test(this.state.user.mobile.toString())
    }

    /**
     * 检查邮箱
     */
    private checkEmail() {
        return /[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}/g.test(this.state.user.email)
    }

    //检查是否为空
    isNotEmpty(...value:(string | number)[]){
        for(let index in value){
            if(value[index].toString().length===0){
                return false
            }
        }
        return true
    }

    private check() {
        return this.isNotEmpty(this.state.user.userId,this.state.user.name,this.state.user.sex,
            this.state.user.serviceAddress,this.state.user.userType,this.state.user.info)
            &&this.checkMobile()&&this.checkEmail()
    }
}

/**
 * 用户管理
 */
export class User extends React.Component<
    {
        undefined?:undefined
    },
    {
        userList?:Array<UserEntity>;
        tipContent:JSX.Element|null;
        user?:UserEntity;
        headImg?:string;
        dialog:JSX.Element|null;
    }>{


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

        this.state={
            tipContent:null,
            dialog:null
        }
    }

    /**
     * 加载用户信息
     */
    loadUser(page:number){
        let that=this
        request(API.account.userList,Method.GET,{
            currentPage:String(page),
            userTypes:[UserType.help,UserType.seekHelp]
        },new FindUserTransform(),function (res:FindUserRes) {
                switch (res.customResult) {
                    case PageDataMessage.ok:
                        that.setState({
                            userList:res.dataList
                        })
                        break
                    case PageDataMessage.fail:
                        that.setState({
                            tipContent:<h3 className="text-danger text-center">加载用户失败</h3>
                        })
                        break
                }
        })
    }


    componentDidMount() {
        this.loadUser(1)
    }

    render() {


        return (
            <Tabs defaultActiveKey="info" id="uncontrolled-tab-example">
                <Tab eventKey="info" title="用户信息">
                    <Table striped bordered hover className="mt-3">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>用户账号</th>
                                <th>姓名</th>
                                <th>年龄</th>
                                <th>性别</th>
                                <th>住址</th>
                                <th>头像</th>
                                <th>服务地点</th>
                                <th>用户身份</th>
                                <th>电话</th>
                                <th>邮箱</th>
                                <th>时间币</th>
                                <th>简介</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {this.state.userList?this.state.userList.length>0?this.state.userList.map((user:UserEntity, index:number)=>
                                <tr key={"tr"+index}>
                                    <td className="align-middle">{index+1}</td>
                                    <td className="align-middle">{user.userId}</td>
                                    <td className="align-middle">{user.name}</td>
                                    <td className="align-middle">{user.age}</td>
                                    <td className="align-middle">{user.sex==='man'?'男':'女'}</td>
                                    <td className="align-middle">{user.address}</td>
                                    <td className="align-middle">
                                        {<Image className="head-img" src={prefix.image+user.headImg} onClick={()=>this.setState({
                                            dialog:<MyDialog content={<Image src={prefix.image + user.headImg}/>}
                                                             open={true}
                                                             titleId={"image-dialog"} menuName={"图片放大"} onClose={()=>this.setState({
                                                dialog:null
                                            })}/>
                                        })}/>}
                                    </td>
                                    <td className="align-middle">{user.serviceAddress}</td>
                                    <td className="align-middle">{user.userType===UserType.seekHelp?'服务发起者':'服务接受者'}</td>
                                    <td className="align-middle">{user.mobile}</td>
                                    <td className="align-middle">{user.email}</td>

                                    <td className="align-middle">{user.timeScore}</td>
                                    <td className="align-middle">{user.info}</td>
                                    <td className="align-middle">
                                        <Button variant="info" className="mr-3" onClick={()=>this.setState({
                                            dialog:<MyDialog content={<EditUser modifyUser={(user:UserEntity)=>this.modifyUser(user)} user={user}/>} open={true} titleId={"user-edit-dialog"} menuName={"修改用户信息"}
                                                             onClose={()=>this.setState({dialog:null})}/>
                                        })}>修改用户信息</Button>
                                        <Button variant="danger" className="mr-3">删除</Button>
                                    </td>
                                </tr>):<h3 className="text-center text-danger">没有用户信息</h3>:null}
                        </tbody>
                    </Table>


                    {this.state.dialog}

                    <MyDialog content={this.state.tipContent} open={this.state.tipContent!=null} titleId={"user-dialog"} menuName={"操作提示"}
                              onClose={()=>this.setState({
                                        tipContent:null
                                })}/>


                </Tab>
            </Tabs>
        );
    }

    /**
     * 修改用户信息
     * @param user
     */
    private modifyUser(user: UserEntity) {
        let that=this
        request(API.account.updateUser,Method.POST, {
            userId:user.userId,
            name:user.name,
            age:String(user.age),
            sex:String(user.sex),
            address:user.address,
            serviceAddress:user.serviceAddress,
            userType:user.userType,
            mobile:user.mobile,
            email:user.email,
            info:user.info

        },new EmptyBodyTransform(),function (res:JSONResponse<SimpleMessage>) {
            switch (res.customResult) {
                case SimpleMessage.ok:
                    that.setState({
                        tipContent:<h3 className="text-center text-info">修改用户信息成功</h3>,
                        dialog:null
                    })
                    that.loadUser(1)
                    break
                case SimpleMessage.fail:
                    that.setState({
                        tipContent:<h3 className="text-center text-danger">修改失败，请联系管理员</h3>
                    })
                    break
            }
        })
    }
}
