/*eslint no-unused-vars:0, no-console:0 */
/* global __DEVELOPMENT__, $ */
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.HomeB = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Choices = require('../components/Choices');

var _Choices2 = _interopRequireDefault(_Choices);

var _reactDocumentMeta = require('react-document-meta');

var _reactDocumentMeta2 = _interopRequireDefault(_reactDocumentMeta);

var _Footer = require('../components/Footer');

var _Footer2 = _interopRequireDefault(_Footer);

var _HeaderB = require('../components/HeaderB');

var _HeaderB2 = _interopRequireDefault(_HeaderB);

var _LatestArticles = require('../components/LatestArticles');

var _LatestArticles2 = _interopRequireDefault(_LatestArticles);

var _LatestChoices = require('../components/LatestChoices');

var _LatestChoices2 = _interopRequireDefault(_LatestChoices);

var _LatestSections = require('../components/LatestSections');

var _LatestSections2 = _interopRequireDefault(_LatestSections);

var _Leading = require('../components/Leading');

var _Leading2 = _interopRequireDefault(_Leading);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactDom = require('react-dom');

var _reactDom2 = _interopRequireDefault(_reactDom);

var _Sidebar = require('../components/Sidebar');

var _Sidebar2 = _interopRequireDefault(_Sidebar);

var _SystemError = require('../components/SystemError');

var _SystemError2 = _interopRequireDefault(_SystemError);

var _TopNews = require('../components/TopNews');

var _TopNews2 = _interopRequireDefault(_TopNews);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _async = require('async');

var _async2 = _interopRequireDefault(_async);

var _reactCookie = require('react-cookie');

var _reactCookie2 = _interopRequireDefault(_reactCookie);

var _reactGa = require('react-ga');

var _reactGa2 = _interopRequireDefault(_reactGa);

var _reactDfp = require('react-dfp');

var _index = require('../constants/index');

var _reactRedux = require('react-redux');

var _index2 = require('../utils/index');

var _listId = require('../conf/list-id');

var _articles = require('../actions/articles');

var _header = require('../actions/header');

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var MAXRESULT = 10;
var PAGE = 1;

if (process.env.BROWSER) {}

