import React from "react";
import {Button, Form, Tab, Table, Tabs} from "react-bootstrap";
import {ManagerEntity, PageProps} from "./entity";
import {Input} from "./ui/InputGroup";
import {Cookies} from "react-cookie";
import {MyDialog} from "./ui/MyDialog";
import {JSONResponse, Method, request} from "./interface";
import {API} from "./api";
import {EmptyBodyTransform, ManagerList, ManagerTransform, PageDataMessage, SimpleMessage} from "./result";
import {manager_cookie} from "./account/PropCookie";
import {register} from './public'
import {Page} from "./ui/Page";

enum Type {
    modify,
    register
}

class EditManager extends React.Component<
    {
        onClick:Function;
        type:Type;
    },
    {
        managerId?:string,
        password:string;
        confirmPwd:string;
    }>{



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

        this.state={
            password:"",
            confirmPwd:"",
        }
    }

    isDisable(){
       return !(this.state.password.length>0
           &&this.state.confirmPwd.length>0&&this.state.password===this.state.confirmPwd&&((this.state.managerId&&this.state.managerId.length>0)||!this.state.managerId))
    }

    render() {
        return (

            <Form>
                {this.props.type===Type.modify?null:
                    <Input name="managerId" desc="管理员账号" onChange={(value:string)=>
                        this.setState({
                            managerId:value
                        })
                    } valid={{check:this.state.managerId?this.state.managerId.length>0:false}}/>
                }

                <Input name="password" type="password"  desc="密码" onChange={(value:string)=>
                    this.setState({
                        password:value
                    })
                } valid={{check:this.state.password.length>0}}/>
                <Input name="confirmPwd" type="password" desc="确认密码"  onChange={(value: string)=>{
                    this.setState({
                        confirmPwd:value
                    })
                }} valid={{check:this.state.confirmPwd.length>0&&this.state.password===this.state.confirmPwd,
                    invalid:this.state.confirmPwd.length>0&&this.state.password!==this.state.confirmPwd?"密码和确认密码不一致":"验证失败"}}/>

                <Button block={true} disabled={this.isDisable()} className="col-3 mt-3 ml-auto mr-auto" onClick={
                    ()=>Type.register===this.props.type?this.props.onClick(this.state.managerId,this.state.password):this.props.onClick(this.state.password)}>提交</Button>
            </Form>


        )
    }
}



/**
 * 管理员管理
 */
export class Manager extends React.Component<
    {
        cookies:Cookies;
    },
    {
        //管理员列表数据
        managerList?:Array<ManagerEntity>;
        //弹框界面
        dialog:JSX.Element|null;
        //操作反馈
        tipContent:JSX.Element|null;
        page?:PageProps;
    }>{

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

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

    }


    /**
     * 修改密码
     */
    private modifyPwd(managerId:string,password:string) {
        let that=this
        request(API.account.update,Method.POST, {
            managerId:managerId,
            password:password
        },new EmptyBodyTransform(),function (res:JSONResponse<SimpleMessage>) {
            switch (res.customResult) {
                case SimpleMessage.ok:
                    that.setState({
                        tipContent:<h3 className="text-center text-info">密码修改成功</h3>,
                        dialog:null
                    })
                    break
                case SimpleMessage.fail:
                    that.setState({
                        tipContent:<h3 className="text-center text-danger">密码修改失败</h3>
                    })
                    break
            }
        })
    }

    /**
     * 加载管理员数据
     */
    loadManager(page:number){
        let that=this
        request(API.account.list,Method.GET,{
            currentPage:page+""
        },new ManagerTransform(),function (res:ManagerList) {
                switch (res.customResult) {
                    case PageDataMessage.ok:
                        that.setState({
                            managerList:res.dataList,
                            page: res.page
                        })
                        break
                    case PageDataMessage.fail:
                        that.setState({
                            tipContent:<h3 className="text-center text-danger">加载数据失败，请联系管理员</h3>
                        })
                        break

                }
        })
    }

    /**
     * 检查密码
     */
    checkPwd(modify:any){
       if(modify.password.length>0&&modify.confirmPwd.length>0&&modify.password===modify.confirmPwd){
           return {
               check:true
           }
       }else if(modify.confirmPwd.length>0&&modify.confirmPwd.length>0){
           return {
               check:false,
               invalid:'两次密码输入不一致'
           }
       }else if(modify.password.length>0&&modify.confirmPwd.length===0){
           return {
               check:false,
               invalid: '确认密码为空'
           }
       }else{
           return {
               check:undefined
           }
       }
    }

    componentDidMount() {
       this.loadManager(1)
    }


    render() {


        return (

            <Tabs defaultActiveKey="info" id="uncontrolled-tab-example">
                <Tab eventKey="info" title="管理员信息">
                    <Button variant="primary" className="mt-3" onClick={() => this.setState({dialog:
                            <MyDialog content={<EditManager onClick={(managerId:string, password:string)=>{
                                let that=this
                                register(this,managerId,password,function(){
                                    that.setState({
                                        dialog:null
                                    })
                                    that.loadManager(1)
                                })

                            }} type={Type.register}/>}
                                      open={true} titleId={"manager-dialog"}
                                      menuName={"添加管理员"}  onClose={()=>{
                                          this.setState({dialog:null});
                            }}/>})}>添加管理员</Button>
                    <Table striped bordered hover className="mt-3">
                        <thead>
                        <tr>
                            <th>#</th>
                            <th>管理员名</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                            {this.state.managerList?
                                this.state.managerList.map((manager:ManagerEntity, index:number)=>
                                    <tr key={"tr" + index}>
                                        <td>{index + 1}</td>
                                        <td>{manager.managerId}</td>
                                        <td>
                                            <Button variant={"info"} className="mr-3"
                                                    onClick={() => this.setState({dialog:
                                                            <MyDialog content={<EditManager type={Type.modify} onClick={(password:string)=>this.modifyPwd(manager.managerId,password)}/>}
                                                                      open={true} titleId={"manager-dialog"}
                                                                      menuName={"修改密码"}  onClose={()=>this.setState({dialog:null})}/>})}>修改密码</Button>


                                            {this.props.cookies.get(manager_cookie)===manager.managerId?null:
                                                <Button variant="danger" onClick={()=>this.delete(manager.managerId)}>删除</Button>
                                                }
                                        </td>
                                    </tr>
                                )
                                :null
                            }
                        </tbody>
                    </Table>

                    {this.state.page?<Page onClick={(page:number)=>this.loadManager(page)} currentPage={this.state.page.currentPage}
                                           totalPage={this.state.page.totalPage} pageSize={this.state.page.pageSize}/>:null}

                    {this.state.dialog}


                    <MyDialog content={this.state.tipContent} open={this.state.tipContent!=null}
                              titleId={"manager-tip"} menuName={"提示信息"} onClose={()=>this.setState({
                        tipContent:null
                    })}/>
                </Tab>
            </Tabs>
        );
    }

    /**
     * 删除管理员
     * @param managerId
     */
    private delete(managerId: string) {
        let that=this
        request(API.account.delete+managerId,Method.POST, {},new EmptyBodyTransform(),
            function (res:JSONResponse<SimpleMessage>) {
                        switch (res.customResult) {
                            case SimpleMessage.ok:
                                that.setState({
                                    tipContent:<h3 className="text-center text-info">删除成功</h3>,
                                })
                                that.loadManager(1)
                                break
                            case SimpleMessage.fail:
                                that.setState({
                                    tipContent:<h3 className="text-center text-info">删除失败，请联系管理员</h3>,
                                })
                                break
                        }
                    })
    }

}
