/**
 * 徐立
 * 2019年12月6日
 * 电子签章多功能封装
 */
import React, { Component } from 'react';
import SignatureCanvas from 'react-signature-canvas';
import { message, Button, Modal } from 'antd';
import config from '@/webPublic/one_stop_public/config';
import reqwest from 'reqwest';
import { getToken, getUserInfo } from '@/webPublic/one_stop_public/utils/token';
import { uaaRequest } from '@/webPublic/one_stop_public/utils/request';
import { getOneStopMyInfo } from '@/webPublic/one_stop_public/utils/utils';
import styles from './mobileSign.less';

// 保存签名 到用户基础信息上
function saveSign(url) {
  if (typeof url !== 'string' || url.length < 15) {
    return true;
  }
  const userInfo = getUserInfo();
  uaaRequest('/UserApi/saveMySysBackgroundImage', {
    username: userInfo.stuNo,
    backgroundImageUrl: userInfo.backgroundImageUrl,
    isUseBackImage: userInfo.isUseBackImage,
    userSign: url,
  })
    .then((g) => {
      getOneStopMyInfo();
      return true;
    });
}

function dataURLtoBlob(toDataURL) {
  var arr = toDataURL.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

function blobToFile(Blob, fileName) {
  Blob.lastModifiedDate = new Date();
  Blob.name = fileName;
  return Blob;
}

export default class Index extends Component {
  constructor(props) {
    super(props);
    const value = props.value;
    this.state = {
      url: value || getUserInfo().userSign,
      showModal: false,
    };
  }

  triggerChange = (changedValue) => {
    // Should provide an event to pass value to Form.
    const onChange = this.props.onChange;
    if (onChange) {
      onChange(changedValue);
    }
  };

  componentWillReceiveProps(nextProps) {
    // Should be a controlled component.
    if ('value' in nextProps) {
      const value = nextProps.value;

      this.setState({ url: value });

      //
    }
  }

  sigCanvas = {
    clear: () => {
    },
    toDataURL: (param) => {
      return '';
    },
  };

  clear = () => {
    this.sigCanvas.clear();
  };
  delete = () => {
    if (!('value' in this.props)) {
      this.setState({ url: null });
    }
    this.triggerChange(null);
  };
  trim = () => {
    const formData = new FormData();
    const xx = dataURLtoBlob(this.sigCanvas.toDataURL('image/png'));
    const file = blobToFile(xx, 'sign.png');
    if (file == null) {
      return;
    }
    formData.append('file', file, 'sign.png');
    formData.append('token', getToken());
    reqwest({
      url: config.uploadUrl,
      method: 'post',
      processData: false,
      data: formData,
      success: (url) => {
        /**
         * 这里的成功 是走的下面的 error
         * */
        // console.log('22334455');
        // if (!('value' in this.props)) {
        //   this.setState({ url: url });
        // }
        // console.log(url);

        // this.triggerChange(url);
        //
        message.success('保存成功');
      },
      error: (e) => {
        if (e.status === 200) {
          const urlP = e.response;
          saveSign(urlP);
          message.success('保存成功');
          if (!('value' in this.props)) {
            this.setState({ url: e.response });
          }
          this.triggerChange(e.response);
        } else {
          message.error('保存失败');
        }
      },
    });
  };

  componentDidMount() {
    if (!this.props.value && this.state.value) {
      this.triggerChange(this.state.value);
    }
  }

  changeShowModal = () => {
    this.setState({
      showModal: !this.state.showModal,
    });
  };

  // 移动端签名组件
  MobileSign = () => {
    const { url } = this.state;
    if (url) {
      return <div className={styles.mobileSign}>

      </div>;
    } else {
      return <div className={styles.mobileSign2}>
        <Button type={'primary'} onClick={this.changeShowModal}>
          点击开始签名
        </Button>
      </div>;
    }
    return null;
  };

  MobileModal = () => {
    const { showModal } = this.state;
    const height = 300;
    const width = window.screen.width - 50;
    return (
      showModal && <Modal className={styles.mobileModal}
                          width={'100vw'}
                          onCancel={this.changeShowModal}
                          visible={true}
                          title={'签名'}
                          bodyStyle={{minHeight: '350px'}}
      >
      <div className={styles.borderDiv}>
        <SignatureCanvas
          penColor='black'
          ref={(ref) => {
            this.sigCanvas = ref;
          }}
          canvasProps={{
            width: width + 'px',
            height: height + 'px',
            className: 'sigCanvas',
          }}
        />
      </div>
      </Modal>);
  };

  render() {
    // console.log('签名组件');
    const {
      width,
      height,
      get,

    } = this.props;
    const { url } = this.state;

    if (get === 'mobile') {
      const MobileSign = this.MobileSign;
      const MobileModal = this.MobileModal;
      return <>
        <MobileSign />
        <MobileModal />
      </>;
    }

    return (
      <div id='canvas_signature' style={{
        width: '100%',
        height: '100%',
        marginLeft: 5,
      }}>
        <div
          style={{
            width: width,
            textAlign: 'center',
            height: height,
            border: '1px  dashed gray',
            position: 'relative',
          }}>
          {url ? (
            <img src={config.httpServer + url} style={{
              width: width,
              height: height - 20,
            }} />
          ) : (
            <SignatureCanvas
              penColor='black'
              ref={(ref) => {
                this.sigCanvas = ref;
              }}
              canvasProps={{
                width: width || 400,
                height: height ? height - 20 : 200,
                className: 'sigCanvas',
              }}
            />
          )}
          <div style={{
            position: 'absolute',
            left: 5,
            bottom: 5,
          }}>
            {url ? (
              <Button type='danger' size='small' onClick={this.delete}>
                重写
              </Button>
            ) : (
              <>
                <Button style={{ marginLeft: 12 }} type='danger' size='small' onClick={this.clear}>
                  清除
                </Button>
                <Button style={{ marginLeft: 12 }} onClick={this.trim} size='small' type='primary'>
                  保存
                </Button>
              </>
            )}
          </div>
        </div>
      </div>
    );
  }
}