var HomeB = function (_Component) {
  _inherits(HomeB, _Component);

  _createClass(HomeB, null, [{
    key: 'fetchData',
    value: function fetchData(_ref) {
      var store = _ref.store;

      return store.dispatch((0, _articles.fetchIndexArticles)(['choices', 'posts', 'sections', 'sectionfeatured'])).then(function () {
        return store.dispatch((0, _articles.fetchTopics)());
      });
    }
  }]);

  function HomeB(props, context) {
    _classCallCheck(this, HomeB);

    var _this = _possibleConstructorReturn(this, (HomeB.__proto__ || Object.getPrototypeOf(HomeB)).call(this, props, context));

    _this.state = {
      page: PAGE
    };
    _this.loadMore = _this._loadMore.bind(_this);
    return _this;
  }

  _createClass(HomeB, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      _reactGa2.default.initialize(_index.GAID, { debug: __DEVELOPMENT__ });
      _reactGa2.default.pageview(this.props.location.pathname);
      this.props.setPageType(_index.HOME);
      this.props.setPageTitle('', _index.SITE_NAME.FULL);

      _reactDfp.DFPManager.attachSlotRenderEnded(function (id, event) {
        if (id.slotId == 'mm_mobile_hp_320x480_FS' && !id.event.isEmpty) {
          console.log(id);
          if ($(window).width() < 970 && !_reactCookie2.default.load('visited')) {
            _reactCookie2.default.save('visited', true, { path: '/', maxAge: 600 });
            $('.ui.dimmer').dimmer('show');
            $('.ui.dimmer .close').click(function () {
              $('.ui.dimmer').dimmer('hide');
              console.log(_reactCookie2.default.load('visited'));
            });
          }
        }
      });
    }
  }, {
    key: 'componentWillUpdate',
    value: function componentWillUpdate(nextProps) {
      if (nextProps.location.pathname !== this.props.location.pathname) {
        _reactGa2.default.pageview(nextProps.location.pathname);
      }
    }
  }, {
    key: 'componentWillMount',
    value: function componentWillMount() {
      var _props = this.props;
      var fetchArticlesByUuidIfNeeded = _props.fetchArticlesByUuidIfNeeded;
      var fetchIndexArticles = _props.fetchIndexArticles;
      var _props2 = this.props;
      var articlesByUuids = _props2.articlesByUuids;
      var entities = _props2.entities;
      var sectionFeatured = _props2.sectionFeatured;
      var sectionList = _props2.sectionList;
      var choices = _props2.choices;
      var fetchLatestPosts = _props2.fetchLatestPosts;
      var topics = _props2.topics;
      var latestPosts = _props2.latestPosts;


      var checkSectionList = _lodash2.default.get(sectionList, 'fetched', undefined);
      var checkSectionFeatured = _lodash2.default.get(sectionFeatured, 'fetched', undefined);
      var checkChoices = _lodash2.default.get(choices, 'fetched', undefined);
      var checkLatestPosts = _lodash2.default.get(latestPosts, 'fetched', undefined);

      var unfetched = [];

      if (!checkLatestPosts) unfetched.push('posts');
      if (!checkSectionList) unfetched.push('sections');
      if (!checkChoices) unfetched.push('choices');
      if (!checkSectionFeatured) unfetched.push('sectionfeatured');

      if (unfetched.length != 0) {
        this.props.fetchIndexArticles(unfetched);
      }

      this.props.fetchEvent({
        max_results: 1,
        where: {
          isFeatured: true
        }
      });

      if (!_lodash2.default.get(topics, 'fetched', undefined)) {
        this.props.fetchTopics();
      }
    }
  }, {
    key: '_loadMore',
    value: function _loadMore() {
      var _props3 = this.props;
      var fetchLatestPosts = _props3.fetchLatestPosts;
      var latestPosts = _props3.latestPosts;


      var page = this.state.page;

      fetchLatestPosts({
        page: page + 1,
        max_results: MAXRESULT,
        sort: '-publishedDate'
      });

      this.setState({
        page: page + 1
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props4 = this.props;
      var articlesByUuids = _props4.articlesByUuids;
      var entities = _props4.entities;
      var sectionFeatured = _props4.sectionFeatured;
      var sectionList = _props4.sectionList;
      var choices = _props4.choices;
      var latestPosts = _props4.latestPosts;
      var topics = _props4.topics;
      var location = _props4.location;
      var device = this.context.device;


      var event = _lodash2.default.get(this.props.event, ['items', 0]);
      var embed = _lodash2.default.get(event, ['embed']);
      var eventType = _lodash2.default.get(event, ['eventType']);
      var eventPeriod = [_lodash2.default.get(event, ['startDate']), _lodash2.default.get(event, ['endDate'])];
      var image = _lodash2.default.get(event, ['image']);
      var isFeatured = _lodash2.default.get(event, ['isFeatured']);
      var video = _lodash2.default.get(event, ['video']);

      var sections = sectionFeatured;
      // let choicesPosts = _.filter(entities.articles, (v,k)=>{ return _.indexOf(choices.items, k) > -1 })
      var posts = _lodash2.default.filter(entities.articles, function (v, k) {
        return _lodash2.default.indexOf(latestPosts.items, k) > -1;
      });

      var sectionListResponse = _lodash2.default.get(sectionList, 'response', {});

      var meta = {
        title: _index.SITE_NAME.FULL,
        description: _index.SITE_META.DESC,
        canonical: _index.SITE_META.URL,
        meta: { property: {} },
        auto: { ograph: true }
      };

      if (posts) {
        return _react2.default.createElement(
          _reactDfp.DFPSlotsProvider,
          { dfpNetworkId: _index.DFPID },
          _react2.default.createElement(
            _reactDocumentMeta2.default,
            meta,
            _react2.default.createElement(_Sidebar2.default, { sectionList: sectionListResponse, topics: topics, pathName: location.pathname }),
            _react2.default.createElement(_HeaderB2.default, { sectionList: sectionListResponse, topics: topics, pathName: location.pathname }),
            _react2.default.createElement(
              'div',
              { className: 'ui dimmer' },
              _react2.default.createElement(
                'div',
                { className: 'content', style: { height: '480px', width: '320px', position: 'fixed', top: 'calc(50% - 240px)', left: 'calc(50% - 160px)' } },
                _react2.default.createElement(
                  'div',
                  { className: 'close', style: { top: '-16px', right: '0', position: 'absolute', 'zIndex': '9999' } },
                  _react2.default.createElement('div', { style: { background: 'url(/asset/close.png) center center no-repeat', backgroundSize: 'cover', width: '32px', height: '32px' } })
                ),
                _react2.default.createElement(
                  'div',
                  { className: 'center' },
                  _react2.default.createElement(_reactDfp.AdSlot, { sizes: [[320, 480]],
                    dfpNetworkId: _index.DFPID,
                    slotId: 'mm_mobile_hp_320x480_FS',
                    adUnit: 'mm_mobile_hp_320x480_FS',
                    sizeMapping: [{ viewport: [1, 1], sizes: [[320, 480]] }, { viewport: [970, 200], sizes: [] }]
                  })
                )
              )
            ),
            _react2.default.createElement(
              'div',
              { id: 'main', className: 'pusher' },
              _react2.default.createElement(
                'div',
                { style: { margin: '0 auto', 'marginBottom': '20px', 'maxWidth': '970px' } },
                _react2.default.createElement(_reactDfp.AdSlot, { sizes: [[970, 90], [970, 250]],
                  dfpNetworkId: _index.DFPID,
                  slotId: 'mm_pc_hp_970x250_HD',
                  adUnit: 'mm_pc_hp_970x250_HD',
                  sizeMapping: [{ viewport: [0, 0], sizes: [] }, { viewport: [970, 200], sizes: [[970, 90], [970, 250]] }]
                })
              ),
              _react2.default.createElement(
                'div',
                { style: { margin: '0 auto', 'marginBottom': '20px', 'maxWidth': '320px' } },
                _react2.default.createElement(_reactDfp.AdSlot, { sizes: [[320, 100]],
                  dfpNetworkId: _index.DFPID,
                  slotId: 'mm_mobile_hp_320x100_HD',
                  adUnit: 'mm_mobile_hp_320x100_HD',
                  sizeMapping: [{ viewport: [1, 1], sizes: [[320, 100], [300, 250]] }, { viewport: [970, 200], sizes: [] }]
                })
              ),
              _react2.default.createElement(_Leading2.default, { leading: eventType, mediaSource: { 'heroImage': image, 'heroVideo': video, 'embed': embed, 'eventPeriod': eventPeriod, 'flag': 'event', 'isFeatured': isFeatured }, device: this.context.device }),
              _react2.default.createElement(_LatestChoices2.default, {
                articles: entities.articles,
                categories: entities.categories,
                choices: _lodash2.default.get(choices, 'items', [])
              }),
              _react2.default.createElement(_LatestArticles2.default, {
                articles: posts,
                categories: entities.categories,
                authors: entities.authors,
                title: "最新文章",
                hasMore: _lodash2.default.get(latestPosts, ['items', 'length'], 0) < _lodash2.default.get(latestPosts, ['meta', 'total'], 0),
                loadMore: this.loadMore
              }),
              _react2.default.createElement(
                'div',
                { style: { margin: '20px auto', 'maxWidth': '970px' } },
                _react2.default.createElement(_reactDfp.AdSlot, { sizes: [[970, 90]],
                  dfpNetworkId: _index.DFPID,
                  slotId: 'mm_pc_hp_970x90_FT',
                  adUnit: 'mm_pc_hp_970x90_FT',
                  sizeMapping: [{ viewport: [0, 0], sizes: [] }, { viewport: [970, 200], sizes: [[970, 90], [970, 250], [300, 250]] }]
                })
              ),
              _react2.default.createElement(
                'div',
                { style: { margin: '20px auto', 'maxWidth': '320px' } },
                _react2.default.createElement(_reactDfp.AdSlot, { sizes: [[320, 100]],
                  dfpNetworkId: _index.DFPID,
                  slotId: 'mm_mobile_hp_320x100_FT',
                  adUnit: 'mm_mobile_hp_320x100_FT',
                  sizeMapping: [{ viewport: [1, 1], sizes: [[320, 100], [300, 250]] }, { viewport: [970, 200], sizes: [] }]
                })
              ),
              _react2.default.createElement(_Footer2.default, { sectionList: sectionListResponse })
            )
          )
        );
      } else {
        return _react2.default.createElement(_SystemError2.default, null);
      }
    }
  }]);

  return HomeB;
}(_react.Component);

function mapStateToProps(state) {
  return {
    articlesByUuids: state.articlesByUuids || {},
    choices: state.choices || {},
    entities: state.entities || {},
    event: state.event || {},
    indexArticles: state.indexArticles || {},
    latestPosts: state.latestPosts || {},
    sectionList: state.sectionList || {},
    sectionFeatured: state.sectionFeatured || {},
    topics: state.topics || {}
  };
}

HomeB.contextTypes = {
  device: _react2.default.PropTypes.string
};

exports.HomeB = HomeB;
exports.default = (0, _reactRedux.connect)(mapStateToProps, {
  fetchArticlesByUuidIfNeeded: _articles.fetchArticlesByUuidIfNeeded,
  fetchEvent: _articles.fetchEvent,
  fetchIndexArticles: _articles.fetchIndexArticles,
  fetchLatestPosts: _articles.fetchLatestPosts,
  fetchTopics: _articles.fetchTopics,
  setPageType: _header.setPageType,
  setPageTitle: _header.setPageTitle
})(HomeB);