import {Component} from "react";
import {Canvas, View} from "@tarojs/components";
import UQRCode from "uqrcodejs";
import Taro from "@tarojs/taro";
import TaroUtils from "../../utils/TaroUtils";

class XQRCode extends Component {

  constructor(props) {
    super(props);
  }

  static defaultProps = {
    size: "200rpx",
    content: "https://www.baidu.com",
    id: "QRCode"
  }

  componentDidMount() {

    const { content, id } = this.props;

    Taro.createSelectorQuery()
      .select(`#${id}`)
      .boundingClientRect()
      .exec(res => {
        const { width } = res[0];
        const qr = new UQRCode();
        qr.data = content;
        qr.size = width;
        qr.make();
        qr.canvasContext = Taro.createCanvasContext(id, this);
        qr.drawCanvas().catch(res => {
          TaroUtils.showToast(`二维码绘制失败`);
        })
      });
  }

  render() {

    const { size, id } = this.props;

    return (
      <View style={{
        width: size,
        height: size,
      }}>
        <Canvas
          id={id}
          canvasId={id}
          className='!w-full !h-full'>
        </Canvas>
      </View>
    );
  }
}

export default XQRCode;
