import Taro, { Component, useEffect } 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, useSelector } from '@tarojs/redux';
import { Customer } from '../../types/Customer/Customer';
import { refreshCodeBar } from '../../api/customer';
import { shareHandle } from '@/common/shareMethod';
import { PayOrderState } from '@/store/rootReducers/orderState';
import WaitPayOrderComponent from '@/components/WaitPayOrder/WaitPayOrder';
import widthWaitPayOrderComponent from '@/components/WaitPayOrder/WaitPayOrder';

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

type PageOwnProps = {};
type PageState = {
  ScreenBrightness: number;
  showBig: boolean;
  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,
      showBig: false,
      showBackTag: false,
    };
  }
  onShareAppMessage = shareHandle;

  componentWillMount() {
    this.drawBarCode();
    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),
      });
    }
  }

  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 { showBig, showBackTag } = this.state;
    const payOrderState = useSelector(
      (state: { orderState: PayOrderState }) =>
        state.orderState.waitPayOrderState,
    );

    useEffect(() => {
      if (!payOrderState) {
        this.drawBarCode();
      }
    }, [payOrderState]);

    return (
      <View className='BarCode'>
        <WaitPayOrderComponent />
        <View className={payOrderState ? '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}
            />
            {payOrderState ? 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;
