import Taro, { Component } from '@tarojs/taro';
import { ComponentClass } from 'react';
import { Button, View, Image, Text } from '@tarojs/components';
import {
  PaymentAndActiveInfo,
  CustomerBeanAccountVo,
} from '../../../../api/baseClass';
import { confirmPay, fetchDeductionInfo } from '../../../../api/order';

import payWayWxLogo from '../../../../images/order/pay_wechat_icon@2x.png';
import payWayAimiLogo from '../../../../images/order/pay_aimi_icon@2x.png';
import payWayHairLogo from '../../../../images/order/pay_chuifengdou_icon@2x.png';
import payWayComLogo from '../../../../images/order/pay_tongyongdou_icon@2x.png';

import './OrderPayway.scss';
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 { getPayType } from '../../../../utils/payType';
import Order from '../../../../types/Order/Order';
import { Customer } from '../../../../types/Customer/Customer';

type PageOwnProps = {
  onPayDoneCallback: () => void;
  userinfo: Customer;
  orderInfo: Order;
  accounts: CustomerBeanAccountVo[];
  payInfos: {
    paymentAndActiveInfos: PaymentAndActiveInfo[];
    paymentConfId: number;
  };
};
type PageState = {
  prePay: boolean;
  payWay: null | {
    activeId: number | undefined;
    amount: number | undefined;
    avtiveComment: string;
    deductionValue: number | undefined;
    isDeduction: number | undefined;
    payType: string;
    payVersion: string;
  };
  accountsInfo: null | {};
  deductionInfos: null | {
    amiAccount: number;
    beanAccount: number;
    deductionMoney: number;
    deductionType: string;
    orderMoney: number;
    payMoney: number;
    payType: string;
    remainAccount: number;
    titlePerfix: string;
  };
};

interface OrderPayway {
  props: PageOwnProps;
  state: PageState;
}
class OrderPayway extends Component {
  static defaultProps = {
    accounts: [],
    payInfos: {
      paymentAndActiveInfos: [],
      paymentConfId: 0,
    },
    orderInfo: {
      actualMoney: 0,
      areaId: 0,
      areaName: '',
      consumeType: '',
      createAt: '',
      customerCellphone: '',
      customerId: 0,
      customerName: '',
      deductionBean: 0,
      deductionMoney: 0,
      equipmentNum: '',
      equipmentPosition: '',
      id: 0,
      operateId: 0,
      operateName: '',
      operationMode: '',
      orderName: '',
      orderNumber: '',
      orderState: '',
      outTradeNo: '',
      payType: '',
      payableMoney: 0,
      serviceId: 0,
      serviceName: '',
      thirdDiscountMoney: 0,
      thirdTradeNumber: '',
      updateDate: '',
    },
  };
  constructor(props: PageOwnProps) {
    super(props);
    this.state = {
      prePay: true,
      payWay: null,
      accountsInfo: null,
      deductionInfos: null,
    };
  }
  componentWillReceiveProps(props) {
    if (props.accounts.length !== 0 && this.props.accounts.length === 0) {
      let amiAccount = props.accounts.find(item => item.serviceId === '0');
      let comAccount = props.accounts.find(item => item.serviceId === '1');
      let beanAccount = props.accounts.find(
        item => item.serviceId !== '0' && item.serviceId !== '1',
      );
      let accountsInfo = {
        '6': amiAccount ? amiAccount.money : 0,
        '8': comAccount ? comAccount.money : 0,
        '7': beanAccount ? beanAccount.money : 0,
      };
      this.setState({
        accountsInfo: accountsInfo,
      });
    }
  }

  changePayWay(payWay: PaymentAndActiveInfo, useWay?: boolean) {
    if (useWay) return;
    this.setState({
      payWay: payWay,
    });
  }

  changePayState() {
    const { orderInfo, payInfos } = this.props;
    const { payWay } = this.state;
    if (payWay) {
      fetchDeductionInfo({
        orderId: orderInfo.id,
        payType: payWay.payType,
        paymentConfId: payInfos.paymentConfId,
      })
        .then(res => {
          this.setState({
            deductionInfos: res.data,
            prePay: false,
          });
        })
        .catch(err => {
          console.log(err);
          Taro.showToast({
            title: '获取抵扣信息失败',
            icon: 'none',
          });
        });
    } else {
      Taro.showToast({
        title: '请选择支付方式',
        icon: 'none',
      });
    }
  }

