import { ComponentClass } from 'react';
import Taro, { Component } from '@tarojs/taro';
import { View, Input, Canvas } from '@tarojs/components';
import { getVcode, getImageVcode } from '../../api/vcode';
import Modal from '../Modal/Modal';
import './Vcode.scss';
import { ResponseDataEntity } from 'src/api';
import { ResendTime } from '@/constants';

type PageOwnProps = {
  positionNum: string;
  text?: string;
  cellphone: string;
};
type PageState = {
  defaultText: string;
  counting: boolean;
  count: number;
  timer: number | null;
  showImgBox: boolean;
  vcode: number | null;
  inputCode: string;
};

interface Vcode {
  props: PageOwnProps;
  state: PageState;
}

class Vcode extends Component {
  static externalClasses = ['vcode-classname'];

  constructor(props: PageOwnProps) {
    super(props);

    this.state = {
      defaultText: props.text ? props.text : '获取验证码',
      counting: false,
      count: ResendTime,
      timer: null,
      showImgBox: false,
      vcode: null,
      inputCode: '',
    };
  }

  componentWillUnmount() {
    const { timer } = this.state;
    if (timer) {
      clearTimeout(timer);
    }
  }

  showImgCode() {
    const { cellphone } = this.props;
    if (cellphone && cellphone.length == 11) {
      getImageVcode({
        loginName: cellphone,
      })
        .then((res: ResponseDataEntity<number>) => {
          const { data } = res;
          this.setState({
            vcode: data,
          });
          this.drawImg(data);
        })
        .catch(console.error);
      this.setState({
        showImgBox: true,
      });
      // this.drawImg(1234);
    } else {
      Taro.showToast({
        title: '输入正确的手机号',
        icon: 'none',
        mask: true,
      });
    }
  }
  closeImageBox() {
    const ctx = Taro.createCanvasContext('Vcode', this.$scope);
    ctx.setFillStyle('#6180f4');
    ctx.fillRect(0, 0, 73, 38);
    ctx.draw();
    this.setState({
      showImgBox: false,
    });
  }

  drawImg(vcode: number) {
    const ctx = Taro.createCanvasContext('Vcode', this.$scope);
    ctx.setFillStyle('#6180f4');
    ctx.fillRect(0, 0, 73, 38);
    ctx.font = '26px arial';
    // ctx.font('normal', '500', 26, 'arial');
    ctx.setFillStyle('#fff');
    ctx.fillText(vcode.toString(), 10, 30, 146); //画布上添加验证码
    ctx.draw();
  }

  clickHandle() {
    const { vcode, inputCode } = this.state;
    if (vcode && vcode.toString() == inputCode) {
      const { cellphone, positionNum } = this.props;

      getVcode({
        cellphone: cellphone,
        businessNum: positionNum,
      })
        .then(res => {
          this.countStart();
          Taro.showToast({
            title: res.msg,
            mask: true,
          });
          this.setState({
            vcode: null,
            inputCode: '',
            showImgBox: false,
          });
        })
        .catch(console.error);
    } else {
      Taro.showToast({
        title: '请输入正确的验证码',
        icon: 'none',
      });
    }
  }

  countStart() {
    this.setState({
      counting: true,
    });
    this.countDown();
  }

  countDown() {
    const { count } = this.state;
    if (count == 1) {
      this.setState({
        counting: false,
      });
    } else {
      const timer = setTimeout(() => {
        this.countDown();
      }, 1000);
      this.setState({
        count: count - 1,
        timer: timer,
      });
    }
  }

  render() {
    const { defaultText, counting, count, showImgBox, inputCode } = this.state;
    return (
      <View>
        {counting ? (
          <View className='vcode-classname Vcode Counting'>{`${count}S后重发`}</View>
        ) : (
          <View className='vcode-classname Vcode' onClick={this.showImgCode}>
            {defaultText}
          </View>
        )}
        <Modal
          visiabled={showImgBox}
          title='请输入图形验证码'
          onCancel={this.closeImageBox}
          onSubmit={this.clickHandle}
          body-class='Vcode-Content'>
          <View className='Vcode-Content-box'>
            <Input
              className='Vcode-input'
              type='number'
              maxLength={4}
              value={inputCode}
              onInput={({ detail: { value } }) => {
                this.setState({
                  inputCode: value,
                });
                return value;
              }}
            />
            <Canvas className='Vcode-canvas' canvasId='Vcode' />
          </View>
        </Modal>
      </View>
    );
  }
}

export default Vcode as ComponentClass<PageOwnProps, PageState>;
