import React, { useState, useEffect, Fragment } from 'react';
import styles from './index.less';
import { Button, WingBlank, WhiteSpace, Toast } from 'antd-mobile';
import importAll from './importAll';
import { Modal } from 'antd';
import { queryFileUrl } from '@/webPublic/one_stop_public/utils/queryConfig';
import { uploadFile } from '@/webPublic/one_stop_public/libs/PictureSignature/ShowItem';
let pc = null;

const dataURLtoFile = (dataurl, filename) => {
  //将base64转换为文件
  let arr = dataurl.split(',');
  let mime = arr[0].match(/:(.*?);/)[1];

  let bstr = atob(arr[1]);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
};

export default function Index({ value, otherProps, json, triggerChange }) {
  const [imgData, setData] = useState(null);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    if (!window.PhotoClip) {
      importAll();
    }

    // 加载的图片必须要与本程序同源，否则无法截图
    // pc.load('img/mm.jpg');
  }, []);

  function uploadImg() {
    if (!imgData) {
      Toast.info('请先上传图片,并拖动截取', 2);
      return false;
    }
    let file = dataURLtoFile(imgData, '1.jpg'); // 将base64 图片转换成 file
    console.log(file);
    Toast.loading('正在上传', 2);
    uploadFile(file).then((y) => {
      if(y && typeof y === 'string' && y.length > 10){
        triggerChange(y);
        closeModal();
      }
    });
  }

  useEffect(() => {
    if (visible) {
      if (window.PhotoClip && !pc) {
        pc = new window.PhotoClip('#clipArea', {
          size: [200, 280],
          outputSize: [200, 280],
          //adaptive: ['60%', '80%'],
          file: '#file',
          view: '#view',
          ok: '#clipBtn',
          //img: 'img/mm.jpg',
          loadStart: function() {
            console.log('开始读取照片');
          },
          loadComplete: function() {
            console.log('照片读取完成');
          },
          done: function(dataURL) {
            setData(dataURL);
          },
          fail: function(msg) {
            alert(msg);
          },
        });
      }
    }
  }, [visible]);

  function handleAClick() {
    // setData(null);
    setVisible(true);
    // pc && pc.destroy();
    // pc = null;
  }

  function closeModal() {
    setVisible(false);
  }

  return (
    <Fragment>
      <a className={styles.handle} onClick={handleAClick}>
        {!!value ? <img src={queryFileUrl(value)} /> : '点击上传'}
      </a>
      {
        <Modal
          visible={visible}
          width={'95vw'}
          forceRender={true}
          onCancel={() => {
            closeModal();
          }}
          style={{ top: 20 }}
          destroyOnClose={false}
          footer={null}
          bodyStyle={{
            minHeight: '60vh',
            maxHeight: '90vh',
            overflowY: 'auto',
          }}
        >
          <div className={styles.photo}>
            <div id='clipArea' style={{ height: '300px' }} />

            <div className={styles.photo2}>
              <label htmlFor='file' className={styles.labelDom}>
                <input
                  type='button'
                  id='btn'
                  value='点我上传'
                  className={styles.btn}
                />
                <span id='text' className={styles.text}>
                  {otherProps.limitMessage || ''}
                </span>
                <input
                  type='file'
                  id='file'
                  className={styles.file}
                  accept={'image/*'}
                />
              </label>
              <Button
                type='primary'
                inline
                size='small'
                id='clipBtn'
                style={{ marginLeft: '20px' }}
              >
                截取
              </Button>
            </div>
            <div
              id='view'
              style={{
                margin: '0 auto',
                width: '200px',
                height: '280px',
                backgroundColor: '#666',
              }}
            />
            <WingBlank style={{ marginTop: '20px',  }}>
              <Button type='primary' onClick={uploadImg}>
                保存
              </Button>
              <WhiteSpace />
            </WingBlank>
            <WingBlank style={{ marginBottom: '20px' }}>
              <Button type='warning' onClick={closeModal}>
                关闭
              </Button>
              <WhiteSpace />
            </WingBlank>
          </div>
        </Modal>
      }
    </Fragment>
  );
}
