import { Button, Canvas, Image } from '@tarojs/components';

import { Swiper } from '@taroify/core';
import { GoodJob } from '@taroify/icons';
import { useCallback, useEffect, useRef, useState } from 'react';

import LoginDialog from '@/components/login-dialog';
import { PageUrl } from '@/constants/app';
import useUserInfo from '@/hooks/use-user-info';
import { EarnType, UserProfitListItem } from '@/types/partner';
import { openCustomerServiceChat } from '@/utils/common';
import { becomePartner, formatMoney, formatTimestamp, formatUserId, getLastProfitList } from '@/utils/partner';
import { navigateTo } from '@/utils/route';
import { isNeedPhone, requestUserInfo } from '@/utils/user';

import './index.less';

const PREFIX = 'partner-intro';

export default function PartnerIntro() {
  const userInfo = useUserInfo();
  const needPhone = isNeedPhone(userInfo);
  const [loginVisible, setLoginVisible] = useState(false);

  const handleOpenService = useCallback(() => {
    openCustomerServiceChat('https://work.weixin.qq.com/kfid/kfc4fcf6b109b3771d7');
  }, []);

  const handleBindSuccess = useCallback(async () => {
    await becomePartner();
    await requestUserInfo();
    setLoginVisible(false);
  }, []);
  const handleBecomePartner = useCallback(() => {
    if (needPhone) {
      setLoginVisible(true);
      return false;
    } else {
      handleBindSuccess();
      return true;
    }
  }, [handleBindSuccess, needPhone]);

  const handleConfirm = useCallback(() => {
    if (!userInfo.isPartner && !handleBecomePartner()) {
      return;
    }
    navigateTo(PageUrl.GroupOwnerCertificate);
  }, [handleBecomePartner, userInfo.isPartner]);

  const handleJump = useCallback(() => {
    if (!userInfo.isPartner && !handleBecomePartner()) {
      return;
    }
    navigateTo(PageUrl.PartnerShareVip);
  }, [handleBecomePartner, userInfo.isPartner]);

  const timerRef = useRef<NodeJS.Timeout | null>(null);
  const [bannerList, setBannerList] = useState<UserProfitListItem[]>([]);

  const getBannerList = useCallback(async () => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }

    const list = await getLastProfitList();
    setBannerList(list);

    timerRef.current = setTimeout(
      () => {
        getBannerList();
      },
      3000 * (list.length || 10)
    );
  }, []);

  useEffect(() => {
    getBannerList();

    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
        timerRef.current = null;
      }
    };
  }, [getBannerList]);

  const showedRef = useRef(false);

  useEffect(() => {
    if (showedRef.current || !userInfo.userId) {
      return;
    }
    showedRef.current = true;
    if (!userInfo.isPartner) {
      handleBecomePartner();
    }
  }, [userInfo]);

  return (
    <div className={PREFIX}>
      <Image
        src="https://publiccdn.neighbourhood.com.cn/img/partner-intro-bg.png"
        className={`${PREFIX}__bg`}
        mode="aspectFill"
      />
      <div className={`${PREFIX}__slogan`}>
        <div>邀请朋友加入播络</div>
        <div>
          高达<div className={`${PREFIX}__slogan-highlight`}>75%</div>分成
        </div>
      </div>
      <div className={`${PREFIX}__main`}>
        <div className={`${PREFIX}__swiper-wrapper`}>
          <Image
            className={`${PREFIX}__swiper-bg`}
            src="https://publiccdn.neighbourhood.com.cn/img/partner-swipe-item.png"
            mode="aspectFill"
          />
          <Swiper className={`${PREFIX}__swiper`} autoplay={3000} touchable={false}>
            {bannerList.map((item, index) => (
              <Swiper.Item className={`${PREFIX}__swiper-item`} key={`${item.userId}-${index}`}>
                <div className={`${PREFIX}__swiper-item-top-line`}>
                  <div className={`${PREFIX}__swiper-item-time`}>{formatTimestamp(item.updatedAt)}</div>
                  <div className={`${PREFIX}__swiper-item-id`}>
                    用户 <div className="id">{formatUserId(item.userId)}</div>
                  </div>
                </div>
                <div className={`${PREFIX}__swiper-item-details`}>
                  <div>
                    <div className={`${PREFIX}__swiper-item-tag`}>分成收入</div>
                    <div className={`${PREFIX}__swiper-item-info`}>
                      {[EarnType.CHAT_ACTIVITY_SHARE_L1, EarnType.CHAT_ACTIVITY_SHARE_L2].includes(item.earnType)
                        ? '主播被开聊'
                        : '会员支付'}
                      <div className="money">+{formatMoney(item.amount)}</div>
                    </div>
                  </div>
                  <div className={`${PREFIX}__swiper-item-info`}>
                    累计<div className="money">{formatMoney(item.total)}</div>
                  </div>
                </div>
              </Swiper.Item>
            ))}
          </Swiper>
        </div>

        <div className={`${PREFIX}__block`}>
          <div className={`${PREFIX}__title`}>
            群主认证
            <div className={`${PREFIX}__recommend`}>
              <GoodJob />
              强烈推荐
            </div>
          </div>
          <div className={`${PREFIX}__card ${PREFIX}__special`}>
            <div className={`${PREFIX}__body`}>
              <div className="center">
                完成群主认证后，群成员通过该群访问任何人分享的播络小程序进行注册，你都能获得分成
              </div>
            </div>
            <Button className={`${PREFIX}__service`} onClick={handleConfirm}>
              立即认证
            </Button>
          </div>
        </div>
        <div className={`${PREFIX}__block`}>
          <div className={`${PREFIX}__title`}>3重收益</div>
          <div className={`${PREFIX}__card`}>
            <div className={`${PREFIX}__h1`}>直接分成：</div>
            <div className={`${PREFIX}__body`}>
              直接获得被邀请人付款金额的<span className={`${PREFIX}__highlight`}>20%</span>
            </div>
            <div className={`${PREFIX}__h1`}>主播分成：</div>
            <div className={`${PREFIX}__body`}>
              邀请的主播创建模卡，被企业开聊，每日可获得收益，分成比例高达
              <span className={`${PREFIX}__highlight`}>50%</span>
            </div>
            <div className={`${PREFIX}__h1`}>邀请合伙人：</div>
            <div className={`${PREFIX}__body`}>
              你邀请的人也加入合伙人，你可获得所邀合伙人收益的<span className={`${PREFIX}__highlight`}>5%</span>
            </div>
          </div>
        </div>
        <div className={`${PREFIX}__block`}>
          <div className={`${PREFIX}__title`}>邀请方法</div>
          <div className={`${PREFIX}__card`}>
            <div className={`${PREFIX}__body`}>
              <div className={`${PREFIX}__h1`}>方法一：</div>
              <div>点击下方“赠送会员给好友”，给群员、好友送会员，每周可以送一次</div>
              <div className={`${PREFIX}__h1`}>方法二：</div>
              <div>分享通告列表页、通告详情页等页面至群、好友</div>
            </div>
          </div>
        </div>
        <div className={`${PREFIX}__block`}>
          <div className={`${PREFIX}__title`}>交流群</div>
          <div className={`${PREFIX}__card  ${PREFIX}__special`}>
            <div className={`${PREFIX}__h1 no-dot`}>加入播络合伙人交流群，分享经验</div>
            <Button className={`${PREFIX}__service`} onClick={handleOpenService}>
              点击加入
            </Button>
          </div>
        </div>
      </div>
      <Canvas id="posterCanvas" canvas-id="posterCanvas" type="2d" style="width: 750px; height: 1334px;" />

      <div className={`${PREFIX}__footer`}>
        <Button className={`${PREFIX}__share-button`} onClick={handleJump}>
          赠送会员给好友
        </Button>
      </div>

      {loginVisible && (
        <LoginDialog onCancel={() => setLoginVisible(false)} onSuccess={handleBindSuccess} needPhone={needPhone} />
      )}
    </div>
  );
}
