import _Upload from "@alifd/next/es/upload";
import _Icon from "@alifd/next/es/icon";
import _Message from "@alifd/next/es/message";
import _Box from "@alifd/next/es/box";
import _Dialog from "@alifd/next/es/dialog";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import React, { useCallback, useEffect, useState } from 'react';
import { saveImage, delImage, getFileDetail } from "../form-item/api";
// import { randomField } from './random';
import { getShortid } from "../../utils";
var CommonImage = function CommonImage(_ref) {
  var style = _ref.style,
    value = _ref.value,
    _ref$isPreview = _ref.isPreview,
    isPreview = _ref$isPreview === void 0 ? false : _ref$isPreview,
    isDisabled = _ref.isDisabled,
    defaultValue = _ref.defaultValue,
    isConvert = _ref.isConvert,
    thumbnailWidth = _ref.thumbnailWidth,
    thumbnailQuality = _ref.thumbnailQuality,
    onChange = _ref.onChange;
  var _useState = useState([]),
    fileData = _useState[0],
    setFileData = _useState[1];
  var _useState2 = useState(''),
    fileId = _useState2[0],
    setFileId = _useState2[1];
  var _useState3 = useState(0),
    rotationAngle = _useState3[0],
    setRotationAngle = _useState3[1];

  //初始化fileId
  useEffect(function () {
    var id = value;
    if (!value) {
      id = getShortid('file_');
    }
    setFileId(id);
  }, [value]);
  var handleRotation = function handleRotation() {
    var angle = rotationAngle + 90;
    setRotationAngle(angle);
  };
  useEffect(function () {
    var rotatableImage = document.getElementById('show-img');
    if (!rotatableImage) return;
    rotatableImage.style.transform = "rotate(" + rotationAngle + "deg)";
  }, [rotationAngle]);
  var init = useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var list;
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          if (fileId) {
            _context.next = 2;
            break;
          }
          return _context.abrupt("return");
        case 2:
          _context.next = 4;
          return getFileDetail(fileId);
        case 4:
          list = _context.sent;
          setFileData(list);
        case 6:
        case "end":
          return _context.stop();
      }
    }, _callee);
  })), [fileId]);
  useEffect(function () {
    init();
  }, [init]);

  // 预览图片
  var onPreview = function onPreview(info) {
    setRotationAngle(0);
    _Dialog.show({
      title: '图片预览',
      content: isPreview ? /*#__PURE__*/React.createElement("img", {
        src: info.url,
        style: {
          width: 600,
          height: 600
        }
      }) : /*#__PURE__*/React.createElement(_Box, {
        spacing: 10
      }, /*#__PURE__*/React.createElement("img", {
        id: "show-img",
        src: info.url,
        style: {
          transform: "rotate(" + rotationAngle + "deg)"
        }
      }), /*#__PURE__*/React.createElement(_Box, {
        justify: "center",
        direction: "row"
      }, /*#__PURE__*/React.createElement("div", {
        className: "rotate",
        onClick: handleRotation
      }, "\u65CB\u8F6C"), /*#__PURE__*/React.createElement("a", {
        href: info.url,
        className: "download"
      }, "\u4E0B\u8F7D"))),
      onCancel: function onCancel() {
        setRotationAngle(0);
      },
      footer: false
    });
  };

  // 删除图片
  var onRemove = /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(data) {
      var formData;
      return _regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            formData = new FormData();
            formData.append('id', data.id);
            _context2.next = 4;
            return delImage(formData);
          case 4:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    }));
    return function onRemove(_x) {
      return _ref3.apply(this, arguments);
    };
  }();

  // 图片上传
  var onImgChange = /*#__PURE__*/function () {
    var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(info) {
      var _newData;
      var uids, newData, fileSize, fileObject, fileType, fileUid, Quality, Width, formData, newImg, id, fileUrl, fileName, _newData2;
      return _regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            uids = info.map(function (item) {
              return item.uid;
            }); // let newData: any = inputValue === undefined ? [] : inputValue;
            newData = fileData || [];
            if (fileId) {
              _context3.next = 4;
              break;
            }
            return _context3.abrupt("return");
          case 4:
            if (!(uids.length > ((_newData = newData) === null || _newData === void 0 ? void 0 : _newData.length))) {
              _context3.next = 26;
              break;
            }
            fileSize = info[info.length - 1].size;
            if (!(fileSize > 25 * 1024 * 1024)) {
              _context3.next = 9;
              break;
            }
            _Message.error('上传文件不能超过25M');
            return _context3.abrupt("return");
          case 9:
            fileObject = info[info.length - 1].originFileObj;
            fileType = info[info.length - 1].type;
            fileUid = info[info.length - 1].uid;
            Quality = thumbnailQuality ? thumbnailQuality : 0.7;
            Width = thumbnailWidth ? thumbnailWidth : 80;
            formData = new FormData();
            formData.append('fileId', fileId);
            formData.append('file', fileObject);
            formData.append('thumbnailQuality', Quality);
            formData.append('thumbnailWidth', Width);
            _context3.next = 21;
            return saveImage(formData);
          case 21:
            newImg = _context3.sent;
            id = newImg.id, fileUrl = newImg.fileUrl, fileName = newImg.fileName;
            newData.push({
              uid: fileUid,
              fileTypes: fileType,
              fileId: fileId,
              id: id,
              name: fileName,
              url: fileUrl,
              downloadURL: fileUrl,
              imgURL: fileUrl,
              state: 'done',
              size: 100
            });
            _context3.next = 27;
            break;
          case 26:
            newData = (_newData2 = newData) === null || _newData2 === void 0 ? void 0 : _newData2.filter(function (item) {
              return uids.indexOf(item.uid) !== -1;
            });
          case 27:
            onChange && onChange(fileId);
            setFileData(newData);
          case 29:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    }));
    return function onImgChange(_x2) {
      return _ref4.apply(this, arguments);
    };
  }();
  React.useEffect(function () {
    setRotationAngle(rotationAngle);
  }, [rotationAngle]);
  var _itemRender = function itemRender(file, _ref5) {
    var remove = _ref5.remove;
    // console.log(file);
    return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("img", {
      src: file.url,
      style: {
        maxWidth: '100%',
        maxHeight: '100%'
      }
    }), /*#__PURE__*/React.createElement("div", {
      style: {
        position: 'absolute',
        top: 0,
        right: 0,
        bottom: 0,
        left: 0,
        background: 'rgba(0,0,0,.5)',
        color: '#ddd',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center'
      }
    }, /*#__PURE__*/React.createElement("span", {
      onClick: function onClick() {
        return onPreview(file);
      }
    }, /*#__PURE__*/React.createElement(_Icon, {
      type: "eye",
      style: {
        marginTop: 40,
        cursor: 'pointer'
      }
    }))), /*#__PURE__*/React.createElement("span", {
      onClick: /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() {
        return _regeneratorRuntime.wrap(function _callee4$(_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              _context4.next = 2;
              return onRemove(file);
            case 2:
              remove();
            case 3:
            case "end":
              return _context4.stop();
          }
        }, _callee4);
      }))
    }, /*#__PURE__*/React.createElement(_Icon, {
      type: "ashbin",
      size: "xs",
      style: {
        position: 'absolute',
        right: 2,
        top: 2,
        color: '#fff',
        cursor: 'pointer'
      }
    })));
  };
  return /*#__PURE__*/React.createElement(_Upload.Card, {
    listType: "card",
    style: style,
    value: fileData,
    defaultValue: defaultValue,
    disabled: isDisabled,
    shape: "card",
    useDataURL: true,
    showDownload: false,
    autoUpload: false,
    isPreview: isPreview,
    accept: "image/png, image/jpg, image/jpeg, image/gif, image/bmp",
    itemRender: function itemRender(file, obj) {
      return _itemRender(file, obj);
    },
    onChange: function onChange(e) {
      return onImgChange(e);
    }
  });
};
CommonImage.displayName = 'CommonImage';
export default CommonImage;