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.whetherSetSignOut === '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 = qrcodeWrapDom1 && new QRCode({
        text: result[0].shortUrl,
        size: 170,
      });
      const qrcodeNode2 = qrcodeWrapDom2 && new QRCode({
        text: result[data.whetherSetSignIn === 'YES' ? 1 : 0].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);
      setTimeout(() => {
        this.initQRCode();
      }, 300)
    })
  }

  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, selectedDate, data } = this.state;
    let fileName1 = `签到二维码_${data.courseName}_${moment(selectedDate).format('YYYY-MM-DD')}.png`;
    let fileName2 = `签退二维码_${data.courseName}_${moment(selectedDate).format('YYYY-MM-DD')}.png`;
    imgUrl1 && setTimeout(() => window.downloadFile(imgUrl1, fileName1), 0);
    imgUrl2 && setTimeout(() => window.downloadFile(imgUrl2, fileName2), 0);
  }

  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')}`);
    const signInTime = `${moment(time).subtract(data.signInTimeNum, unit).format('YYYY-MM-DD HH:mm')} ~ ${moment(time).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(`${date} ${moment(data.endTime).format('HH:mm')}`).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/Q42ZRrQDkJ.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/Q42ZRrQDkJ.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>
    )
  }
}