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 ScanFileModal from '../../../resource-disk/modal/ScanFileModal';
import './QRCodeModal.less';

const { Option } = Select;

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

  componentDidUpdate(preProps) {
    const { visible } = this.props;
    if (!preProps.visible && visible) {
      this.getCourseDetail();
    }
  }

  getQrcode = () => {
    const { selectedDate, data } = this.state;
    let list = [];
    const qrcodeWrapDom1 = document.querySelector('#qrcodeWrap1');
      const qrcodeWrapDom2 = document.querySelector('#qrcodeWrap2');
      if (data.whetherSetSignIn === 'YES') {
      const htmlUrl = `${LIVE_SHARE}sign_in?id=${User.getStoreId()}&calendar=${selectedDate}&courseId=${data.courseId}&from=work_weixin`;
      list.push(htmlUrl);
    }
    if (data.whetherSetSignIn === 'YES') {
      const htmlUrl = `${LIVE_SHARE}sign_out?id=${User.getStoreId()}&calendar=${selectedDate}&courseId=${data.courseId}&from=work_weixin`;
      list.push(htmlUrl);
    }
    Service.Sales('public/businessShow/convertShortUrls', {
        urls: list
    }).then((res) => {
      const { result = [] } = res;
      const qrcodeNode1 = new QRCode({
        text: result[0].shortUrl,
        size: 170,
      });
      const qrcodeNode2 = result[1] && new QRCode({
        text: result[1].shortUrl,
        size: 170,
      });
      qrcodeWrapDom1 && qrcodeWrapDom1.childNodes[0] && qrcodeWrapDom1.removeChild(qrcodeWrapDom1.childNodes[0]);
      qrcodeWrapDom1 && qrcodeWrapDom1.appendChild(qrcodeNode1);
      qrcodeWrapDom2 && qrcodeWrapDom2.childNodes[0] && qrcodeWrapDom2.removeChild(qrcodeWrapDom2.childNodes[0]);
      qrcodeWrapDom2 && qrcodeWrapDom2.appendChild(qrcodeNode2);
      this.initQRCode();
    })
  }

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

  initQRCode = () => {
    const domList = document.querySelectorAll('.image-box');
    for (let index = 0; index < domList.length; index++) {
      const dom = domList[index];
      html2canvas(dom, {
        useCORS: true,
      }).then(canvas => {
        const dataUrl = canvas.toDataURL('image/png');
        this.setState({ [`imgUrl${index + 1}`]: dataUrl });
      });
    }
  }

  downloadImg = () => {
    const { imgUrl1, imgUrl2 } = this.state;
    const fileName = '二维码.png';
    imgUrl1 && window.downloadFile(imgUrl1, fileName);
    imgUrl2 && window.downloadFile(imgUrl2, fileName);
  }

  render() {
    const { visible, onCancel } = this.props;
    const { selectedDate, data = {}, imgUrl1, imgUrl2, imgUrl, showPreviewModal } = 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.downloadImg();
            }}
          >下载二维码</Button>
        </div>
        {whetherSetSignIn === 'YES' && <div
          className="image-box"
          key="1"
          onClick={() => this.setState({ showPreviewModal: true, imgUrl: imgUrl1 })}
        >
          <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"
          onClick={() => this.setState({ showPreviewModal: true, imgUrl: imgUrl2 })}
        >
          <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>}
        {showPreviewModal &&
          <ScanFileModal
            fileType="JPG"
            item={{ ossUrl: imgUrl }}
            close={() => this.setState({ showPreviewModal: false })}
          />
        }
      </Modal>
    )
  }
}