import Taro, { Component } from '@tarojs/taro';
import { ComponentClass } from 'react';
import { View, Canvas, Image, Text } from '@tarojs/components';

import RefreshIcon from '../../images/barcode/pic_shuaxin@2x.png';
import ArrIcon from '../../images/barcode/icon_fangda@2x.png';
import CodeIcon from '../../images/water/nocode@2x.png';

import wxbarcode from 'wxbarcode';

import './BarCode.scss';
import { UserState, updateUserInfo } from '../../store/rootReducers/userinfo';
import { connect } from '@tarojs/redux';
import { fetchPayOrder, fetchOrderDetailAndPay } from '../../api/order';
import OrderInfo from '../Order/components/OrderInfo/OrderInfo';
import OrderTitle from '../Order/components/OrderTitle/OrderTitle';
import OrderPayway from '../Order/components/OrderPayway/OrderPayway';
import {
  PaymentAndActiveInfo,
  CustomerBeanAccountVo,
} from '../../api/baseClass';
import { Customer } from '../../types/Customer/Customer';
import { refreshCodeBar } from '../../api/customer';
import Order from '@/types/Order/Order';
import { shareHandle } from '@/common/shareMethod';

type PageStateProps = {
  userinfo: Customer;
};
type PageDispatchProps = {
  updateUserInfo: (e: UserState) => void;
};

type PageOwnProps = {};
type PageState = {
  ScreenBrightness: number;
  showPayOrder: boolean;
  showBig: boolean;
  accounts: CustomerBeanAccountVo[];
  orderInfo: Order;
  payInfos: {
    paymentAndActiveInfos: PaymentAndActiveInfo[];
    paymentConfId: number;
  };
  deductionInfos: {
    amiAccount: number;
    beanAccount: number;
    deductionMoney: number;
    deductionType: string;
    orderMoney: number;
    payMoney: number;
    payType: string;
    remainAccount: number;
    titlePerfix: string;
  };
  showBackTag: boolean;
};

type IProps = PageStateProps & PageOwnProps & PageDispatchProps;
interface BarCode {
  props: IProps;
  state: PageState;
}