  callNativePay() {
    const {
      userinfo: { customerId },
      orderInfo: { id },
      payInfos,
      onPayDoneCallback,
    } = this.props;
    const { payWay } = this.state;
    confirmPay({
      orderId: id,
      payType: payWay ? payWay.payType : '',
      [payWay && payWay.activeId ? 'activeId' : 'notUse']: payWay
        ? payWay.activeId
        : 0,
      returnUrl: '',
      callType: '3',
      paymentConfId: payInfos.paymentConfId,
    })
      .then(res => {
        const { payStr } = res;
        if (payStr) {
          const key = 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);
              onPayDoneCallback();
            })
            .catch(err => {
              Taro.showToast({
                title: err.msg || '发起支付失败',
                icon: 'none',
              });
            });
        } else {
          onPayDoneCallback();
        }
      })
      .catch(err => {
        console.log(err);

        Taro.showToast({
          title: err.msg || '发起支付失败',
          icon: 'none',
        });
      });
  }
  render() {
    const { prePay, payWay, accountsInfo, deductionInfos } = this.state;
    const {
      payInfos: { paymentAndActiveInfos },
      orderInfo,
    } = this.props;
    const payInfoList = paymentAndActiveInfos.filter(
      item =>
        item.payType === '2' ||
        item.payType === '6' ||
        item.payType === '7' ||
        item.payType === '8',
    );
    const useAmi = accountsInfo && accountsInfo['6'] >= orderInfo.payableMoney;
    const useCom = accountsInfo && accountsInfo['8'] >= orderInfo.payableMoney;
    const useBean = accountsInfo && accountsInfo['7'] >= orderInfo.payableMoney;

    return (
      <View className='OrderPayway'>
        {prePay ? (
          payInfoList.length ? (
            payInfoList.map(payway =>
              payway.payType === '2' ? (
                <View
                  key={payway.payType}
                  className='OrderPay-payway'
                  onClick={() => this.changePayWay(payway)}>
                  <Image className='OrderPay-icon' src={payWayWxLogo} />
                  <Text className='OrderPay-text'>
                    {getPayType(payway.payType)}
                  </Text>
                  <View
                    className={`OrderPay-check ${
                      payWay && payWay.payType === payway.payType
                        ? 'checked'
                        : ''
                    }`}
                  />
                </View>
              ) : payway.payType === '6' ? (
                <View
                  key={payway.payType}
                  className={`OrderPay-payway ${useAmi ? '' : 'disabled'}`}
                  onClick={() => this.changePayWay(payway, !useAmi)}>
                  <Image className='OrderPay-icon' src={payWayAimiLogo} />
                  <Text className='OrderPay-text'>
                    {getPayType(payway.payType)}(余额：
                    {accountsInfo && accountsInfo['6']
                      ? accountsInfo['6'].toFixed(2)
                      : '0.00'}
                    )
                  </Text>
                  <View
                    className={`OrderPay-check ${
                      payWay && payWay.payType === payway.payType
                        ? 'checked'
                        : ''
                    } ${useAmi ? '' : 'disabled'}`}
                  />
                </View>
              ) : payway.payType === '7' ? (
                <View
                  key={payway.payType}
                  className={`OrderPay-payway ${useBean ? '' : 'disabled'}`}
                  onClick={() => this.changePayWay(payway, !useBean)}>
                  <Image className='OrderPay-icon' src={payWayHairLogo} />
                  <Text className='OrderPay-text'>
                    {orderInfo.serviceName}豆(余额：
                    {accountsInfo && accountsInfo['7']
                      ? accountsInfo['7'].toFixed(2)
                      : '0.00'}
                    )
                  </Text>
                  <View
                    className={`OrderPay-check ${
                      payWay && payWay.payType === payway.payType
                        ? 'checked'
                        : ''
                    } ${useBean ? '' : 'disabled'}`}
                  />
                </View>
              ) : payway.payType === '8' ? (
                <View
                  key={payway.payType}
                  className={`OrderPay-payway ${useCom ? '' : 'disabled'}`}
                  onClick={() => this.changePayWay(payway, !useCom)}>
                  <Image className='OrderPay-icon' src={payWayComLogo} />
                  <Text className='OrderPay-text'>
                    {getPayType(payway.payType)}(余额：
                    {accountsInfo && accountsInfo['8']
                      ? accountsInfo['8'].toFixed(2)
                      : '0.00'}
                    )
                  </Text>
                  <View
                    className={`OrderPay-check ${
                      payWay && payWay.payType === payway.payType
                        ? 'checked'
                        : ''
                    } ${useCom ? '' : 'disabled'}`}
                  />
                </View>
              ) : null,
            )
          ) : null
        ) : (
          <View>
            {payWay && payWay.payType === '2' ? (
              <View className='OrderPay-payinfo'>
                <Text>订单金额</Text>
                <Text>{deductionInfos && deductionInfos.payMoney}</Text>
              </View>
            ) : payWay && payWay.payType === '6' ? (
              <View className='OrderPay-payinfo'>
                <Text>艾米余额</Text>
                <Text>
                  {deductionInfos && deductionInfos.amiAccount.toFixed(2)}
                </Text>
              </View>
            ) : payWay && (payWay.payType === '7' || payWay.payType === '8') ? (
              <View className='OrderPay-payinfo'>
                <Text>
                  {deductionInfos && deductionInfos.titlePerfix}豆余额
                </Text>
                <Text>
                  {deductionInfos && deductionInfos.beanAccount.toFixed(2)}
                </Text>
              </View>
            ) : null}

            {deductionInfos && deductionInfos.deductionType === '1' ? (
              <View>
                <View className='OrderPay-payinfo'>
                  <Text>
                    {deductionInfos.titlePerfix}豆抵扣金额（余额:
                    {deductionInfos.beanAccount.toFixed(2)}）
                  </Text>
                  <Text>{deductionInfos.deductionMoney.toFixed(2)}</Text>
                </View>
                <View className='OrderPay-DeductionInfo'>
                  豆抵扣总消费额的
                  {payWay && payWay.deductionValue
                    ? payWay.deductionValue * 100
                    : 0}
                  %，不满0.01元，累计算1分
                </View>
              </View>
            ) : deductionInfos && deductionInfos.deductionType === '2' ? (
              <View>
                <View className='OrderPay-payinfo'>
                  <Text>
                    通用豆抵扣金额（余额:{deductionInfos.beanAccount.toFixed(2)}
                    ）
                  </Text>
                  <Text>{deductionInfos.deductionMoney.toFixed(2)}</Text>
                </View>
                <View className='OrderPay-DeductionInfo'>
                  豆抵扣总消费额的
                  {payWay && payWay.deductionValue
                    ? payWay.deductionValue * 100
                    : 0}
                  %，不满0.01元，累计算1分
                </View>
              </View>
            ) : deductionInfos && deductionInfos.deductionType === '3' ? (
              <View className='OrderPay-payinfo'>
                <Text>
                  艾米抵扣金额（余额:{deductionInfos.amiAccount.toFixed(2)}）
                </Text>
                <Text>{deductionInfos.deductionMoney.toFixed(2)}</Text>
              </View>
            ) : null}
            {payWay && payWay.payType === '2' ? (
              <View className='OrderPay-payinfo'>
                <Text>订单支付</Text>
                <Text>{deductionInfos && deductionInfos.payMoney}</Text>
              </View>
            ) : payWay && payWay.payType === '6' ? (
              <View>
                <View className='OrderPay-payinfo'>
                  <Text>艾米支付余额</Text>
                  <Text>
                    -{deductionInfos && deductionInfos.payMoney.toFixed(2)}
                  </Text>
                </View>
                <View className='OrderPay-payinfo'>
                  <Text>艾米支付结余</Text>
                  <Text>
                    {deductionInfos && deductionInfos.remainAccount.toFixed(2)}
                  </Text>
                </View>
              </View>
            ) : payWay && (payWay.payType === '7' || payWay.payType === '8') ? (
              <View>
                <View className='OrderPay-payinfo'>
                  <Text>
                    {deductionInfos && deductionInfos.titlePerfix}豆支付
                  </Text>
                  <Text>
                    -{deductionInfos && deductionInfos.payMoney.toFixed(2)}
                  </Text>
                </View>
                <View className='OrderPay-payinfo'>
                  <Text>
                    {deductionInfos && deductionInfos.titlePerfix}豆支付结余
                  </Text>
                  <Text>
                    {deductionInfos && deductionInfos.remainAccount.toFixed(2)}
                  </Text>
                </View>
              </View>
            ) : null}
          </View>
        )}
        {prePay ? (
          <Button
            className='button OrderPay-next'
            onClick={this.changePayState}>
            下一步
          </Button>
        ) : (
          <Button className='button OrderPay-next' onClick={this.callNativePay}>
            确认支付
          </Button>
        )}
      </View>
    );
  }
}

export default OrderPayway as ComponentClass<PageOwnProps, PageState>;
