"use strict";

var __assign = this && this.__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 = this && this.__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 = this && this.__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
    };
  }
};
exports.__esModule = true;
var react_1 = require("react");
var react_infinite_scroll_component_1 = require("react-infinite-scroll-component");
var use_pubsub_js_1 = require("use-pubsub-js");
var base_1 = require("../../../../api/base");
var noData_png_1 = require("../../../../module/assets/noData.png");
var index_module_scss_1 = require("../index.module.scss");
function List(props) {
  var _this = this;
  var mediaType = props.mediaType;
  var _a = react_1.useState([]),
    list = _a[0],
    setList = _a[1];
  var _b = react_1.useState(0),
    listIndex = _b[0],
    setListIndex = _b[1];
  var _c = react_1.useState({
      pageNum: 1,
      pageSize: 10,
      total: 0
    }),
    page = _c[0],
    setPage = _c[1];
  var _d = react_1.useState(true),
    hasMore = _d[0],
    setHasMore = _d[1];
  var _e = react_1.useState(''),
    schema = _e[0],
    setSchema = _e[1];
  var _f = react_1.useState([]),
    header = _f[0],
    setHeader = _f[1];
  var _g = react_1.useState(0),
    headerIndex = _g[0],
    setHeaderIndex = _g[1];
  use_pubsub_js_1.usePublish({
    token: 'schema_token',
    message: schema,
    isAutomatic: true
  });
  // 仅用于图文左侧瀑布流布局
  react_1.useEffect(function () {
    if (!list.length || mediaType !== 'IMAGE_TEXT') return;
    setTimeout(function () {
      list.map(function (item) {
        var dom = document.getElementById("item" + item.mediaId);
        var height = dom.getBoundingClientRect().height;
        if (+height) dom.style.gridRow = "auto / span " + Math.floor(+height / 10);
        return item;
      });
    }, 0);
  }, [list, mediaType]);
  react_1.useEffect(function () {
    getMediaListData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [page.pageNum, page.pageSize]);
  react_1.useEffect(function () {
    getMediaCategoryListData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  // 获取 list 数据
  var getMediaListData = function getMediaListData(sceneId) {
    if (sceneId === void 0) {
      sceneId = -1;
    }
    return __awaiter(_this, void 0, void 0, function () {
      var data;
      return __generator(this, function (_a) {
        switch (_a.label) {
          case 0:
            return [4 /*yield*/, base_1.getMediaList({
              mediaType: 'IMAGE_TEXT',
              permission: 'PUBLIC',
              isRecommend: 1,
              sceneId: sceneId,
              colorId: -1,
              styleId: -1,
              pageNum: page.pageNum,
              pageSize: page.pageSize
            })];
          case 1:
            data = _a.sent().data;
            if (data) {
              setList(list.concat(data.list));
              setPage(data.page);
            }
            return [2 /*return*/];
        }
      });
    });
  };

  var getMoreData = function getMoreData() {
    var pageNum = page.pageNum,
      pageSize = page.pageSize,
      total = page.total;
    if (pageNum * pageSize >= total) {
      setHasMore(false);
      return;
    }
    setTimeout(function () {
      setPage(function (rest) {
        return __assign(__assign({}, rest), {
          pageNum: pageNum + 1
        });
      });
    }, 500);
  };
  // list 选中
  var handleListIndex = function handleListIndex(e) {
    return __awaiter(_this, void 0, void 0, function () {
      var data, psdJson, _a, width, height, children, newData;
      return __generator(this, function (_b) {
        switch (_b.label) {
          case 0:
            return [4 /*yield*/, base_1.getMediaQuery({
              mediaId: e
            })];
          case 1:
            data = _b.sent();
            if (data) {
              psdJson = data.data.psdJson;
              _a = JSON.parse(psdJson), width = _a.width, height = _a.height, children = _a.children;
              newData = JSON.stringify(Object.assign({}, {
                width: width,
                height: height,
                mediaId: e,
                layers: deepFlatten(children)
              }));
              setSchema(newData);
              setListIndex(e);
            }
            return [2 /*return*/];
        }
      });
    });
  };
  // 数组扁平化
  var deepFlatten = function deepFlatten(args) {
    var result = [];
    args.forEach(function (item) {
      var map = function map(data) {
        if (data.type !== 'group') result.push(data);
        (data === null || data === void 0 ? void 0 : data.children) && data.children.forEach(function (child) {
          return map(child);
        });
      };
      map(item);
    });
    return result;
  };
  // 获取 tab 数据
  var getMediaCategoryListData = function getMediaCategoryListData() {
    return __awaiter(_this, void 0, void 0, function () {
      var data;
      return __generator(this, function (_a) {
        switch (_a.label) {
          case 0:
            return [4 /*yield*/, base_1.getMediaCategoryList({
              parentId: 1
            })];
          case 1:
            data = _a.sent().data;
            if (data) {
              data.unshift({
                ctgId: -1,
                parentId: 1,
                sub: [],
                title: '推荐'
              });
              setHeader(data);
              setHeaderIndex(data[0].ctgId);
            }
            return [2 /*return*/];
        }
      });
    });
  };
  // tab 切换
  var handleHeaderIndex = function handleHeaderIndex(e) {
    setHeaderIndex(e);
    getMediaListData(e);
  };
  return react_1["default"].createElement(react_1["default"].Fragment, null, react_1["default"].createElement("div", {
    className: index_module_scss_1["default"]['xt-list-header']
  }, header.length ? header.map(function (item, index) {
    return react_1["default"].createElement("span", {
      key: index,
      className: "" + (headerIndex === item.ctgId ? index_module_scss_1["default"]['xt-header-active'] : ''),
      onClick: function onClick() {
        return handleHeaderIndex(item.ctgId);
      }
    }, item.title);
  }) : null), react_1["default"].createElement("div", {
    className: mediaType === 'IMAGE_TEXT' ? index_module_scss_1["default"]['xt-fall-content'] : index_module_scss_1["default"]['xt-list-content'],
    style: {
      height: list.length ? 'auto' : '100%'
    }
  }, list.length ? react_1["default"].createElement(react_infinite_scroll_component_1["default"], {
    dataLength: list.length,
    next: getMoreData,
    hasMore: hasMore,
    loader: react_1["default"].createElement("h4", null, "Loading..."),
    height: 400
  }, list.map(function (item) {
    return react_1["default"].createElement("img", {
      id: "item" + item.mediaId,
      key: item.mediaId,
      src: item.psdImg,
      className: "\n                  " + index_module_scss_1["default"]['xt-content-block'] + "\n                  " + (listIndex === item.mediaId ? index_module_scss_1["default"]['xt-content-active'] : '') + "\n                ",
      onClick: function onClick() {
        return handleListIndex(item.mediaId);
      }
    });
  })) : react_1["default"].createElement("div", {
    className: index_module_scss_1["default"]['xt-list-no-data']
  }, react_1["default"].createElement("img", {
    src: noData_png_1["default"],
    alt: ""
  }), react_1["default"].createElement("span", null, "\u7A7A\u7A7A\u5982\u4E5F"))));
}
exports["default"] = List;