import { Button, Image } from '@tarojs/components';
import Taro, { useDidShow } from '@tarojs/taro';

import { Dialog } from '@taroify/core';
import { Question } from '@taroify/icons';
import { useCallback, useEffect, useState } from 'react';

import { PageUrl } from '@/constants/app';
import { PartnerProfitsState } from '@/types/partner';
import { formatMoney, getPartnerProfitStat, withdrawMoney } from '@/utils/partner';
import { navigateTo } from '@/utils/route';
import Toast from '@/utils/toast';

import './index.less';

const PREFIX = 'partner-kanban';

function TipDialog(props: { open: boolean; onClose: () => void }) {
  return (
    <Dialog open={props.open} onClose={props.onClose}>
      <Dialog.Content>
        <div className={`${PREFIX}-tip-dialog__container`}>
          <div
            className={`${PREFIX}-tip-dialog__title`}
          >{`会员支付的收益无需提现，\n支付15日后自动分账至微信零钱`}</div>
          <Button className={`${PREFIX}-tip-dialog__confirm-button`} onClick={props.onClose}>
            我知道了
          </Button>
        </div>
      </Dialog.Content>
    </Dialog>
  );
}

function WithdrawDialog(props: { open: boolean; onClose: () => void; count: number }) {
  const handleWithdraw = useCallback(async () => {
    if (Taro.canIUse('requestMerchantTransfer')) {
      try {
        const result = await withdrawMoney();
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-expect-error
        wx.requestMerchantTransfer({
          mchId: '1642470088',
          appId: 'wxf0724a83f8e377d2',
          package: result.packageInfo,
          success: (res: never) => {
            // res.err_msg将在页面展示成功后返回应用时返回ok，并不代表付款成功
            console.log('success:', res);
            Toast.success('提现成功');
            props.onClose();
          },
          fail: (res: never) => {
            Toast.error('提现失败');
            console.log('fail:', res);
          },
        });
      } catch (e) {
        Toast.error('提现订单创建失败');
        console.log(e);
      }
    } else {
      await Taro.showModal({
        content: '你的微信版本过低，请更新至最新版本。',
        showCancel: false,
      });
    }
  }, [props]);
  return (
    <Dialog open={props.open} onClose={props.onClose}>
      <Dialog.Content>
        <div className={`${PREFIX}-withdraw-dialog__container`}>
          <div className={`${PREFIX}-withdraw-dialog__title`}>本次申请提现金额为</div>
          <div className={`${PREFIX}-withdraw-dialog__count`}>
            {+props.count}
            <div className="yuan">元</div>
          </div>
          <div className={`${PREFIX}-withdraw-dialog__hint`}>单日提现最大200元</div>
          <Button className={`${PREFIX}-withdraw-dialog__confirm-button`} onClick={handleWithdraw}>
            提现
          </Button>
          <div className={`${PREFIX}-withdraw-dialog__cancel-button`} onClick={props.onClose}>
            取消
          </div>
        </div>
      </Dialog.Content>
    </Dialog>
  );
}

type PartnerKanbanProps = {
  simple?: boolean;
};
export default function PartnerKanban({ simple }: PartnerKanbanProps) {
  const [tipOpen, setTipOpen] = useState(false);
  const [withdrawOpen, setWithdrawOpen] = useState(false);
  const [stats, setStats] = useState<PartnerProfitsState>({
    availableBalance: 0,
    withdrawingBalance: 0,
    withdrawnBalance: 0,
    availableProfit: 0,
    withdrawnProfit: 0,
    failedProfit: 0,
  });
  const total =
    stats.availableBalance +
    stats.withdrawingBalance +
    stats.withdrawnBalance +
    stats.availableProfit +
    stats.withdrawnProfit;
  const handleNavigate = useCallback(() => {
    navigateTo(PageUrl.Partner);
  }, []);
  const handleNavigateRecord = useCallback(() => {
    navigateTo(PageUrl.WithdrawRecord);
  }, []);
  const handleViewTip = useCallback(() => {
    setTipOpen(true);
  }, []);
  const handleTipClose = useCallback(() => {
    setTipOpen(false);
  }, []);
  const getProfitStats = useCallback(async () => {
    const data = await getPartnerProfitStat();
    setStats(data);
  }, []);
  const handleViewWithdraw = useCallback(() => {
    if (stats.availableBalance < 0) {
      Toast.info('提现金额需大于等于0元');
      return;
    }
    // if (stats.availableBalance < 10 * 1000) {
    //   Toast.error('提现金额需大于等于10元');
    //   return;
    // }
    setWithdrawOpen(true);
  }, [stats.availableBalance]);
  const handleWithdrawClose = useCallback(() => {
    setWithdrawOpen(false);
    getProfitStats();
  }, [getProfitStats]);
  useDidShow(() => {
    getProfitStats();
  });
  useEffect(() => {
    getProfitStats();
  }, []);
  if (simple) {
    return (
      <div className={`${PREFIX} ${PREFIX}-simple`}>
        <Image
          className={`${PREFIX}-simple__bg`}
          src="https://publiccdn.neighbourhood.com.cn/img/partner_bg.png"
          mode="aspectFill"
        />
        <div className={`${PREFIX}-simple__content`}>
          <div className={`${PREFIX}-simple__title`}>总收益(元)</div>
          <div className={`${PREFIX}-simple__money`}>{formatMoney(total)}</div>
        </div>
        <div className={`${PREFIX}-simple__button`} onClick={handleNavigate}>
          详情
          <Image
            className={`${PREFIX}-simple__button-image`}
            mode="aspectFit"
            src={require('@/statics/svg/caret-right.svg')}
          />
        </div>
      </div>
    );
  }
  return (
    <div className={PREFIX}>
      <Image
        className={`${PREFIX}__bg`}
        src="https://publiccdn.neighbourhood.com.cn/img/partner_bg.png"
        mode="aspectFill"
      />
      <div className={`${PREFIX}__content`}>
        <div className={`${PREFIX}__total`}>
          <div className={`${PREFIX}__title`}>总收益（元）</div>
          <div className={`${PREFIX}__money`}>{formatMoney(total)}</div>
        </div>
        <div className={`${PREFIX}__details`}>
          <div className={`${PREFIX}__details-part`}>
            <div className={`${PREFIX}__title`}>可提现（元）</div>
            <div className={`${PREFIX}__money`}>{formatMoney(stats.availableBalance)}</div>
          </div>
          <div className={`${PREFIX}__details-part`}>
            <div className={`${PREFIX}__title`}>提现中（元）</div>
            <div className={`${PREFIX}__money`}>{formatMoney(stats.withdrawingBalance)}</div>
          </div>
          <div className={`${PREFIX}__details-part`}>
            <div className={`${PREFIX}__title`}>
              待分账（元）
              {!simple && <Question onClick={handleViewTip} />}
            </div>
            <div className={`${PREFIX}__money`}>{formatMoney(stats.availableProfit)}</div>
          </div>
        </div>
        <div className={`${PREFIX}__buttons`}>
          <Button className={`${PREFIX}__withdraw`} onClick={handleViewWithdraw}>
            提现
          </Button>
          <Button className={`${PREFIX}__record`} onClick={handleNavigateRecord}>
            提现记录
          </Button>
        </div>
      </div>
      <TipDialog open={tipOpen} onClose={handleTipClose} />
      <WithdrawDialog
        count={Math.min(Number(formatMoney(stats.availableBalance)), 200)}
        open={withdrawOpen}
        onClose={handleWithdrawClose}
      />
    </div>
  );
}