@connect(
  ({ userinfo }) => ({
    userinfo,
  }),
  dispatch => ({
    updateUserInfo(entity: UserState) {
      dispatch(updateUserInfo(entity));
    },
  }),
)
class BarCode extends Component {
  constructor(props: PageOwnProps) {
    super(props);
    this.state = {
      ScreenBrightness: 1,
      showPayOrder: false,
      showBig: false,
      accounts: [],
      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: '',
      },
      payInfos: {
        paymentAndActiveInfos: [],
        paymentConfId: 0,
      },
      deductionInfos: {
        amiAccount: 0,
        beanAccount: 0,
        deductionMoney: 0,
        deductionType: '',
        orderMoney: 0,
        payMoney: 0,
        payType: '',
        remainAccount: 0,
        titlePerfix: '',
      },
      showBackTag: false,
    };
  }
  onShareAppMessage = shareHandle;

  componentWillMount() {
    const { userinfo } = this.props;
    fetchPayOrder({
      customerId: userinfo.customerId,
    })
      .then(res => {
        if (res.data.length) {
          this.fetchOrder(res.data[0].id);
          this.setState({ showPayOrder: true });
        } else {
          this.drawBarCode();
        }
      })
      .catch(err => {
        console.log(err);
      });
    console.log('调整亮度');
    Taro.getScreenBrightness()
      .then(({ value }) => {
        console.log(value);
        this.setState({
          ScreenBrightness: value,
        });
        Taro.setScreenBrightness({
          value: 1,
        });
      })
      .catch(err => {
        console.log(err);
        Taro.setScreenBrightness({
          value: 1,
        });
      });
    this.checkShowBackTag();
  }

  componentWillUnmount() {
    console.log('调整亮度');
    const { ScreenBrightness } = this.state;
    console.log(ScreenBrightness);

    Taro.setScreenBrightness({
      value: ScreenBrightness,
    });
  }

  checkShowBackTag() {
    let params = this.$router.params;
    console.log(params);
    if (params && params.backPage) {
      this.setState({
        showBackTag: true,
      });
    }
  }

  goBackPage() {
    let params = this.$router.params;
    if (params && params.backPage) {
      Taro.redirectTo({
        url: decodeURIComponent(params.backPage),
      });
    }
  }

  fetchOrder(id: number) {
    return fetchOrderDetailAndPay({
      id,
    })
      .then(res => {
        const { accounts, orderInfo, payInfos } = res;
        this.setState({
          accounts: accounts,
          orderInfo: orderInfo,
          payInfos: payInfos,
        });
      })
      .catch(err => {
        console.log(err);
      });
  }

  payDoneHandle() {
    this.setState(
      {
        showPayOrder: false,
      },
      () => {
        this.drawBarCode();
      },
    );
  }
  drawBarCode() {
    const { userinfo } = this.props;
    const routeParams = this.$router.params;
    let serviceId = '';
    if (routeParams && routeParams.serviceId) {
      serviceId =
        routeParams.serviceId.length === 1
          ? '0' + routeParams.serviceId
          : routeParams.serviceId;
    }
    console.log('serviceId: ', serviceId);
    if (userinfo.idBar && userinfo.idBar.length > 2) {
      let idBar =
        userinfo.idBar.substring(0, userinfo.idBar.length - 2) + serviceId;
      wxbarcode.barcode('BarCode', idBar, 646, 188);
      wxbarcode.barcode('BarCodeBig', idBar, 700, 364);
    } else {
      this.refreshCodeBar();
    }
  }

  toggleBigBarCode() {
    const { showBig } = this.state;
    this.setState({
      showBig: !showBig,
    });
  }
  refreshCodeBar() {
    const { updateUserInfo } = this.props;
    refreshCodeBar()
      .then(res => {
        console.log(res);
        const data = res.data;
        updateUserInfo({
          idBar: data,
        });
        this.drawBarCode();
      })
      .catch(err => {
        Taro.showToast({
          title: err.msg || '获取失败',
          icon: 'none',
        });
      });
  }

  render() {
    const { userinfo } = this.props;
    const {
      showPayOrder,
      showBig,
      orderInfo,
      payInfos,
      accounts,
      showBackTag,
    } = this.state;
    return (
      <View className='BarCode'>
        {showPayOrder && (
          <View className='OrderBox'>
            <OrderTitle price={orderInfo.payableMoney} />
            <OrderInfo orderInfo={orderInfo} />
            <OrderPayway
              onPayDoneCallback={this.payDoneHandle}
              userinfo={userinfo}
              accounts={accounts}
              orderInfo={orderInfo}
              payInfos={payInfos}
            />
          </View>
        )}
        <View className={showPayOrder ? 'blur' : ''}>
          {showBackTag && (
            <View className='BackTag' onClick={this.goBackPage}>
              <Image className='icon' src={CodeIcon} />
              <Text className='text'>隐藏条码</Text>
            </View>
          )}
          <View className={`BarCodeBox ${showBig ? 'BarCodeBoxBig' : ''}`}>
            <Image
              className='BarCodeBox-refresh'
              src={RefreshIcon}
              onClick={this.refreshCodeBar}
            />
            {showPayOrder ? null : (
              <View className={`BarCodeImg ${showBig ? 'BarCodeImgBig' : ''}`}>
                <Canvas
                  className={`BarCodeCav ${showBig ? 'show' : ''}`}
                  canvasId='BarCodeBig'
                />
                <Canvas
                  className={`BarCodeCav ${showBig ? '' : 'show'}`}
                  canvasId='BarCode'
                />
              </View>
            )}
            <View className='toggleBtn' onClick={this.toggleBigBarCode}>
              <Image
                className={`arricon ${showBig ? 'rever' : ''}`}
                src={ArrIcon}
              />
            </View>
          </View>
          <View className='warnning'>
            如扫描条码终端无响应，请刷新条码后重试！
          </View>
        </View>
      </View>
    );
  }
}

export default BarCode as ComponentClass<PageOwnProps, PageState>;
