import React from 'react';
import { Button, Modal, Select } from 'antd';
import moment from 'moment';
import html2canvas from 'html2canvas';
import { LIVE_SHARE } from "@/domains/course-domain/constants";
import QRCode from '../../../../libs/qrcode/qrcode';
import User from '@/common/js/user';
import Service from "@/common/js/service";
import './QRCodeModal.less';

const { Option } = Select;

export default class QRCodeModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedDate: '',
      data: {},
    }
  }

  componentWillReceiveProps(nextProps) {
    const { visible } = this.props;
    if (nextProps.visible && !visible) {
      this.getCourseDetail(nextProps);
    }
  }

  getQrcode = () => {
    const { selectedDate, data } = this.state;
    if (data.whetherSetSignIn === 'YES') {
      const qrcodeWrapDom = document.querySelector('#qrcodeWrap1');
      const htmlUrl = `${LIVE_SHARE}sign_in?id=${User.getCustomerStoreId() || User.getStoreId()}&userId=${User.getStoreUserId()}&calendar=${selectedDate}&courseId=${data.courseId}&from=work_weixin`;
      Service.Sales('public/businessShow/convertShortUrls', {
          urls: [htmlUrl]
      }).then((res) => {
          const { result = [] } = res;
          this.setState({
              shareUrl: result[0].shortUrl
          }, () => {
            const qrcodeNode = new QRCode({
              text: this.state.shareUrl,
              size: 170,
            })
            qrcodeWrapDom.childNodes[0] && qrcodeWrapDom.removeChild(qrcodeWrapDom.childNodes[0]);
            qrcodeWrapDom.appendChild(qrcodeNode);
          })
      })
    }
    if (data.whetherSetSignIn === 'YES') {
      const qrcodeWrapDom = document.querySelector('#qrcodeWrap2');
      const htmlUrl = `${LIVE_SHARE}sign_out?id=${User.getCustomerStoreId()||User.getStoreId()}&userId=${User.getStoreUserId()}&calendar=${selectedDate}&courseId=${data.courseId}&from=work_weixin`;
      Service.Sales('public/businessShow/convertShortUrls', {
          urls: [htmlUrl]
      }).then((res) => {
          const { result = [] } = res;
          this.setState({
              shareUrl: result[0].shortUrl
          }, () => {
            const qrcodeNode = new QRCode({
              text: this.state.shareUrl,
              size: 170,
            })
            qrcodeWrapDom.childNodes[0] && qrcodeWrapDom.removeChild(qrcodeWrapDom.childNodes[0]);
            qrcodeWrapDom.appendChild(qrcodeNode);
          })
      })
    }
  }

  getCourseDetail = (props) => {
    const { courseId } = props.data;
    Service.Hades('public/hades/getOfflineCourseDetail',{
      courseId
    }).then((res) => {
      this.setState({ selectedDate: res.result.calendarTime[0], data: res.result }, () => {
        this.getQrcode();
      })
    });
  }

  downloadQRCode = () => {
    const domList = document.querySelectorAll('.image-box');
    for (let index = 0; index < domList.length; index++) {
      const dom = domList[index];
      html2canvas(dom, {
        useCORS: true,
      }).then(canvas => {
        this.downloadImg(canvas, '二维码');
      });
    }
  }

  downloadImg = (canvas, type) => {
    const dataUrl = canvas.toDataURL('image/png');
    const fileName = `${type}.png`;
    window.downloadFile(dataUrl, fileName);
  }

  render() {
    const { visible, onCancel } = this.props;
    const { selectedDate, data = {} } = this.state;
    const { startTime, endTime, courseName, whetherSetSignIn, whetherSetSignOut } = data;
    const unit = (data.signInTimeUnit || '').toLocaleLowerCase() + 's';
    const time = moment(data.startTime).subtract(data.signInTimeNum, unit);
    const startUnit = (data.signOutStartTimeUnit || '').toLocaleLowerCase() + 's';
    const endUnit = (data.signOutEndTimeUnit || '').toLocaleLowerCase() + 's';
    const start = moment(data.startTime).add(data.signOutStartTimeNum, startUnit);
    const end = moment(data.endTime).add(data.signOutEndTimeNum, endUnit);
    return (
      <Modal
        title="考勤二维码"
        width={560}
        visible={visible}
        footer={<Button onClick={() => onCancel()}>关闭</Button>}
        onCancel={() => onCancel()}
        className="offline-qrcode-modal"
      >
        <div>
          <Select
            style={{ width: 200 }}
            placeholder="请选择"
            value={selectedDate}
            onChange={(value) => {
              this.setState({ selectedDate: value }, () => {
                this.getQrcode(this.props);
              })
            }}
          >
            {(data.calendarTime || []).map(item => (
              <Option value={item}>{moment(item).format('MM月DD日')}</Option>
            ))}
          </Select>
          <Button
            type="primary"
            style={{ marginLeft: 8 }}
            onClick={() => {
              this.downloadQRCode();
            }}
          >下载二维码</Button>
        </div>
        {whetherSetSignIn === 'YES' && <div className="image-box">
          <img src="https://image.xiaomaiketang.com/xm/xYSpX2y6ri.png" className="image" />
          <div className="title">签到二维码</div>
          <div className="name">{courseName}</div>
          <div className="qrcodeWrap" id="qrcodeWrap1"></div>
          <div className="time">签到时间：{moment(selectedDate).format('YYYY-MM-DD')} {moment(time).format('HH:mm')} ~ {moment(selectedDate).format('YYYY-MM-DD')} {moment(data.endTime).format('HH:mm')}</div>
        </div>}
        {whetherSetSignOut === 'YES' && <div className="image-box">
          <img src="https://image.xiaomaiketang.com/xm/xYSpX2y6ri.png" className="image" />
          <div className="title">签退二维码</div>
          <div className="name">{courseName}</div>
          <div className="qrcodeWrap" id="qrcodeWrap2"></div>
          <div className="time">签退时间：{moment(selectedDate).format('YYYY-MM-DD')} {moment(start).format('HH:mm')} ~ {moment(selectedDate).format('YYYY-MM-DD')} {moment(end).format('HH:mm')}</div>
        </div>}
      </Modal>
    )
  }
}