
import React , { useEffect , useState } from 'react';
import { Button, Dropdown, Input, Menu , message, Pagination } from 'antd';
import Search from '../../Component/Search';
import Item from '../Team-item';
import Nodata from '../../Nodata';
import axios from 'axios';
import CheckProfile from '../../Component/ProfileModal/Profile';
import './index.scss';
import SearchUser from '../../Component/SearchUser';
import { FlexAJ } from '../../Component/layout';

// 个人中心-贡献确权
function Contribution(props){
  const limit = 10;
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(undefined);
  // 转账列表
  const [reload, setReload] = useState(undefined);
  const [list, setList] = useState(undefined);
  // 选项 1 转账 0 记录
  const [ type, setType] = useState(1);
  // 目标转账用户id/login
  const [userLogin, setUserLogin] = useState({});
  const [error1, setError1] = useState(undefined);
  // 转账数值
  const [tokenCount, setTokenCount] = useState({});
  const [error2, setError2] = useState(undefined);
  // 操作仓库id
  const [proId, setProId] = useState(undefined);
  const {current_user:{user_id, login, open_blockchain}, current_user} = props;
  const {user} = props;
  const username = props.match.params.username;

  useEffect(()=>{
    if((username && current_user && (current_user.login !== username)) || !open_blockchain){
      props.history.push(`/${username}`);
    }
  },[current_user,username])

  useEffect(()=>{
    // token转账列表
    axios.get(`/users/blockchain/balance.json`,{params: {
      user_id,
      limit,
      page
    }}).then(res=>{
      if(res && res.data){
        const {projects} = res.data;
        const newProjects = [];
        let deleteProjectCount = 0;
        projects.map(item=>{
          if(item.id){
            newProjects.unshift(item);
          }else{
            deleteProjectCount++;
          }
        })
        deleteProjectCount && newProjects.push({
          'balance': deleteProjectCount
        })
        setList(newProjects);
        setTotal(res.data.total_count);
      }
    })
  }, [reload, page])

  useEffect(()=>{
    if(user){
      // 更改网页标题
      const {username, login} = user;
      document.title = `贡献确权-${username}/${login}`;
    }
  },[user])

  // 目标转账用户
  function getUser(id, login){
    // 使用JSON进行对象深拷贝
    const userLoginObject = JSON.parse(JSON.stringify(userLogin));
    userLoginObject[id] = login;
    setUserLogin(userLoginObject);
  }

  // token转账值
  function setToken(id, token){
    const tokenCountObject = JSON.parse(JSON.stringify(tokenCount));
    tokenCountObject[id] = token;
    setTokenCount(tokenCountObject);
  }

  // 确认转账
  function confirmTransfer(id, identifier, max){
    setError1(undefined);
    setError2(undefined);
    setProId(id);
    const userLoginById = userLogin[id];
    const tokenCountById = tokenCount[id];
    if(!userLoginById || !tokenCountById){
      !userLoginById && setError1('请确定目标转账用户');
      if(!tokenCountById){
        setError2('请输入token数额');
      }
    }else if(!/^[1-9]+[0-9]*]*$/.test(tokenCountById) || tokenCountById>max){
      setError2('转账token数额必须为不超过token总数的正整数');
    }else{
      axios.post(`/users/blockchain/transfer`, {
        owner_login: login,
        project_identifier: identifier,
        user_id,
        transfer_amount: tokenCountById,
        transfer_login: userLoginById,
        payer_id: user_id,
        project_id: id
      }).then(res=>{
        if(res && res.data && res.data.status === 2){
          getUser(id, undefined);
          setToken(id, undefined);
          setReload(Math.random());
          message.success('转账成功');
        }
      })
    }
  }

  return(<div className='mt15 contribution'>
    {/* 转账/记录切换 */}
    {/* <div className='contHead'>
      <a className={`itemCont ${type ? 'active' : ''}`} onClick={()=>{setType(1)}}>token转账</a>
      <a className={`itemCont ${type ? '' : 'active'}`} onClick={()=>{setType(0)}}>token记录</a>
    </div> */}
    {/* token转账 */}
    {type ? <div className='contributionTable mt25'>
      {list && list.length > 0 && <div className='flexCenterCont tableHeadTri mb5'>
        <div className='tableColumn1'>项目名称</div>
        <div className='tableColumn2'>token总量</div>
        <div className='tableColumn3'>目标转账用户</div>
        <div className='tableColumn4'>转账token数额</div>
        <div className='tableColumn5'>操作</div>
      </div>}
      {list && !list.length && <Nodata _html="暂无数据"/>}
      {list && list.map(item=>{return item.id ? <div key={item.id} className='flexCenterCont transferAccount'>
        <div className='tableColumn1'>{item.name}</div>
        <div className='tableColumn2'>{item.balance}</div>
        <div className='tableColumn3'>
          <SearchUser getUser={(login)=>{getUser(item.id, login)}} width={"100%"} placeholder="搜索转账目标用户" value={userLogin[item.id]}/>
          {proId === item.id && error1 && <div className='errorTipTri'>{error1}</div>}
        </div>
        <div className='tableColumn4'>
          <Input value={tokenCount[item.id]} onChange={(e)=>{setToken(item.id, e.target.value)}} placeholder='请输入token数额'/>
          {proId === item.id && error2 && <div className='errorTipTri'>{error2}</div>}
        </div>
        <div className='tableColumn5'><Button className='confirmTransfer' onClick={()=>{confirmTransfer(item.id, item.identifier, item.balance)}}>确认</Button></div>
      </div>: <div className='flexCenterCont transferAccount deleteRepo'>{item.balance}个项目被删除</div>})}
    </div> : <div className='contributionTable mt20 record'>
      <FlexAJ className='contributionRecordItem font-15'>
        <span><span className='themeSpan'>蒋宇航</span>在<span className='themeSpan'>GilLink/确实开源</span>给你转账了1000个tiken</span>
        <span className='tableHeadTri'>6小时前</span>
      </FlexAJ>
      <FlexAJ className='contributionRecordItem font-15'>
        <span><span className='themeSpan'>蒋宇航</span>在<span className='themeSpan'>GilLink/确实开源</span>给你转账了1000个tiken</span>
        <span className='tableHeadTri'>6小时前</span>
      </FlexAJ>
    </div>}
    {total > limit && <div className='mt20 paginationTri mb50'>
      <Pagination simple current={page} pageSize={limit} total={total} onChange={(page)=>{setPage(page);window.scrollTo(0,0);}}/>
    </div>}
  </div>
  )
}
export default Contribution;