import React, { Component, useState } from 'react';
import { Form, Row, Col, Input, Button, Tabs, Tree, Select, Upload } from 'antd';
import styles from './UserInfo.less';
import 'remixicon/fonts/remixicon.css';
import moment from 'moment';

const FormItem = Form.Item;
const TabPane = Tabs.TabPane;
const TreeNode = Tree.TreeNode;

/**
 * 顶部主菜单及其内容
 */
const UserAuthorization = (props) => {

  const {
    onSaveUserInfo, onCloseUserInfo, tokenModel, roleInfoData, menuData=[], cacheUserData, userInfoData
  } = props;

  const [form] = Form.useForm();
  const {getFieldDecorator, getFieldsValue, validateFields, resetFields} = form;

  const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  };
  const singleFormItemLayout = {
    labelCol: { span: 3 },
    wrapperCol: { span: 21 },
  };

  const iconStyle = {
    verticalAlign: "bottom",
    marginRight: "5px",
  };

  const uploadIconStyle = {
    verticalAlign: "bottom",
    marginRight: "5px",
    fontSize: "40px",
  }

  let userInfo = userInfoData ? userInfoData : tokenModel && tokenModel.userInfo ? JSON.parse(tokenModel.userInfo) : "";

  const [expandedTreeNodeKeys, setExpandedTreeNodeKeys] = useState(null);

  const onExpandTreeNode = (expandedTreeNodeKeys, item) => {
    setExpandedTreeNodeKeys({ expandedTreeNodeKeys })
  };

  const resolveMenu = (menuDatas, menuKeyMap) => {
    for (let i = 0; i < menuDatas.length; i++) {
      const item = menuDatas[i];
      menuKeyMap.set(item.key, item);
      if (item.children && item.children.length > 0) {
        resolveMenu(item.children, menuKeyMap);
      }
    }
  };

  const generateMenus = (selectedMenus, menuKeyMap) => {
    if (!selectedMenus || selectedMenus.length == 0) {
      return menuData;
    }

    const selectedMenuList = [];
    const allMenuList = Array.from(menuKeyMap.values());
    const menus = selectedMenus && selectedMenus.length > 0 ? selectedMenus.split(",") : [];
    for (let i = 0; i < menus.length; i++) {
      const menu = menuKeyMap.get(menus[i]);
      if (!menu.parentId || menu.children) {
        selectedMenuList.push(menu);
      }

      if (menu.parentId) {
        const menuObj = allMenuList.filter(item => item.id == menu.parentId)[0];
        if (selectedMenus.indexOf(menuObj.key) < 0) {
          selectedMenuList.push(menuObj);
        }
      }
    }
    return selectedMenuList.sort((x, y) => moment(x.createTime) - moment(y.createTime));
  };

  const menuKeyMap = new Map();
  resolveMenu(menuData, menuKeyMap);
  const selectedMenuList = generateMenus(roleInfoData && roleInfoData.menuIds ? roleInfoData.menuIds : null, menuKeyMap);
  const generateTreeNodes = (data) => data.filter(item => item.show).map((item) => {
    if (item.children) {
      return (
        <TreeNode title={item.name} key={item.key} dataRef={item}>
          {generateTreeNodes(item.children)}
        </TreeNode>
      );
    }
    return <TreeNode title={item.name} key={item.key} dataRef={item}/>;
  });

  const uploadProps = {
    name: "PictureToolBar",
    listType: "picture-card",
    className: "avatar-uploader",
    showUploadList: false,
    beforeUpload: (file) => {
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onload = function (event) {
        let base64 = event.target.result;
        userInfo.imgBase64 = base64;
        cacheUserData(userInfo);
      }
    },
  }

  const uploadButton = (
    <div>
      <i className={"ri-user-line"} style={uploadIconStyle} />
      <div style={{ marginTop: 0 }}>上传头像</div>
    </div>
  )

  return (
    <div id={"userAuthorization"} className={styles.userInfoUpdate}>
      <Tabs defaultActiveKey={"basicInfo"} style={{padding: "0px 20px 20px 20px"}}>
        <TabPane tab={<span><i className={"ri-user-line"} style={iconStyle}/>&nbsp;基本信息</span>} key={"basicInfo"}>
          <Form initialValues={userInfo ? userInfo : null} style={{ margin: "20px 0px 0px 0px" }}>
            <Row>
              <Col span={12}>
                <Row>
                  <Col span={24}>
                    <FormItem { ...formItemLayout } label="用户名称" name={"userName"} rules={[{required: true, message: '请输入用户名称'}]}>
                      <Input placeholder={"请输入用户名称"} disabled={"disabled"}/>
                    </FormItem>
                  </Col>
                </Row>
                <Row>
                  <Col span={24}>
                    <FormItem { ...formItemLayout } label="手机号码" name={"phoneNumber"} rules={[{required: true, message: '请输入手机号码'}]}>
                      <Input placeholder={"请输入手机号码"} />
                    </FormItem>
                  </Col>
                </Row>
              </Col>
              <Col span={12}>
                <Upload { ...uploadProps } className={styles.uploadDiv}>
                  {
                    userInfo.imgBase64 ?
                      <img src={userInfo.imgBase64} alt="avatar" style={{ width: '28%' }} /> : uploadButton
                  }
                </Upload>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <FormItem { ...formItemLayout } label="邮箱地址" name={"email"} rules={[{required: true, message: '请输入用户名'}]}>
                  <Input placeholder={"请输入用户名"} />
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem { ...formItemLayout } label="旧密码" name={"password"} rules={[{required: true, message: '请输入旧密码'}]}>
                  <Input placeholder={"请输入旧密码"} />
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <FormItem { ...formItemLayout } label="新密码" name={"newPassword"} rules={[{required: true, message: '请输入新密码'}]}>
                  <Input placeholder={"请输入新密码"} />
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem { ...formItemLayout } label="确认密码" name={"newPassword"} rules={[{required: true, message: '请输入确认密码'}]}>
                  <Input placeholder={"请输入确认密码"} />
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={24}>
                <FormItem { ...singleFormItemLayout } label="个人简介" name={"resume"} rules={[{required: false}]}>
                  <Input.TextArea placeholder={"请输入个人简介，最长500个字"} />
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={24}>
                <FormItem { ...singleFormItemLayout } label="个性标签" name={"individual"} rules={[{required: false}]}>
                  <Select mode="tags" placeholder="请输入个性标签，最长100个字" style={{ width: '100%' }} />
                </FormItem>
              </Col>
            </Row>
          </Form>
          <div style={{ textAlign: "center" }}>
            <Button type={"primary"} icon={<i className="ri-save-3-line" style={iconStyle}/>} onClick={onSaveUserInfo}>保存</Button>
            <Button type={"danger"} icon={<i className="ri-close-circle-line" style={iconStyle}/>} style={{ marginLeft: "10px" }} onClick={onCloseUserInfo}>关闭</Button>
          </div>
        </TabPane>
        <TabPane tab={<span><i className={"ri-windows-line"} style={iconStyle}/>&nbsp;角色权限</span>} key={"menuLimit"}>
          <Tree onExpand={onExpandTreeNode} style={{width: "93%", overflow: "auto", height: "350px"}}>
            {
              menuData && menuData.length > 0 ? generateTreeNodes(selectedMenuList) : null
            }
          </Tree>
        </TabPane>
        <TabPane tab={<span><i className={"ri-database-line"} style={iconStyle}/>&nbsp;账号绑定</span>} key={"dataLimit"}>
          <div style={{width: "93%", overflow: "auto", height: "350px"}}>暂无数据</div>
        </TabPane>
      </Tabs>
    </div>
  )
};

export default UserAuthorization;
