import React from 'react';
import { Upload, message, Badge, Icon, Modal } from 'antd';
import config from '@/webPublic/one_stop_public/config';
import { zipImage } from '@/webPublic/zyd_public/utils/handlePhoto';
import { getToken } from '@/webPublic/one_stop_public/utils/token';
import { queryFileUrl } from '@/webPublic/one_stop_public/utils/queryConfig';
import {
  getSassApiHeader,
  getSysCode,
} from '@/webPublic/one_stop_public/2023yunshangguizhou/utils';
import PhotoClip from './Split/PhotoClip/index';

/**
 * otherProps: {
 *   limitMessage: '请上传xx格式图片图片', // 图片格式限制提示语句
 *   photoClip: true, // 是否开启图片裁剪功能. 开启后需要引入对应的依赖js
 *   accept: 'image/png, image/jpeg', // 图片格式限制
 *   limitFileType: ['jpg', 'jpeg', 'png'], // 图片格式限制(上传时)
 *   limitWidth: 1024, // 图片宽度限制 如果设置了 上传的图片必须和此宽度限制一致
 *   limitHeight: 768, // 图片高度限制 如果设置了 上传的图片必须和此高度限制一致
 * }
 * */

export default class ImgUploadCom extends React.Component {
  constructor(props) {
    super(props);
    const value = props.value;
    this.state = {
      url: value,
    };
  }

  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 });
    }
  }

  changeUrl = (info, key) => {
    if (info.file.status === 'done') {
      message.success(`图片上传成功`);

      if (!('value' in this.props)) {
        this.setState({ url: info.file.response });
      }
      this.triggerChange(info.file.response);
    } else if (info.file.status === 'error') {
      message.error(`图片上传失败`);
    }
  };
  changePos = (obj) => {
    if (!('value' in this.props)) {
      this.setState({ ...obj });
    }
    this.triggerChange({ ...obj });
  };

  removePicture = (e) => {
    if (e && e.stopPropagation) {
      e.stopPropagation();
      e.preventDefault();
    }
    this.triggerChange('');
  };

  getImageWidthAndHeight = (file) => { // 解决禅道任务 2006 评奖评优管理头像上传限制优化
    return new Promise((resolve, reject) => {
      let _URL = window.URL || window.webkitURL;
      let image = new Image();
      image.src = _URL.createObjectURL(file);
      image.onload = function() {
        resolve({
          width: image.width,
          height: image.height,
        });
      };
    });
  };

  giveMessage = () => {
    const { otherProps = {} } = this.props;
    Modal.warning({
      title: '图片限制',
      content: otherProps.limitMessage || '图片格式错误!',
      okText: '确定',
    });
  };


  render() {
    const { json, disabled, otherProps, value } = this.props;
    const { url } = this.state;
    console.log('🚀 ~ file:ImgUploadCom method:render line:103 -----', otherProps, '');
    if(!disabled && otherProps.photoClip){
      return (
        <PhotoClip json={json}
                   value={value}
                   triggerChange={this.triggerChange}
                   otherProps={otherProps}
        />
      );
    }
    return (
      <>
      <Upload.Dragger
        disabled={disabled}
        accept={otherProps.accept || 'image/*'}
        url={url}
        headers={getSassApiHeader()}
        data={{
          token: getToken(),
        }}
        beforeUpload={(file) => {
          if (otherProps) {
            if (otherProps.limitFileType && Array.isArray(otherProps.limitFileType)) { // 限制文件类型
              let fileType = file.name.split('.').pop();
              if (!otherProps.limitFileType.includes(fileType)) {
                this.giveMessage();
                return false;
              }
            }
            if (otherProps.limitWidth || otherProps.limitHeight) { //限制上传图片的宽高. 解决禅道任务 2006
              return new Promise((resolve, reject) => {
                this.getImageWidthAndHeight(file).then((res) => {
                  if (otherProps.limitWidth && res.width !== otherProps.limitWidth) {
                    this.giveMessage();
                    reject(false);
                    return false;
                  }
                  if (otherProps.limitHeight && res.height !== otherProps.limitHeight) {
                    this.giveMessage();
                    reject(false);
                    return false;
                  }
                  return resolve(zipImage(file, 4));
                });
              });
            }
          }


          return zipImage(file, 4);
          // 图片压缩函数. 超过fileSizeLimitMb兆的图片 直接压缩成原来的 30%  如果后续有其他需求考虑 做成全局配置项 配置可以压缩的图片的范围
          // 禅道bug 23185
        }}
        showUploadList={false}
        name='file'
        action={config.uploadUrl}
        onChange={this.changeUrl}
        multiple={false}
        style={{ padding: 0 }}>
        {url ? (
          disabled ? <img
              src={queryFileUrl(url)}
              style={{
                height: json.height,
                width: json.width,
                maxWidth: '60vw', // 解决图片在移动端过宽的bug
              }}
            /> :
            <Badge
              count={
                <Icon type='close-circle' style={{ color: 'red' }} onClick={this.removePicture} />
              }>
              <img
                src={queryFileUrl(url)}
                style={{
                  height: json.height,
                  width: json.width,
                  maxWidth: '60vw', // 解决图片在移动端过宽的bug
                }}
              />
            </Badge>
        ) : (
          <div
            style={{
              // height: json.height,
              // width: json.width,
              display: 'grid',
              placeItems: 'center',
            }}
          >{disabled ? '' : '点击上传'}</div>
        )}
      </Upload.Dragger>

      </>
    );
  }
}
