/*
 * @Author: sunbingqing
 * @Date: 2019-07-26 14:04:00
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2020-11-28 11:40:44
 */

import React, { useState, useEffect } from 'react';
import { Modal, Row, Col, Button } from 'antd';
import _ from 'underscore';
import $  from 'jquery';
import '@/libs/cropper/cropper.min.css';
import 'cropper';
import Upload from '../core/upload';
import './CropperModal.less';
const baseImg ='https://image.xiaomaiketang.com/xm/rJeQaZxtc7.png'

interface CropperModalProps {
  title?: string;
  imgUrl?: any;
  close: () => void;
  save: (value: any) => void;
  type?: string;
  visible?:boolean
}

const CropperModal = (props: CropperModalProps) => {
  const { title, close, save } = props;

  const [imgUrl, setImgUrl] = useState(props.imgUrl ? `${props.imgUrl}` : baseImg);
  const [clickStatus,setClickStatus] = useState(false);
  useEffect(() => {
    imgUrl && initCropper();
  }, [imgUrl]);

  function initCropper(): any {
    $(() => {
      const $image = $('#image');
      const $previews = $('.preview-wrap .preview');
      ($image as any).cropper({
        aspectRatio: 1,
        viewMode: 1,
        ready: () => {
          const $clone = $image.clone().removeClass('cropper-hidden') as any;
          $previews.html($clone);
        },
        crop: _.throttle(function (e: any) {
          const imageData = ($image as any).cropper('getImageData');
          $previews.each(function () {
            const $preview = $(this);
            const previewWidth:any= $preview.width();
            const imageScaledRatio = e.width / previewWidth;
            $preview.find('img').css({
              width: imageData.naturalWidth / imageScaledRatio,
              height: imageData.naturalHeight / imageScaledRatio,
              marginLeft: -e.x / imageScaledRatio,
              marginTop: -e.y / imageScaledRatio,
            });
          });
        }, 200),
      });
    });
  }
  

  function _handleSave(): any {
    if (clickStatus) {
      return;
    }
    setClickStatus(true);
    setTimeout(() => {
      setClickStatus(false);
    }, 4000);
    const $image = $('#image');
    ($image as any).cropper('getCroppedCanvas').toBlob((blob: any) => {
      console.log("blob",blob);
      Upload.uploadBlobToOSS(blob, 'avatar' + (new Date()).valueOf()).then((imgAddress:string) => {
        save(imgAddress);
        close();
      });
    });
  }

  function _handleUpdateAvatar(e: any): any {
    const avatar = e.target.files[0];
    const newUrl = URL.createObjectURL(avatar);
    const $image = $('#image');
    setImgUrl(newUrl);
    ($image as any).cropper('destroy').attr('src', newUrl);
    initCropper();
  }

  function _onUpload(): any {
    $('#CrpperAvatarPic').trigger('click');
  }

  return (
    <Modal
      className={`cropper-image-modal new-cropper-${props.type}`}
      width={600}
      title={title || '设置头像'}
      visible={true}
      maskClosable={false}
      footer={[
        <Button
          id='cancel_avatar_btn'
          key="back" onClick={close}>取消</Button>,
        <Button
          id='save_avatar_btn'
          key="submit" type="primary" onClick={_handleSave}>
          确定
          </Button>,
      ]}
      onCancel={close}>
      <Row>
        <Col span={14}>
          <div className="container">
            <div className="img-placeholder">
              {
                imgUrl &&
               <img  id="image"
                  className="img-source"
                  src={imgUrl}
                  alt="Picture" />
              }
            </div>
            {/* <Button id="click_upload_btn" onClick={_onUpload}>点击上传</Button>
            <input
              type="file"
              accept="image/*"
              id="CrpperAvatarPic"
              style={{ display: 'none' }}
              onChange={_handleUpdateAvatar} /> */}
          </div>
        </Col>

        {
          imgUrl &&
          <Col span={10} className="preview-wrap">
            <h2>预览</h2>
            <div className="preview preview-1"></div>
          </Col>
        }
      </Row>
    </Modal>
  );
};

export default CropperModal;
