import _Progress from "@alifd/next/es/progress";
import _Icon from "@alifd/next/es/icon";
import _Dialog from "@alifd/next/es/dialog";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _extends from "@babel/runtime/helpers/extends";
import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import React, { Component } from 'react';
import { readPsd } from 'ag-psd';
import style from "./index.module.scss";
import cosUpload from "../../module/axios/cosUpload";
import { b64toFile } from "../../utils/utils";
var progressText = ['', ' 模板上传中', ' 模板解析中', ' 背景图上传中'];
var UploadImgSetter = /*#__PURE__*/function (_Component) {
  _inheritsLoose(UploadImgSetter, _Component);
  function UploadImgSetter() {
    var _this2;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this2 = _Component.call.apply(_Component, [this].concat(args)) || this;
    _this2.state = {
      selectIdx: 0,
      psdList: [],
      upLoad: {
        step: 0,
        progress: 0
      }
    };
    return _this2;
  }
  var _proto = UploadImgSetter.prototype;
  _proto.componentDidMount = function componentDidMount() {
    var selected = this.props.selected;
    var _this$state$psdList = this.state.psdList,
      psdList = _this$state$psdList === void 0 ? '[]' : _this$state$psdList;
    var storageList = localStorage.getItem(selected.id) || [];
    if ((psdList === null || psdList === void 0 ? void 0 : psdList.length) < 1 && (storageList === null || storageList === void 0 ? void 0 : storageList.length) > 0) {
      this.setState({
        psdList: JSON.parse(storageList)
      });
    }
  };
  _proto.render = function render() {
    var _this3 = this;
    var _this$props = this.props,
      _this$props$value$max = _this$props.value.maxLen,
      maxLen = _this$props$value$max === void 0 ? 4 : _this$props$value$max,
      selected = _this$props.selected,
      onChange = _this$props.onChange;
    var _this$state = this.state,
      _this$state$psdList2 = _this$state.psdList,
      psdList = _this$state$psdList2 === void 0 ? '[]' : _this$state$psdList2,
      upLoad = _this$state.upLoad;
    // const storageList = localStorage.getItem(selected.id) || [];
    // const storageList = psdList
    // if (psdList?.length < 1 && storageList?.length > 0) {
    //   this.setState({
    //     psdList: JSON.parse(storageList),
    //   });
    // }

    var step = upLoad.step,
      progress = upLoad.progress;

    /**
     *
     * @param { number } total 总大小
     * @param { number } loaded 已处理大小
     * @param { number } step 状态
     */
    var setUploadStatus = function setUploadStatus(_ref, step) {
      var total = _ref.total,
        loaded = _ref.loaded;
      var progress = (loaded / total * 100).toFixed(2) - 0;
      _this3.setState({
        upLoad: {
          step: step,
          progress: progress
        }
      });
      changeTpl(_this3.state.psdList.length - 1);
    };
    var changeTpl = function changeTpl(idx) {
      var state = _extends({}, _this3.state, {
        selectIdx: idx
      });
      _this3.setState(state);
      var _state = Object.assign({}, state);
      onChange(_state);
    };
    var SelectChange = /*#__PURE__*/function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(e) {
        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return new Promise(function (resolve) {
                var val = {
                  bgImg: '',
                  layers: [],
                  source: e
                };
                var xhr = new XMLHttpRequest();
                xhr.open('GET', e, true);
                xhr.responseType = 'arraybuffer';
                xhr.addEventListener('load', function () {
                  var buffer = xhr.response;
                  var rPsd = readPsd(buffer);
                  rPsd.children.forEach( /*#__PURE__*/function () {
                    var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(res) {
                      var _ref4, _canvas, _text, _name, top, left, bgFile, _yield$cosUpload, code, data, ossPath, text, _text$style, fontSize, fillColor, font, fauxBold, fauxItalic, fontBaseline, transform, multiple, _fontSize, _style;
                      return _regeneratorRuntime.wrap(function _callee$(_context) {
                        while (1) switch (_context.prev = _context.next) {
                          case 0:
                            _ref4 = res || {
                              text: {}
                            }, _canvas = _ref4.canvas, _text = _ref4.text, _name = _ref4.name, top = _ref4.top, left = _ref4.left;
                            if (!(res.name === '背景')) {
                              _context.next = 11;
                              break;
                            }
                            bgFile = b64toFile(_canvas.toDataURL('image/webp'), "tmp-file-" + Date.now() + ".webp");
                            _context.next = 5;
                            return cosUpload(bgFile, {
                              pathDir: 'banner-psd/bg-img' || '',
                              isDateDir: true,
                              reName: true,
                              onProgress: function onProgress(_ref5) {
                                var total = _ref5.total,
                                  loaded = _ref5.loaded;
                                setUploadStatus({
                                  total: total,
                                  loaded: loaded
                                }, 3);
                              }
                            });
                          case 5:
                            _yield$cosUpload = _context.sent;
                            code = _yield$cosUpload.code;
                            data = _yield$cosUpload.data;
                            if (code === '0000') {
                              ossPath = data.ossPath;
                              val.bgImg = ossPath + "?imageMogr2/thumbnail/1200x";
                              resolve(val);
                            }
                            _context.next = 16;
                            break;
                          case 11:
                            text = _text.text, _text$style = _text.style, fontSize = _text$style.fontSize, fillColor = _text$style.fillColor, font = _text$style.font, fauxBold = _text$style.fauxBold, fauxItalic = _text$style.fauxItalic, fontBaseline = _text$style.fontBaseline, transform = _text.transform;
                            multiple = [1, 2].includes(fontBaseline) ? 0.5 : 1;
                            _fontSize = fontSize * transform[0] * 100 / rPsd.width;
                            _style = {
                              fontSize: _fontSize * multiple + "vw",
                              // 实际字体大小 * 100 / 画布宽
                              color: "rgba(" + Object.values(fillColor).join(',') + ")",
                              // 颜色
                              fontFamily: font.name,
                              fontWeight: fauxBold ? 'bolder' : 'normal',
                              fontStyle: fauxItalic ? 'italic' : 'normal',
                              left: left * 100 / rPsd.width + "%",
                              top: top * 100 / rPsd.height + "%"
                            };
                            val.layers.push({
                              text: text,
                              _name: _name,
                              style: _style
                            });
                          case 16:
                          case "end":
                            return _context.stop();
                        }
                      }, _callee);
                    }));
                    return function (_x2) {
                      return _ref3.apply(this, arguments);
                    };
                  }());
                }, false);
                xhr.onprogress = function (_ref6) {
                  var total = _ref6.total,
                    loaded = _ref6.loaded;
                  setUploadStatus({
                    total: total,
                    loaded: loaded
                  }, 2);
                };
                xhr.send();
              });
            case 2:
              return _context2.abrupt("return", _context2.sent);
            case 3:
            case "end":
              return _context2.stop();
          }
        }, _callee2);
      }));
      return function SelectChange(_x) {
        return _ref2.apply(this, arguments);
      };
    }();
    var upLoadFn = /*#__PURE__*/function () {
      var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(ev) {
        var _ev$target;
        var _this, succ;
        return _regeneratorRuntime.wrap(function _callee4$(_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              _this = _this3;
              succ = cosUpload(ev === null || ev === void 0 ? void 0 : (_ev$target = ev.target) === null || _ev$target === void 0 ? void 0 : _ev$target.files[0], {
                pathDir: 'banner-psd' || '',
                isDateDir: true,
                reName: true,
                onProgress: function onProgress(_ref8) {
                  var total = _ref8.total,
                    loaded = _ref8.loaded;
                  setUploadStatus({
                    total: total,
                    loaded: loaded
                  }, 1);
                  if (total === loaded) _this.setState({
                    upLoad: {
                      progress: 0
                    }
                  });
                }
              });
              succ.then( /*#__PURE__*/function () {
                var _ref10 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(_ref9) {
                  var code, data, psdItem;
                  return _regeneratorRuntime.wrap(function _callee3$(_context3) {
                    while (1) switch (_context3.prev = _context3.next) {
                      case 0:
                        code = _ref9.code, data = _ref9.data;
                        if (!(code === '0000')) {
                          _context3.next = 9;
                          break;
                        }
                        _context3.next = 4;
                        return SelectChange(data.ossPath);
                      case 4:
                        psdItem = _context3.sent;
                        psdList.push(Object.assign(psdItem, {
                          key: getUrlFileName(psdItem.source)
                        }));
                        _this.setState({
                          psdList: psdList
                        });
                        localStorage.setItem(selected.id, JSON.stringify(psdList));
                        changeTpl(psdList.length - 1);
                      case 9:
                      case "end":
                        return _context3.stop();
                    }
                  }, _callee3);
                }));
                return function (_x4) {
                  return _ref10.apply(this, arguments);
                };
              }());
            case 3:
            case "end":
              return _context4.stop();
          }
        }, _callee4);
      }));
      return function upLoadFn(_x3) {
        return _ref7.apply(this, arguments);
      };
    }();
    var getUrlFileName = function getUrlFileName(url) {
      return url.replace(/.+?(\w+)\.[\w?=]+$$/g, '$1');
    };
    var delItem = function delItem(ev, key) {
      ev.stopPropagation();
      _Dialog.confirm({
        title: '提示',
        content: '您确定要删除此模板?',
        onOk: function onOk() {
          var idx = psdList.findIndex(function (res) {
            return res.key === key;
          });
          psdList.splice(idx, 1);
          psdList.length ? localStorage.setItem(selected.id, JSON.stringify(psdList)) : localStorage.removeItem(selected.id);
          _this3.setState({
            psdList: psdList
          });
        }
      });
    };
    var onChangeXtBanner = function onChangeXtBanner(e) {
      localStorage.setItem(selected.id, JSON.stringify([e]));
      var changePsdList = JSON.parse(localStorage.getItem(selected.id));
      _this3.setState({
        psdList: changePsdList
      });
      onChange(_extends({}, _this3.state, {
        psdList: [e]
      }));
    };
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
      className: style['upload-imgselect']
    }, (psdList === null || psdList === void 0 ? void 0 : psdList.length) > 0 ? psdList.map(function (res, idx) {
      return /*#__PURE__*/React.createElement("div", {
        style: {
          backgroundImage: "url(" + res.bgImg + ")"
        },
        className: style['upload-imgselect-li'] + " " + (_this3.state.selectIdx === idx ? style.active : ''),
        onClick: function onClick() {
          return changeTpl(idx);
        },
        key: res.key
      }, /*#__PURE__*/React.createElement(_Icon, {
        className: style.del,
        type: "ashbin",
        onClick: function onClick(ev) {
          return delItem(ev, res.key);
        }
      }));
    }) : '', psdList.length < maxLen ? /*#__PURE__*/React.createElement("div", {
      className: style['upload-imgselect-li'] + " " + style.add
    }, /*#__PURE__*/React.createElement("input", {
      type: "file",
      onChange: function onChange(ev) {
        return upLoadFn(ev);
      },
      accept: ".psd"
    }), /*#__PURE__*/React.createElement("img", {
      className: style.upload,
      src: "https://img.maimairen.com/low-code/ali/material-icon/update-psd.svg",
      alt: "upload"
    }), "\u4E0A\u4F20PSD\u6A21\u677F") : '', /*#__PURE__*/React.createElement(_Dialog, {
      title: "\u63D0\u793A",
      visible: progress > 0 && progress < 100,
      footer: /*#__PURE__*/React.createElement("div", null),
      closeMode: [],
      className: style.uploading
    }, /*#__PURE__*/React.createElement(_Progress, {
      percent: progress,
      style: {
        width: '150px',
        height: '100%'
      },
      textRender: function textRender() {
        return /*#__PURE__*/React.createElement("div", {
          className: style['dialog-upload']
        }, /*#__PURE__*/React.createElement("div", {
          style: {
            textAlign: 'cenger'
          }
        }, progress, "%"), /*#__PURE__*/React.createElement("div", {
          className: style['dialog-txt']
        }, progressText[step]));
      },
      shape: "circle"
    }))));
  };
  return UploadImgSetter;
}(Component);
UploadImgSetter.displayName = 'UploadImgSetter';
export { UploadImgSetter as default };