"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _antd = require("antd");

var _findIndex = _interopRequireDefault(require("lodash/findIndex"));

var _isEmpty = _interopRequireDefault(require("lodash/isEmpty"));

var _react = _interopRequireWildcard(require("react"));

var _CommonModal = _interopRequireDefault(require("./CommonModal"));

var _const = require("./CommonModal/const");

var _CommonSelPicCard = _interopRequireDefault(require("./CommonSelPicCard"));

var _const2 = require("./const");

var _Iconfont = _interopRequireDefault(require("../Iconfont"));

require("./index.less");

var _commonUtil = require("../../utils/commonUtil");

var _dataTreeUtils = _interopRequireDefault(require("../../utils/dataTreeUtils"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

var __assign = void 0 && (void 0).__assign || function () {
  __assign = Object.assign || function (t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];

      for (var p in s) {
        if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
      }
    }

    return t;
  };

  return __assign.apply(this, arguments);
};

var __awaiter = void 0 && (void 0).__awaiter || function (thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function (resolve) {
      resolve(value);
    });
  }

  return new (P || (P = Promise))(function (resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }

    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }

    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }

    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};

var __generator = void 0 && (void 0).__generator || function (thisArg, body) {
  var _ = {
    label: 0,
    sent: function sent() {
      if (t[0] & 1) throw t[1];
      return t[1];
    },
    trys: [],
    ops: []
  },
      f,
      y,
      t,
      g;
  return g = {
    next: verb(0),
    "throw": verb(1),
    "return": verb(2)
  }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
    return this;
  }), g;

  function verb(n) {
    return function (v) {
      return step([n, v]);
    };
  }

  function step(op) {
    if (f) throw new TypeError("Generator is already executing.");

    while (_) {
      try {
        if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
        if (y = 0, t) op = [op[0] & 2, t.value];

        switch (op[0]) {
          case 0:
          case 1:
            t = op;
            break;

          case 4:
            _.label++;
            return {
              value: op[1],
              done: false
            };

          case 5:
            _.label++;
            y = op[1];
            op = [0];
            continue;

          case 7:
            op = _.ops.pop();

            _.trys.pop();

            continue;

          default:
            if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
              _ = 0;
              continue;
            }

            if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
              _.label = op[1];
              break;
            }

            if (op[0] === 6 && _.label < t[1]) {
              _.label = t[1];
              t = op;
              break;
            }

            if (t && _.label < t[2]) {
              _.label = t[2];

              _.ops.push(op);

              break;
            }

            if (t[2]) _.ops.pop();

            _.trys.pop();

            continue;
        }

        op = body.call(thisArg, _);
      } catch (e) {
        op = [6, e];
        y = 0;
      } finally {
        f = t = 0;
      }
    }

    if (op[0] & 5) throw op[1];
    return {
      value: op[0] ? op[1] : void 0,
      done: true
    };
  }
};

var __spreadArrays = void 0 && (void 0).__spreadArrays || function () {
  for (var s = 0, i = 0, il = arguments.length; i < il; i++) {
    s += arguments[i].length;
  }

  for (var r = Array(s), k = 0, i = 0; i < il; i++) {
    for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) {
      r[k] = a[j];
    }
  }

  return r;
};

var TreeNode = _antd.Tree.TreeNode;
var modalSize = _const.size;
var Search = _antd.Input.Search;
var picAccept = '.gif,.jpg,.png';
var videoAccept = '.AVI,.mov,.rmvb,.rm,.FLV,.mp4,.3GP';
var pageSize = 24;

