import React, { useState, useEffect } from 'react';
import { WhiteBack, Blueline, AlignCenter, FlexAJ } from '../../../Component/layout';
import { Menu, Table, Pagination, Icon, Tooltip, Popconfirm, Dropdown, Spin } from 'antd';
import Sort from '../../../Component/Sort';
import Title from '../../../Component/Title';
import Search from '../../../Component/Search';
import SearchUser from '../../../Component/SearchUser';
import styled from 'styled-components';
import { getImageUrl } from 'educoder';
import axios from 'axios';
import { Link } from 'react-router-dom';
const Img = styled.img`{
  width:30px;
  height:30px;
  border-radius:50%;
}`

export default ((props) => {
  const [login, setAddUserLogin] = useState(undefined);
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(15);
  const [total, setTotal] = useState(0);
  const [data, setMembers] = useState(undefined);
  const [isSpin, setIsSpin] = useState(false);
  const [identify, setIdentify] = useState(undefined);
  const [search, setQuery] = useState(undefined);
  const { OIdentifier, groupId } = props.match.params;
  const { current_user } = props;
  
  useEffect(() => {
    getMember()
  }, [page, search, identify])

  function getMember() {
    setIsSpin(true)
    const url = `/organizations/${OIdentifier}/teams/${groupId}/team_users.json`;
    axios
      .get(url, {
        params: {
          page,
          search,
          identify,
          limit
        },
      })
      .then((result) => {
        if (result && result.data) {
          setMembers(result.data.team_users)
          setTotal(result.data.total_count)
        }
      }).catch((error) => { });
    setIsSpin(false)
  };

  // 获取搜索用户框里面选择的用户Login字段，接口是这样定义的
  function getUser(login) {
    setAddUserLogin(login)
  }

  function addUser() {
    setIsSpin(true)
    const url = `/organizations/${OIdentifier}/teams/${groupId}/team_users.json`;
    if (login) {
      axios.post(url, {
        username: login
      })
        .then((result) => {
          if (result && result.data) {
            setPage(1)
            setQuery(undefined)
            setIdentify(undefined)
            this.getMember();
          }
        })
        .catch((error) => { });
    }
    setIsSpin(false)
  }
  // 搜索
  function onSearch(value) {
    setQuery(value)
  }

  // 角色筛选
  function onSelectMenu(e) {
    let select_role = e.key
    setPage(1)
    setQuery(undefined)
    setIdentify(select_role === "all" ? undefined : select_role)
  }

  // 切换分页
  function ChangePage(page) {
    setPage(page);
  }

  // 移除成员
  function removeUser(username) {
    setIsSpin(true)
    const url = `/organizations/${OIdentifier}/teams/${groupId}/team_users/${username}.json`;
    if (username) {
      axios.delete(url)
        .then((result) => {
          if (result && result.data) {
            setPage(1)
            setQuery(undefined)
            setIdentify(undefined)
            this.getMember();
          }
        })
        .catch((error) => { });
    }
    setIsSpin(false)
  }

  const MENU_LIST = [
    {
      id: "Manager",
      name: "管理员",
      desc: "拥有仓库设置功能、代码库读、写操作"
    },
    {
      id: "Developer",
      name: "开发者",
      desc: "只拥有代码库读、写操作"
    },
    {
      id: "Reporter",
      name: "报告者",
      desc: "只拥有代码库读操作"
    },
  ];

  const menu = (
    <Menu onSelect={onSelectMenu}>
      <Menu.Item key="all">全部</Menu.Item>
      {MENU_LIST.map((item, key) => {
        return (
          <Menu.Item
            key={item.id}
            value={item.id}
          >
            {item.name}
          </Menu.Item>
        );
      })}
    </Menu>
  )
  const roleTitle = (
    <div><span className="mr3">角色</span>
      <Tooltip placement='bottom' title=
        {
          <div>
            {MENU_LIST.map((item, key) => {
              return (
                <div className="mb3">{item.name}：{item.desc}</div>
              );
            })}
          </div>
        }
      >
        <Icon type="question-circle"></Icon>
      </Tooltip>
    </div>
  );
  function get_color(role) {
    if (role === "manager") {
      return "text-green";
    } else if (role === "developer") {
      return "text-primary";
    } else {
      return "text-yellow";
    }
  };

  const setRoles = (id) => (
    <Menu>
      {MENU_LIST.map((item, key) => {
        return (
          <Menu.Item
            key={item.id}
            value={item.id}
            onClick={(e) => this.changeOperaiton(e, id)}
          >
            {item.name}
          </Menu.Item>
        );
      })}
    </Menu>
  );

  // 修改权限
  function changeOperaiton(e, id) {
    console.log(e)
  };

  const member_roles = (item) => {
    const operation = MENU_LIST.filter((i) => i.id === item.identify);
    return (
      <span>
        {operation && operation[0] ?
          <span>
            {current_user && current_user.login === item.login ? (
              <label className={get_color(item.role)}>
                {operation && operation[0].name}
              </label>
            ) : (
                <Dropdown overlay={setRoles(`${item.id}`)} placement={"bottomCenter"}>
                  <span className={get_color(item.role)}>
                    {operation && operation[0].name}
                    <Icon type="caret-down" className="ml2" size="13" />
                  </span>
                </Dropdown>
              )}
          </span>
          : ""
        }
      </span>
    );
  };

  const columns = [
    {
      title: '头像',
      dataIndex: 'Img',
      width: "7%",
      render: (value, item) => {
        return (
          <Img src={getImageUrl(`images/${item.user.image_url}`)}></Img>
        )
      }
    },
    {
      title: '用户名',
      dataIndex: 'name',
      width: "13%",
      align: "center",
      render: (value, item) => {
        return (
          <Link to={`/users/${item.user.login}`}>{item.user.name}</Link>
        )
      }
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      width: "25%",
      render: (value, item) => {
        return (
          item.user.mail
        )
      }
    },
    {
      title: roleTitle,
      dataIndex: 'role',
      width: "20%",
      render: (value, item) => member_roles(item.user),
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: "15%",
      render: (value, item) => {
        return <Popconfirm
          title="确认移除成员吗？"
          onConfirm={() => removeUser(item.user.login)}
          okText="确认"
          cancelText="取消"
        >
          <a className="color-grey-8" href="#">移除成员</a>
        </Popconfirm>
      }
    }
  ]

  return (
    <Spin spinning={isSpin}>
      <WhiteBack>
        <Title>
          <span>组织成员管理</span>
          <AlignCenter>
            <SearchUser getUser={getUser} />
            <Blueline className="ml30" onClick={addUser}>+&nbsp;添加用户</Blueline>
          </AlignCenter>
        </Title>
        <FlexAJ className="padding20-30">
          <div style={{ width: "580px" }}>
            <Search placeholder="输入用户名或邮箱、团队名搜索" value={search} onSearch={onSearch} />
          </div>
          <Sort menu={menu}>
            <a className="color-blue">角色筛选<i className="iconfont icon-sanjiaoxing-down ml3 font-14"></i></a>
          </Sort>
        </FlexAJ>
        <div className="pl30 pr30 pb30">
          <Table
            size="small"
            columns={columns}
            dataSource={data}
            pagination={false}
            className="teamMemberTable"
          ></Table>
          {
            total > limit ?
              <div className="edu-txt-center mt30 mb20">
                <Pagination simple defaultCurrent={page} total={total} pageSize={limit} onChange={ChangePage}></Pagination>
              </div>
              : ""
          }
        </div>
      </WhiteBack>
    </Spin>

  )
})