import './Account.scss';
import AccountCardBg from '../../images/account/bg_zhanghu@2x.png';

import TBeanIcon from '../../images/home/icon_tongyongdou@2x.png';
import HBeanIcon from '../../images/home/icon_chuifengdou@2x.png';
import WBeanIcon from '../../images/home/ic_yinshui@2x.png';
import SBeanIcon from '../../images/home/ic_xiyu@2x.png';
import WechatIcon from '../../images/payway/img_wechat@2x.png';
import PaySelectedIcon from '../../images/payway/pc_sel_icon@2x.png';
import radioIcon from '../../images/login/pc_nor_icon@2x.png';

import { View, Button, Image, Text } from '@tarojs/components';
import Taro, { useState } from '@tarojs/taro';
import { useSelector } from '@tarojs/redux';
import { Customer } from '@/types/Customer/Customer';
import { Service } from '@/api/home';
import useRechargePay from '@/hooks/useRechargePay';
import useAllBeanCount, { BeanType } from '@/hooks/useAllBeanCount';
import { rechargeOrder } from '@/api/account';
import AES from 'crypto-js/aes';
import Utf8 from 'crypto-js/enc-utf8';
import ECBmode from 'crypto-js/mode-ecb';
import PaddingPkcs7 from 'crypto-js/pad-pkcs7';
import useCreditDeposits from '@/hooks/useCreditDeposits';

enum PaywayCode {
  wx = 2,
}

