import './WaterDispenser.scss';
import Taro, { Component } from '@tarojs/taro';
import { View, Image, Text } from '@tarojs/components';
import ScanIcon from '../../images/shower/ic_saoma@2x.png';
import StartIcon from '../../images/water/start@2x.png';
import CantStartIcon from '../../images/water/nostart@2x.png';
import CodeIcon from '../../images/water/code@2x.png';

import DeviceInfo from '@/components/DeviceInfo/DeviceInfo';
import EquipmentItem from './components/EquipmentItem/EquipmentItem';
import {
  getUsedEquipment,
  getUsingEquipment,
  waterBeginning,
  fetchWaterEquipmentInfo,
  DeviceInfoResponse,
  fetchPageConfig,
  PageConfigResponse,
} from '@/api/waterDispenser';
import { Customer } from '@/types/Customer/Customer';
import { connect, useSelector } from '@tarojs/redux';
import { ComponentClass } from 'react';
import { ResponseDataEntity } from '@/api';
import { CustomerBeanAccountVo, PaymentAndActiveInfo } from '@/api/baseClass';
import Order from '@/types/Order/Order';
import { fetchOrderDetailAndPay, fetchPayOrder } from '@/api/order';
import WaitPayOrderComponent from '@/components/WaitPayOrder/WaitPayOrder';
import { PayOrderState } from '@/store/rootReducers/orderState';

export type DeviceInfo = {
  code: string;
  position: string;
};
type PageStateProps = {
  userinfo: Customer;
};

type PageState = {
  deviceInfo: DeviceInfo;
  waterUsingState: boolean;
  useList: DeviceInfo[];
  timer: number | null;
  showToggleTag: boolean;
};

type IProps = PageStateProps;

interface WaterDispenser {
  props: IProps;
  state: PageState;
}

@connect(({ userinfo }) => ({
  userinfo,
}))
class WaterDispenser extends Component {
  constructor(props: IProps) {
    super(props);
    this.state = {
      waterUsingState: false,
      deviceInfo: {
        code: '',
        position: '',
      },
      useList: [],
      timer: null,
      showToggleTag: false,
    };
  }

  componentWillMount() {
    this.getUsedEquipment();
    this.fetchPageConfig();
  }

  componentWillUnmount() {
    this.clearTimer();
  }

  fetchPageConfig() {
    const { userinfo } = this.props;
    fetchPageConfig({
      campusId: userinfo.areaId,
    })
      .then((res: ResponseDataEntity<PageConfigResponse>) => {
        console.log(res);
        const data = res.data;
        if (data.mode === 3) {
          if (data.defualtMode === 1) {
            this.toggleCodeState();
          } else {
            this.setState({
              showToggleTag: true,
            });
          }
        } else if (data.mode === 2) {
          this.setState({
            showToggleTag: false,
          });
        } else if (data.mode === 1) {
          Taro.redirectTo({
            url: '/pages/BarCode/BarCode',
          });
        }
      })
      .catch(err => {
        console.error(err);
      });
  }
  clearTimer() {
    const { timer } = this.state;
    if (timer) {
      clearTimeout(timer);
      this.setState({
        timer: null,
      });
    }
  }

  toggleCodeState() {
    Taro.redirectTo({
      url: `/pages/BarCode/BarCode?serviceId=9&backPage=${encodeURIComponent(
        '/pages/WaterDispenser/WaterDispenser',
      )}`,
    });
  }

  scanEquipment() {
    return Taro.scanCode({
      onlyFromCamera: true,
      scanType: ['qrCode'],
    })
      .then(res => {
        console.log(res);
        const { result } = res;
        const { userinfo } = this.props;

        return fetchWaterEquipmentInfo({
          deviceCode: result,
          customerId: userinfo.customerId.toString(),
          campusId: userinfo.areaId,
        })
          .then((res: ResponseDataEntity<DeviceInfoResponse>) => {
            console.log(res);

            const data = res.data;
            this.setState({
              deviceInfo: data,
            });
          })
          .catch(err => {
            console.error(err);
            Taro.showToast({
              title: err.msg || '请扫描正确的设备码',
              icon: 'none',
            });
          });
      })
      .catch(err => {
        console.error(err);
        // Taro.showToast({
        //   title: err.msg || '呼起扫码失败！',
        //   icon: 'none',
        // });
      });
  }

  getUsedEquipment() {
    const { userinfo } = this.props;
    getUsedEquipment({
      customerId: userinfo.customerId.toString(),
      campusId: userinfo.areaId,
    })
      .then(res => {
        console.log(res);
        this.setState({
          useList: res.data,
        });
      })
      .catch(err => {
        console.error(err);
      });
  }

  getUsingEquipment() {
    const { userinfo } = this.props;
    getUsingEquipment({
      customerId: userinfo.customerId.toString(),
    })
      .then(res => {
        console.log(res);
        if (res.data) {
        } else {
          this.setState({
            waterUsingState: false,
          });
        }
      })
      .catch(err => {
        console.error(err);
      });
  }

  getSelectedEquipment = (data: DeviceInfo) => {
    this.setState({
      deviceInfo: data,
    });
  };

  waterBeginning() {
    Taro.showLoading();
    const { deviceInfo } = this.state;
    const { userinfo } = this.props;
    waterBeginning({
      deviceCode: deviceInfo.code,
      customerId: userinfo.customerId,
      customerName: userinfo.customerName,
      customerPhone: userinfo.customerPhone,
      campusId: userinfo.areaId,
    })
      .then(res => {
        console.log(res);
        Taro.hideLoading();
        this.setState(
          {
            waterUsingState: true,
          },
          () => {
            this.startCheckusing();
          },
        );
      })
      .catch(err => {
        console.error('开启失败： ', err);
      });
  }

  startCheckusing() {
    const { waterUsingState } = this.state;
    if (waterUsingState) {
      this.getUsingEquipment();
      let timer = setTimeout(() => {
        this.startCheckusing();
      }, 5000);
      this.setState({
        timer,
      });
    } else {
      this.clearTimer();
    }
  }

  render() {
    const {
      waterUsingState,
      deviceInfo: { code, position },
      useList,
      showToggleTag,
    } = this.state;
    const payOrderState = useSelector(
      (state: { orderState: PayOrderState }) =>
        state.orderState.waitPayOrderState,
    );

    return (
      <View className='WaterDispenser'>
        <WaitPayOrderComponent />
        <View className={payOrderState ? 'blur' : ''}>
          {showToggleTag && (
            <View className='WaterDispenser-tg' onClick={this.toggleCodeState}>
              <Image className='icon' src={CodeIcon} />
              <Text className='text'>显示条码</Text>
            </View>
          )}
          <DeviceInfo size='small' code={code} position={position} />

          <View className='btn-box'>
            <Image
              className='shower-scan-btn'
              src={ScanIcon}
              onClick={this.scanEquipment}
            />
            {code && !waterUsingState ? (
              <Image
                className='shower-start-btn'
                src={StartIcon}
                onClick={this.waterBeginning}
              />
            ) : (
              <Image className='shower-start-btn' src={CantStartIcon} />
            )}
          </View>

          <View className='LastUseList'>
            <View className='LastUseList-title bb'>最近使用</View>
            {useList.map(device => (
              <EquipmentItem
                key={device.code}
                ex-class='bb'
                code={device.code}
                position={device.position}
                onClick={this.getSelectedEquipment}
              />
            ))}
          </View>
        </View>
      </View>
    );
  }
}

export default WaterDispenser as ComponentClass<IProps, PageState>;
