/**
 * 徐立
 * 2019年12月6日
 * 电子签章多功能封装
 * 2022年8月17日
 * 从个人基本信息中拿默认签名.
 */
import React, { Component } from 'react';
import SignatureCanvas from 'react-signature-canvas';
import { message, Button, Modal, Icon } 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 styles from './styles.less';
import { saveSign, dataURLtoBlob, blobToFile } from './Split';
import {queryFileUrl} from "@/webPublic/one_stop_public/utils/queryConfig";

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

	triggerChange = (changedValue) => {
		const onChange = this.props.onChange;
		if (onChange) {
			onChange(changedValue);
		}
	};

	componentWillReceiveProps(nextProps) {
		// Should be a controlled component.
		if ('value' in nextProps && nextProps.value) {
			const value = nextProps.value;
			if (value !== this.state.url) {
				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 = () => {
		message.info('正在保存签名，请等待');
		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
				 * */
				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.changeShowModal();
					this.triggerChange(e.response);
				} else {
					message.error('保存失败');
				}
			},
		});
	};

	componentDidMount() {
		if (!this.props.value && this.state.url) {
			setTimeout(() => {
				this.triggerChange(this.state.url);
			}, 2000);
		}
	}

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

  showSignImage = () => {
    const { url } = this.state;
    Modal.info({
      okText: '确定',
      cancelText: '取消',
      title: '查看签名',
      content: <div className={styles.showDiv}>
        <img src={queryFileUrl(url)}/>
      </div>,
      footer: null,
    });
  };

  EditIcon = () => {
    return <Icon type="edit" onClick={this.changeShowModal} className={styles.editIcon}/>
  }

	// 移动端签名组件
	MobileSign = () => {
		const { url } = this.state;
		const EditIcon = this.EditIcon;
		if (url) {
			return (
				<div className={styles.mobileSign}>
          <EditIcon />
       {/*   <Button
						type={'primary'}
						onClick={this.changeShowModal}
						className={styles.reSign}>
						重新签名
					</Button>*/}
					<img src={queryFileUrl(url)} className={styles.littleSign} onClick={this.showSignImage}/>
				</div>
			);
		} else {
			return (
				<div className={styles.mobileSign2}>
          <EditIcon />
					{/*<Button type={'primary'} onClick={this.changeShowModal}>
						点击开始签名
					</Button>*/}
				</div>
			);
		}
	};

	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}
					onOk={this.trim}
					title={'签名'}
					bodyStyle={{
						minHeight: '350px',
						padding: '24px 12px',
					}}>
					<div className={styles.borderDiv}>
						<SignatureCanvas
							penColor="black"
							ref={(ref) => {
								this.sigCanvas = ref;
							}}
							canvasProps={{
								width: width + 'px',
								height: height + 'px',
								className: 'sigCanvas',
							}}
						/>
					</div>
				</Modal>
			)
		);
	};

	WebModal = () => {
		const { showModal } = this.state;
		const height = 300;
		const width = 600;
		return (
			showModal && (
				<Modal
					className={styles.mobileModal}
					width={700}
					onCancel={this.changeShowModal}
					visible={true}
					onOk={this.trim}
					title={'签名'}
					bodyStyle={{
						minHeight: '350px',
						padding: '24px 12px',
					}}>
					<div className={styles.borderDiv}>
						<SignatureCanvas
							penColor="black"
							ref={(ref) => {
								this.sigCanvas = ref;
							}}
							canvasProps={{
								width: width + 'px',
								height: height + 'px',
								className: 'sigCanvas',
							}}
						/>
					</div>
				</Modal>
			)
		);
	};

	WebSign = () => {
		const { width, height } = this.props;
		const EditIcon = this.EditIcon;
		const { url } = this.state;
		if (url) {
			return (
				<div className={styles.webSign}>
          <EditIcon />
					<img
            onClick={this.showSignImage}
						src={queryFileUrl(url)}
						style={{
							height,
							width,
						}}
					/>
				</div>
			);
		} else {
			return (
				<div className={styles.mobileSign2}>
          <EditIcon />
				</div>
			);
		}
		return null;
	};

	render() {
	  // return null;
		// 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 />
				</>
			);
		} else {
      const WebSign = this.WebSign;
      const WebModal = this.WebModal;
			return (
				<>
					<WebSign />
					<WebModal />
				</>
			);
		}
	}
}
