import _regeneratorRuntime from "@babel/runtime/regenerator";

function _extends() { _extends = Object.assign || 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); }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? Object(arguments[i]) : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys.push.apply(ownKeys, Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

import { fetch, useFetch } from '@fishx/rest';
import { Button, Card, Col, Icon, Input, message, Pagination, Row, Spin, Tree, Upload } from '@whalecloud/fdx';
import findIndex from 'lodash/findIndex';
import isEmpty from 'lodash/isEmpty';
import React, { useState } from 'react';
import { checkFileName } from '../../../../../../utils/commonUtil';
import treeUtils from '../../../../../../utils/dataTreeUtils';
import CommonModal from '../CommonModal';
import { size } from '../CommonModal/const';
import CommonSelPicCard from '../CommonSelPicCard';
import { catgType, contentCatgTypeMap } from '../const';
import './index.less';
var TreeNode = Tree.TreeNode;
var modalSize = size;
var Search = Input.Search;
var picAccept = '.gif,.jpg,.png';
var videoAccept = '.AVI,.mov,.rmvb,.rm,.FLV,.mp4,.3GP';
var pageSize = 24;

function ImageModal(_ref) {
  var onCancel = _ref.onCancel,
      visible = _ref.visible,
      _onOk = _ref.onOk,
      maxCount = _ref.maxCount,
      type = _ref.type;

  var _useState = useState([]),
      _useState2 = _slicedToArray(_useState, 2),
      treeData = _useState2[0],
      setTreeData = _useState2[1];

  var _useState3 = useState(['-1']),
      _useState4 = _slicedToArray(_useState3, 2),
      selectedKeys = _useState4[0],
      setSelectedKeys = _useState4[1];

  var _useState5 = useState([]),
      _useState6 = _slicedToArray(_useState5, 2),
      selectedPics = _useState6[0],
      setSelectedPics = _useState6[1];

  var _useState7 = useState([]),
      _useState8 = _slicedToArray(_useState7, 2),
      contents = _useState8[0],
      setContents = _useState8[1];

  var _useState9 = useState(0),
      _useState10 = _slicedToArray(_useState9, 2),
      total = _useState10[0],
      setTotal = _useState10[1];

  var _useState11 = useState(1),
      _useState12 = _slicedToArray(_useState11, 2),
      pageIndex = _useState12[0],
      setPageIndex = _useState12[1];

  var _useState13 = useState(false),
      _useState14 = _slicedToArray(_useState13, 2),
      spinning = _useState14[0],
      setSpinning = _useState14[1];

  var _useState15 = useState(''),
      _useState16 = _slicedToArray(_useState15, 2),
      name = _useState16[0],
      setName = _useState16[1];

  var _useState17 = useState([]),
      _useState18 = _slicedToArray(_useState17, 2),
      contentcatgsList = _useState18[0],
      setContentcatgsList = _useState18[1];

  var _useState19 = useState(''),
      _useState20 = _slicedToArray(_useState19, 2),
      searchValue = _useState20[0],
      setSearchValue = _useState20[1];

  var _useState21 = useState([]),
      _useState22 = _slicedToArray(_useState21, 2),
      expandedKeys = _useState22[0],
      setExpandedKeys = _useState22[1];

  var _useState23 = useState(true),
      _useState24 = _slicedToArray(_useState23, 2),
      autoExpandParent = _useState24[0],
      setAutoExpandParent = _useState24[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 = useFetch(function (data) {
    var extreParams = {};

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

    return {
      url: "".concat(window.MParams.MBaseUrl, "/contents"),
      params: _objectSpread({
        pageIndex: pageIndex,
        pageSize: pageSize,
        pageTotal: false,
        name: name,
        catgType: type === contentCatgTypeMap.PICTURE ? catgType.PICTURE : catgType.VIDEO
      }, data, extreParams)
    };
  }, {
    manual: true,
    onSuccess: function onSuccess(data) {
      if (data) {
        var newContentData = [];
        (data.list || []).forEach(function (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);
    }
  }); // 查询图片库类目

  useFetch(function () {
    return {
      url: "".concat(window.MParams.MBaseUrl, "/contentcatgs"),
      params: {
        catgType: type === contentCatgTypeMap.PICTURE ? catgType.PICTURE : catgType.VIDEO
      }
    };
  }, {
    onSuccess: function onSuccess(data) {
      var mapProps = {
        value: 'contentCatgId',
        title: 'contentCatgName'
      };
      setContentcatgsList([{
        value: '-1',
        title: 'Default',
        contentCatgName: 'Default'
      }].concat(_toConsumableArray(data)));
      var newData = treeUtils.translateDataToTree(data || [], 'contentCatgId', 'parentCatgId', mapProps);
      newData.unshift({
        value: '-1',
        title: 'Default',
        contentCatgName: 'Default'
      });
      setTreeData(newData);
      setSelectedKeys(['-1']);
      qryImageContents.run({
        contentCatgId: '-1'
      });
    }
  });

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

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

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


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

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

  var onUpload = function onUpload(data) {
    return fetch("".concat(window.MParams.MBaseUrl, "/upload/contents"), {
      method: 'POST',
      data: data,
      headers: headers // onUploadProgress,

    });
  };

  var handleUpload = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(file) {
      var form, result;
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (!(catgType === contentCatgTypeMap.PICTURE)) {
                _context.next = 5;
                break;
              }

              if (!(file.type.indexOf('image/') < 0)) {
                _context.next = 3;
                break;
              }

              return _context.abrupt("return", false);

            case 3:
              _context.next = 8;
              break;

            case 5:
              if (!(catgType === contentCatgTypeMap.VIDEO)) {
                _context.next = 8;
                break;
              }

              if (!(file.type.indexOf('video/') < 0)) {
                _context.next = 8;
                break;
              }

              return _context.abrupt("return", false);

            case 8:
              form = new FormData(); // 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); // 文件类型

              _context.next = 15;
              return onUpload(form);

            case 15:
              result = _context.sent;
              return _context.abrupt("return", result);

            case 17:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function handleUpload(_x) {
      return _ref2.apply(this, arguments);
    };
  }(); // 自定义上传


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

    setSpinning(true);
    handleUpload(file).then(function (result) {
      if (result !== false) {
        // 上传成功刷新表格
        qryImageContents.run({
          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 "".concat(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("".concat(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.run({
        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 = [].concat(_toConsumableArray(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.run({
      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.createElement("span", null, beforeStr, /*#__PURE__*/React.createElement("span", {
        style: {
          color: '#f50'
        }
      }, searchValue), afterStr) : /*#__PURE__*/React.createElement("span", null, item.title);
      var value = item.value,
          children = item.children;

      if (children) {
        return /*#__PURE__*/React.createElement(TreeNode, {
          key: value,
          title: title
        }, renderTreeNodes(children));
      }

      return /*#__PURE__*/React.createElement(TreeNode, {
        key: value,
        value: value,
        title: title
      });
    });
  };

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

export default ImageModal;