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.getStoreId()}&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.getStoreId()}&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 { courseName, whetherSetSignIn, whetherSetSignOut } = data;
    const date = moment(selectedDate).format('YYYY-MM-DD');
    const unit = (data.signInTimeUnit || '').toLocaleLowerCase() + 's';
    const time = moment(`${date} ${moment(data.signInType == 'START_AGO' ? data.startTime : data.endTime).format('HH:mm')}`).subtract(data.signInTimeNum, unit);
    const signInTime = `${moment(time).format('YYYY-MM-DD HH:mm')} ~ ${moment(data.signInType == 'START_AGO' ? data.startTime : data.endTime).format('YYYY-MM-DD HH:mm')}`;
    const endUnit = (data.signOutEndTimeUnit || '').toLocaleLowerCase() + 's';
    const end = moment(`${date} ${moment(data.endTime).format('HH:mm')}`).add(data.signOutEndTimeNum, endUnit);
    let startUnit = '';
    let start = '';
    if (data.signOutType === 'START_LATER') {
      startUnit = (data.signOutStartTimeUnit || '').toLocaleLowerCase() + 's';
      start = moment(`${date} ${moment(data.startTime).format('HH:mm')}`).add(data.signOutStartTimeNum, startUnit);
    }
    const signOutTime = data.signOutType === 'START_LATER' ? `${moment(start).format('YYYY-MM-DD HH:mm')} ~ ${moment(end).format('YYYY-MM-DD HH:mm')}` : `${moment(data.endTime).format('YYYY-MM-DD HH:mm')} ~ ${moment(end).format('YYYY-MM-DD HH:mm')}`;
    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} key={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" key="1">
          <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">签到时间：{signInTime}</div>
        </div>}
        {whetherSetSignOut === 'YES' && <div className="image-box" key="2">
          <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">签退时间：{signOutTime}</div>
        </div>}
      </Modal>
    )
  }
}