export const AccountComponent = () => {
  const [payConfigId, setPayConfigId] = useState(0);
  const [paywayId, setPaywayId] = useState(PaywayCode.wx);

  const userinfo = useSelector(
    (state: { userinfo: Customer }) => state.userinfo,
  );
  const serviceList = useSelector(
    (state: { serviceList: Service[] }) => state.serviceList,
  );
  const { paywayList, payConfigList, isFirstRecharge } = useRechargePay(
    userinfo.areaId,
    userinfo.customerId,
  );
  const [filterBeanList, fetchNewBeanList] = useAllBeanCount(
    userinfo,
    serviceList,
  );
  const creditInfo = useCreditDeposits(userinfo.areaId);

  const clickPayBtn = () => {
    if (!payConfigId) {
      Taro.showToast({
        title: '请选择充值金额',
        icon: 'none',
      });
      return;
    }
    if (!paywayId) {
      Taro.showToast({
        title: '请选择支付方式',
        icon: 'none',
      });
      return;
    }
    let preAimiItem = filterBeanList.find(
      item => item.serviceId === BeanType.aimi,
    );
    let preAimi = preAimiItem ? preAimiItem.money : 0;
    console.log('in recharge: preAimi', preAimiItem, preAimi);
    rechargeOrder({
      id: payConfigId,
      customerId: userinfo.customerId,
      isFirstRecharge: isFirstRecharge,
      rechargeType: paywayId.toString(),
    })
      .then(res => {
        const { canCall, payStr } = res;
        console.log(res);
        if (canCall) {
          if (payStr) {
            const key = userinfo.customerId.toString().padEnd(16, '0');
            const payData = JSON.parse(
              AES.decrypt(payStr, Utf8.parse(key), {
                mode: ECBmode,
                padding: PaddingPkcs7,
              }).toString(Utf8),
            );
            console.log(payData);
            Taro.requestPayment({
              timeStamp: payData.msg.timeStamp.toString(),
              nonceStr: payData.msg.nonceStr,
              package: payData.msg.package,
              signType: payData.msg.signType,
              paySign: payData.msg.paySign,
            })
              .then(res => {
                console.log(res);
                fetchNewBeanList(
                  userinfo.customerId,
                  userinfo.areaId,
                  userinfo.customerPhone,
                )
                  .then(beanAccount => {
                    let aimiItem = beanAccount.find(
                      item => item.serviceId === '0',
                    );
                    console.log(aimiItem, preAimi);
                    if (aimiItem && aimiItem.money === preAimi) {
                      Taro.showModal({
                        title: '提示',
                        content:
                          '由于网络原因，本次充值可能延迟到账，请稍后查看余额',
                      });
                    }
                  })
                  .catch(console.error);
              })
              .catch(err => {
                Taro.showToast({
                  title: err.msg || '发起支付失败',
                  icon: 'none',
                });
              });
          }
        } else {
          Taro.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      })
      .catch(err => {
        Taro.showToast({
          title: err.msg || '呼起失败！',
          icon: 'none',
        });
      });
  };

  return (
    <View className='Account'>
      <View className='Account-Card-warp'>
        <View className='Account-Card'>
          <Image className='bg' src={AccountCardBg} />
          <View className='Account-Card-money'>
            <View className='Account-Card-Aimi'>
              <View className='Account-Card-label'>艾米余额</View>
              {filterBeanList.length &&
                filterBeanList.map(beanItem =>
                  beanItem.serviceId === BeanType.aimi ? (
                    <View key={beanItem.serviceId} className='Account-Card-num'>
                      {beanItem.money.toFixed(2)}
                    </View>
                  ) : null,
                )}
            </View>
            {creditInfo.showType && (
              <View className='Account-Card-credit'>
                <View className='Account-Card-label'>
                  {creditInfo.showType == '1' ? '我的授信' : '我的保证金'}
                </View>
                <View className='Account-Card-num'>
                  {creditInfo.amount.toFixed(2)}
                </View>
              </View>
            )}
          </View>
          <View className='Account-line' />

          <View className='Account-Card-Bean'>
            {filterBeanList.length &&
              filterBeanList.map(beanItem =>
                beanItem.serviceId === BeanType.common ? (
                  <View
                    key={beanItem.serviceId}
                    className='Account-Card-BeanItem'>
                    <Image className='Account-Card-BeanIcon' src={TBeanIcon} />
                    <Text>通用豆：</Text>
                    <Text className='Account-Card-BeanCount'>
                      {beanItem.money ? beanItem.money.toFixed(2) : '0.00'}
                    </Text>
                  </View>
                ) : beanItem.serviceId === BeanType.water ? (
                  <View
                    key={beanItem.serviceId}
                    className='Account-Card-BeanItem'>
                    <Image className='Account-Card-BeanIcon' src={WBeanIcon} />
                    <Text>饮水豆：</Text>
                    <Text className='Account-Card-BeanCount'>
                      {beanItem.money ? beanItem.money.toFixed(2) : '0.00'}
                    </Text>
                  </View>
                ) : beanItem.serviceId === BeanType.hairDryer ? (
                  <View
                    key={beanItem.serviceId}
                    className='Account-Card-BeanItem'>
                    <Image className='Account-Card-BeanIcon' src={HBeanIcon} />
                    <Text>吹风豆：</Text>
                    <Text className='Account-Card-BeanCount'>
                      {beanItem.money ? beanItem.money.toFixed(2) : '0.00'}
                    </Text>
                  </View>
                ) : beanItem.serviceId === BeanType.shower ? (
                  <View
                    key={beanItem.serviceId}
                    className='Account-Card-BeanItem'>
                    <Image className='Account-Card-BeanIcon' src={SBeanIcon} />
                    <Text>洗浴豆：</Text>
                    <Text className='Account-Card-BeanCount'>
                      {beanItem.money ? beanItem.money.toFixed(2) : '0.00'}
                    </Text>
                  </View>
                ) : null,
              )}
          </View>
        </View>
      </View>

      <View className='Account-Money'>
        {payConfigList.map(item => (
          <View
            key={item.id}
            className={`Account-Money-Item ${
              payConfigId === item.id ? 'selected' : ''
            }`}
            onClick={() => setPayConfigId(item.id)}>
            <View>{item.rechargeMoney.toFixed(2)}元</View>
            {item.giveId && (
              <View className='giveText'>
                送{item.giveName}
                {item.giveMoney}个
              </View>
            )}
          </View>
        ))}
      </View>

      <View className='Account-Payway'>
        {paywayList.map(item =>
          item.id === 2 ? (
            <View
              key={item.id}
              className='Account-Payway-Item'
              onClick={() => setPaywayId(item.id)}>
              <Image className='Account-Payway-Item-icon' src={WechatIcon} />
              <View className='Account-Payway-Item-name'>{item.name}</View>
              {paywayId === item.id ? (
                <Image
                  className='Account-Payway-Item-state'
                  src={PaySelectedIcon}
                />
              ) : (
                <Image className='Account-Payway-Item-state' src={radioIcon} />
              )}
            </View>
          ) : null,
        )}
      </View>

      <Button className='Account-Paybtn' onClick={clickPayBtn}>
        确定充值
      </Button>
    </View>
  );
};