function ImageModal(_a) {
  var _this = this;

  var onCancel = _a.onCancel,
      visible = _a.visible,
      _onOk = _a.onOk,
      _b = _a.maxCount,
      maxCount = _b === void 0 ? 1 : _b,
      _c = _a.type,
      type = _c === void 0 ? _const2.contentCatgTypeMap.PICTURE : _c;

  var _d = (0, _react.useState)([]),
      treeData = _d[0],
      setTreeData = _d[1];

  var _e = (0, _react.useState)(['-1']),
      selectedKeys = _e[0],
      setSelectedKeys = _e[1];

  var _f = (0, _react.useState)([]),
      selectedPics = _f[0],
      setSelectedPics = _f[1];

  var _g = (0, _react.useState)([]),
      contents = _g[0],
      setContents = _g[1];

  var _h = (0, _react.useState)(0),
      total = _h[0],
      setTotal = _h[1];

  var _j = (0, _react.useState)(1),
      pageIndex = _j[0],
      setPageIndex = _j[1];

  var _k = (0, _react.useState)(false),
      spinning = _k[0],
      setSpinning = _k[1];

  var _l = (0, _react.useState)(''),
      name = _l[0],
      setName = _l[1];

  var _m = (0, _react.useState)([]),
      contentcatgsList = _m[0],
      setContentcatgsList = _m[1];

  var _o = (0, _react.useState)(''),
      searchValue = _o[0],
      setSearchValue = _o[1];

  var _p = (0, _react.useState)([]),
      expandedKeys = _p[0],
      setExpandedKeys = _p[1];

  var _q = (0, _react.useState)(true),
      autoExpandParent = _q[0],
      setAutoExpandParent = _q[1]; // const currentUser = sessionUtil.getUser() || {};
  // const { _csrf } = currentUser;
  // const headers = {};
  // if (_csrf && _csrf.headerName) {
  //   headers[_csrf.headerName] = _csrf.token;
  // }


  var headers = {};
  headers['X-CSRF-TOKEN'] = localStorage.getItem('X-CSRF-TOKEN') || '';
  headers.accessToken = localStorage.getItem('X-CSRF-TOKEN') || ''; // 查询图片库类目下的图片列表

  var qryImageContents = function qryImageContents(data) {
    return __awaiter(_this, void 0, void 0, function () {
      var extreParams, res, newContentData_1;
      return __generator(this, function (_a) {
        switch (_a.label) {
          case 0:
            extreParams = {};

            if (data && "" + data.contentCatgId === '-1') {
              extreParams.contentType = 'File';
            }

            return [4
            /*yield*/
            , (0, _commonUtil.commonFetch)(window.magicDesign.MBaseUrl + "/contents", __assign(__assign({
              pageIndex: pageIndex,
              pageSize: pageSize,
              pageTotal: false,
              name: name,
              catgType: type === _const2.contentCatgTypeMap.PICTURE ? _const2.catgType.PICTURE : _const2.catgType.VIDEO
            }, data), extreParams), 'GET')];

          case 1:
            res = _a.sent();

            if (res) {
              newContentData_1 = [];
              (res.list || []).forEach(function (item) {
                newContentData_1.push({
                  contentId: item.uid,
                  contentTitle: item.name,
                  url: item.oriUrl ? item.oriUrl : item.url,
                  imgUrl: item.imgUrl,
                  contentType: item.contentType
                });
              });
              setTotal(res.total);
              setContents(newContentData_1);
            }

            setSpinning(false);
            return [2
            /*return*/
            ];
        }
      });
    });
  }; // const qryImageContents = useFetch(
  //   data => {
  //     const extreParams = {};
  //     if (data && `${data.contentCatgId}` === '-1') {
  //       extreParams.contentType = 'File';
  //     }
  //     return {
  //       url: `${window.magicDesign.MBaseUrl}/contents`,
  //       params: {
  //         pageIndex,
  //         pageSize,
  //         pageTotal: false,
  //         name,
  //         catgType: type === contentCatgTypeMap.PICTURE ? catgType.PICTURE : catgType.VIDEO,
  //         ...data,
  //         ...extreParams,
  //       },
  //     };
  //   },
  //   {
  //     manual: true,
  //     onSuccess: data => {
  //       if (data) {
  //         const newContentData = [];
  //         (data.list || []).forEach(item => {
  //           newContentData.push({
  //             contentId: item.uid,
  //             contentTitle: item.name,
  //             url: item.url,
  //             imgUrl: item.imgUrl,
  //             contentType: item.contentType,
  //           });
  //         });
  //         setTotal(data.total);
  //         setContents(newContentData);
  //       }
  //       setSpinning(false);
  //     },
  //   }
  // );
  // 查询图片库类目


  var getContentCatgs = function getContentCatgs() {
    return __awaiter(_this, void 0, void 0, function () {
      var data, mapProps, newData;
      return __generator(this, function (_a) {
        switch (_a.label) {
          case 0:
            return [4
            /*yield*/
            , (0, _commonUtil.commonFetch)(window.magicDesign.MBaseUrl + "/contentcatgs", {
              catgType: type === _const2.contentCatgTypeMap.PICTURE ? _const2.catgType.PICTURE : _const2.catgType.VIDEO
            }, 'GET')];

          case 1:
            data = _a.sent();
            mapProps = {
              value: 'contentCatgId',
              title: 'contentCatgName'
            };
            setContentcatgsList(__spreadArrays([{
              value: '-1',
              title: 'Default',
              contentCatgName: 'Default'
            }], data));
            newData = _dataTreeUtils["default"].translateDataToTree(data || [], 'contentCatgId', 'parentCatgId', mapProps);
            newData.unshift({
              value: '-1',
              title: 'Default',
              contentCatgName: 'Default'
            });
            setTreeData(newData);
            setSelectedKeys(['-1']);
            qryImageContents({
              contentCatgId: '-1'
            });
            return [2
            /*return*/
            ];
        }
      });
    });
  };

  (0, _react.useEffect)(function () {
    getContentCatgs();
  }, []);

  var selectFolder = function selectFolder(id) {
    setSelectedKeys(["" + id]);
    var filterArr = (expandedKeys || []).filter(function (val) {
      return val === "" + id;
    });

    if (!(filterArr && filterArr.length)) {
      setAutoExpandParent(true);
      setExpandedKeys(__spreadArrays(expandedKeys, ["" + id]));
    }

    setPageIndex(1);
    qryImageContents({
      contentCatgId: id,
      pageIndex: 1
    });
  }; // 选择类目上某个节点


  var onSelect = function onSelect(record) {
    if (!(record && record.length)) {
      return;
    }

    setSelectedKeys(record);
    setPageIndex(1);
    qryImageContents({
      contentCatgId: record[0],
      pageIndex: 1
    });
  };

  var onUpload = function onUpload(data) {
    return fetch('/operation/v1/upload/contents', {
      method: 'POST',
      body: data,
      headers: headers
    }).then(function () {
      setSpinning(false);
    });
  };

  var handleUpload = function handleUpload(file) {
    return __awaiter(_this, void 0, void 0, function () {
      var form, result;
      return __generator(this, function (_a) {
        switch (_a.label) {
          case 0:
            if (_const2.catgType === _const2.contentCatgTypeMap.PICTURE) {
              if (file.type.indexOf('image/') < 0) {
                return [2
                /*return*/
                , false];
              }
            } else if (_const2.catgType === _const2.contentCatgTypeMap.VIDEO) {
              if (file.type.indexOf('video/') < 0) {
                return [2
                /*return*/
                , false];
              }
            }

            form = new FormData();
            form.append('file', file); // 文件对象

            form.append('path', file.path && file.path.indexOf('/') > -1 ? file.path : ''); // 文件路径

            form.append('contentCatgId', selectedKeys[0]); // 文件对象

            form.append('catgType', type); // 文件类型

            return [4
            /*yield*/
            , onUpload(form)];

          case 1:
            result = _a.sent();
            return [2
            /*return*/
            , result];
        }
      });
    });
  }; // 自定义上传


  var beforeUpload = function beforeUpload(file) {
    if (!(0, _commonUtil.checkFileName)(file.name)) {
      _antd.message.error("File name cannot have '/' '\\' ',' special characters");

      return false;
    }

    setSpinning(true);
    handleUpload(file).then(function (result) {
      if (result !== false) {
        // 上传成功刷新表格
        qryImageContents({
          contentCatgId: selectedKeys[0],
          name: '',
          pageIndex: 1
        });
      }
    });
    return false;
  };

  var getParentKey = function getParentKey(key, tree) {
    var parentKey;

    for (var i = 0; i < tree.length; i += 1) {
      var node = tree[i];

      if (node.children) {
        if (node.children.some(function (item) {
          return "" + item.value === key;
        })) {
          parentKey = node.value;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }

    return parentKey;
  };

  var onChange = function onChange(e) {
    var value = e.target.value;
    var newKeys = (contentcatgsList || []).map(function (item) {
      if ((item.contentCatgName || '').toLowerCase().indexOf((value || '').toLowerCase()) > -1) {
        return getParentKey("" + item.contentCatgId, treeData);
      }

      return null;
    }).filter(function (item, i, self) {
      return item && self.indexOf(item) === i;
    });
    setSearchValue(value);
    setExpandedKeys(newKeys);
    setAutoExpandParent(true);
  }; // 分页信息


  var pagination = {
    current: pageIndex,
    pageSize: pageSize,
    total: total,
    onChange: function onChange(page) {
      setPageIndex(page);
      qryImageContents({
        contentCatgId: selectedKeys[0],
        pageIndex: page
      });
    }
  };

  var onSelectPic = function onSelectPic(e, content) {
    var checked = e.target.checked; // 单选

    if (maxCount === 1) {
      if (checked) {
        setSelectedPics([]);
      } else {
        setSelectedPics([content]);
      }
    }

    setSelectedPics(function (pics) {
      var newPics = []; // 多选

      if (checked) {
        newPics = __spreadArrays(pics, [content]);
      } else {
        newPics = pics.filter(function (pic) {
          return pic.contentId !== content.contentId;
        });
      }

      return newPics;
    });
  };

  var handleSearch = function handleSearch(value) {
    var newName = value ? value.trim() : '';
    setName(newName);
    setPageIndex(1);
    qryImageContents({
      name: newName,
      pageIndex: 1,
      contentCatgId: selectedKeys[0]
    });
  };

  var handleExpand = function handleExpand(keys) {
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    setAutoExpandParent(false);
    setExpandedKeys(keys);
  };

  var treeOpts = {
    blockNode: true,
    autoExpandParent: autoExpandParent,
    selectedKeys: selectedKeys,
    expandedKeys: expandedKeys,
    onSelect: onSelect,
    onExpand: handleExpand
  };

  var renderTreeNodes = function renderTreeNodes(data) {
    return (data || []).map(function (item) {
      var index = (item.title || '').toLowerCase().indexOf((searchValue || '').toLowerCase());
      var beforeStr = (item.title || '').substr(0, index);
      var afterStr = (item.title || '').substr(index + searchValue.length);
      var title = index > -1 ? /*#__PURE__*/_react["default"].createElement("span", null, beforeStr, /*#__PURE__*/_react["default"].createElement("span", {
        style: {
          color: '#f50'
        }
      }, searchValue), afterStr) : /*#__PURE__*/_react["default"].createElement("span", null, item.title);
      var value = item.value,
          children = item.children;

      if (children) {
        return /*#__PURE__*/_react["default"].createElement(TreeNode, {
          key: value,
          title: title
        }, renderTreeNodes(children));
      }

      return /*#__PURE__*/_react["default"].createElement(TreeNode, {
        key: value,
        title: title,
        value: value
      });
    });
  };

  return /*#__PURE__*/_react["default"].createElement(_CommonModal["default"], {
    modalOpts: {
      title: 'Image',
      width: modalSize.LARGE
    },
    onCancel: onCancel,
    onOk: function onOk() {
      return _onOk(selectedPics);
    },
    visible: visible
  }, /*#__PURE__*/_react["default"].createElement(_antd.Row, {
    style: {
      marginBottom: 8
    }
  }, /*#__PURE__*/_react["default"].createElement(_antd.Col, {
    span: 3
  }, /*#__PURE__*/_react["default"].createElement(_antd.Upload, {
    accept: type === _const2.contentCatgTypeMap.PICTURE ? picAccept : videoAccept,
    action: "/ecommerce/upload/contents",
    beforeUpload: beforeUpload,
    fileList: [],
    headers: headers
  }, /*#__PURE__*/_react["default"].createElement(_antd.Button, null, /*#__PURE__*/_react["default"].createElement(_Iconfont["default"], {
    type: "upload"
  }), "Upload"))), /*#__PURE__*/_react["default"].createElement(_antd.Col, {
    span: 8
  }, /*#__PURE__*/_react["default"].createElement(Search, {
    enterButton: true,
    onSearch: function onSearch(value) {
      return handleSearch(value);
    },
    placeholder: "Please Search"
  }))), /*#__PURE__*/_react["default"].createElement(_antd.Row, null, /*#__PURE__*/_react["default"].createElement(_antd.Col, {
    span: 6
  }, /*#__PURE__*/_react["default"].createElement(_antd.Card, {
    bodyStyle: {
      height: 500,
      overflowY: 'auto'
    },
    className: "catg_tree_container"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "search_container"
  }, /*#__PURE__*/_react["default"].createElement(Search, {
    onChange: onChange,
    placeholder: "Keywrods"
  })), /*#__PURE__*/_react["default"].createElement(_antd.Tree, treeOpts, renderTreeNodes(treeData)))), /*#__PURE__*/_react["default"].createElement(_antd.Col, {
    span: 18
  }, /*#__PURE__*/_react["default"].createElement(_antd.Card, {
    bodyStyle: {
      height: 500
    },
    className: "catg_img"
  }, /*#__PURE__*/_react["default"].createElement(_antd.Card, {
    bodyStyle: {
      height: 380,
      overflowX: 'auto'
    }
  }, /*#__PURE__*/_react["default"].createElement(_antd.Spin, {
    spinning: spinning
  }, !(0, _isEmpty["default"])(contents) && contents.map(function (content) {
    return /*#__PURE__*/_react["default"].createElement(_CommonSelPicCard["default"], {
      key: content.contentId,
      checked: (0, _findIndex["default"])(selectedPics || [], function (val) {
        return val.contentId === content.contentId;
      }) > -1,
      content: content,
      onChange: function onChange(e) {
        return onSelectPic(e, content);
      },
      onClick: selectFolder,
      type: type
    });
  }))), /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      "float": 'right',
      margin: '16px 0'
    }
  }, /*#__PURE__*/_react["default"].createElement(_antd.Pagination, _extends({
    size: "small"
  }, pagination)))))));
}

var _default = ImageModal;
exports["default"] = _default;