import { useEffect, useMemo, useState } from "react";
import useCopyLink from "~/hooks/useCopy";
import { getTime, splitAddress, toThousands } from "~/utils";
import store from "~/store";
import { observer } from "mobx-react";
import { useRouter } from "~/hooks/useRouter";
import BackBar from "~/components/BackBar";
import { Cell, Empty, List, Tabs } from "react-vant";
import { debounce } from 'lodash';
import '~/styles/personal.scss';
import { history_record } from "~/api";

const Record = () => {

  const { token } = store.state;
  const { push, location } = useRouter()
  console.log(location);
  
  const recordTabs = useMemo(() => ['充值', '提现', '收益'], []);
  const [recordIndex, setRecordIndex] = useState(location.state ? location.state.index : 0);
  const { copyVal } = useCopyLink();
  const [query, setQuery] = useState([
    { page: 1, page_size: 20 },
    { page: 1, page_size: 20 },
    { page: 1, page_size: 20 },
  ]);
  const [finished, setFinished] = useState<boolean[]>([true, true, true]);
  const [assetsRecord, setAssetsRecord] = useState([
    [] as any[],
    [] as any[],
    [] as any[],
  ]);

  const getAssetsRecord = debounce(async () => {

    let res: any = await history_record({ type: recordIndex + 1, ...query[recordIndex] });
    if (res.code === 0) {
      if (res.data.length < 20) {
        if (assetsRecord[recordIndex].length <= 0) {
          assetsRecord[recordIndex] = res.data
        } else {
          assetsRecord[recordIndex] = [...assetsRecord[recordIndex], ...res.data]
        }
        finished[recordIndex] = true
        setFinished([...finished]);
        setAssetsRecord([...assetsRecord]);
        return
      }
      query[recordIndex].page = query[recordIndex].page + 1
      if (assetsRecord[recordIndex].length <= 0) {
        assetsRecord[recordIndex] = res.data
      } else {
        assetsRecord[recordIndex] = [...assetsRecord[recordIndex], ...res.data]
      };
      finished[recordIndex] = false;
      setFinished([...finished]);
      setAssetsRecord([...assetsRecord]);
      setQuery([...query]);
    };
  }, 200);

  const renderItem = (index: number) => {
    let el = [
      <RechargeRecord list={assetsRecord[recordIndex]} copy={copyVal} finished={finished[recordIndex]} getData={getAssetsRecord} />,
      <WithdrawRecord list={assetsRecord[recordIndex]} copy={copyVal} finished={finished[recordIndex]} getData={getAssetsRecord} />,
      <TransferRecord list={assetsRecord[recordIndex]} finished={finished[recordIndex]} getData={getAssetsRecord} />,
    ];
    return el[index];
  };

  useEffect(() => {
    token && assetsRecord[recordIndex].length <= 0 && getAssetsRecord();
    !token && push('/', null, true);
    !token && setFinished([true, true, true, true, true, true]);
  }, [recordIndex, token]);


  return (
    <div className="plr-2 record">
      <BackBar
        title='账单'
      />
      <Tabs
        swipeable
        type="capsule"
        background="rgb(248,247,255)"
        sticky
        defaultActive={recordIndex}
        offsetTop={window.innerWidth / 430 * 60}
        onChange={(_, index) => setRecordIndex(index)}
        align="start"
        className="tabs"
        lazyRender
      >
        {
          recordTabs.map((item, index) => (
            <Tabs.TabPane
              key={index}
              title={item}
              titleStyle={{ width: 70, height: 30, padding: 0 }}
            >
              {renderItem(index)}
            </Tabs.TabPane>
          ))
        }
      </Tabs>
    </div>
  )
}

interface ChildProps {
  list: any[],
  copy?: Function,
  finished: boolean,
  getData: Function
}

const RechargeRecord = (
  { list, copy, finished, getData }: ChildProps
) => {

  if (list.length <= 0 || Object.keys(list).length <= 0) return <Empty description="暂无记录" />;

  return (
    <List finished={finished} onLoad={() => getData()} errorText="请求失败，点击重新加载" offset={10}>
      {
        list.map((item) => (
          <Cell key={item.id} className="ptb-1" style={{ background: 'none' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <div>
                <div className='fz-wb-550'>{item.name}</div>
                <div className='sub-text fz-14 mt-6px'>{getTime(item.time * 1000)}</div>
                <div className='sub-text fz-14'>
                  交易哈希：{splitAddress(item.tx_hash, 10)}
                  {
                    item.tx_hash && (
                      <i className='iconfont icon-fuzhi_copy black ml-5px' onClick={() => copy && copy(item.tx_hash)}></i>
                    )
                  }
                </div>
              </div>
              <div className='column-justify-between tae'>
                <div className='green fz-wb-550'>+{toThousands(item.amount)} {item.symbol}</div>
                <div className={`tar ${item.status === 1 && 'green'}`}>
                  {item.status === 1 ? '完成' : '確認中'}
                </div>
              </div>
            </div>
          </Cell>
        ))
      }
    </List >
  )
}

const WithdrawRecord = ({ list, finished, getData, copy }: ChildProps) => {

  if (list.length <= 0 || Object.keys(list).length <= 0) return <Empty description="暂无记录" />;

  return (
    <List finished={finished} onLoad={() => getData()} errorText="请求失败，点击重新加载" offset={10}>
      {
        list.map((item, index) => (
          <Cell className='ptb-1' key={item.id} style={{ background: 'none' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <div>
                <div className='fz-wb-550'>提现</div>
                <div className='sub-color fz-14'>{getTime(item.time * 1000)}</div>
                <div className='sub-color fz-14'>
                  交易哈希：{item.tx_hash && splitAddress(item.tx_hash, 8)}
                  {item.tx_hash && <i className='iconfont icon-fuzhi_copy black ml-5px' onClick={() => {
                    copy && copy(item.tx_hash)
                  }}></i>}
                </div>
              </div>
              <div className='column-justify-between tae'>
                <div className='tar'>
                  <div className="red fz-wb-550">-{toThousands(item.amount)} {item.symbol}</div>
                  <div className="sub-text fz-14">手續費：{item.withdraw_fee} {item.withdraw_fee_symbol}</div>
                </div>
                <div className='tar sub-text fz-14'>{item.status === 4 ? '完成' : '確認中'}</div>
              </div>
            </div>
          </Cell>
        ))
      }
    </List>

  )
}

const TransferRecord = ({ list, finished, getData }: ChildProps) => {

  if (list.length <= 0 || Object.keys(list).length <= 0) return <Empty description="暂无记录" />;

  return (
    <List finished={finished} onLoad={() => getData()} errorText="请求失败，点击重新加载" offset={10}>
      {
        list.map((item, index) => (
          <Cell className="ptb-1" key={item.id} style={{ background: 'none' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <div>
                <div className='fz-wb-550'> {item.name}</div>
                <div className='sub-color fz-14 mt-6px'>{getTime(item.time * 1000)}</div>
              </div>
              <div className='column-justify-between tar fz-wb-550'>
                <div>
                  <div className=" green">+{toThousands(item.amount)} {item.symbol}</div>
                </div>
                <div className='sub-text'>+{toThousands(item.amount_usdt)} USDT(價值)</div>
              </div>
            </div>
          </Cell>
        ))
      }
    </List>
  )
}

export default observer(Record);