import "choerodon-ui/pro/lib/form/style";
import _Form from "@hzero-front-ui/c7n-ui/lib/FormPro";
import "choerodon-ui/pro/lib/select/style";
import _Select from "choerodon-ui/pro/lib/select";

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 React, { Fragment, useState, useEffect, useCallback } from 'react';
import { withRouter } from 'react-router-dom';
import { observer } from 'mobx-react-lite';
import { injectIntl, FormattedMessage } from 'react-intl';
import { Page, Header, Content, Breadcrumb } from '@choerodon/boot';
import _ from 'lodash';
import moment from 'moment';
import HeaderButtons from "../Component/HeaderButtons";
import ChartSwitch from "../Component/ChartSwitch";
import LineChart from "./LineChart";
import CommitHistory from "./CommitHistory";
import TimePicker from "../Component/TimePicker";
import NoChart from "../Component/NoChart";
import MaxTagPopover from "../Component/MaxTagPopover";
import "./Submission.less";
import "../../main.less";
import LoadingBar from "../../../components/loading";
import { useReportsStore } from "../stores";
import { useSubmissionStore } from "./stores";
/**
 * 将数据转为图表可用格式
 * @param data
 * @returns {{total, user: Array}}
 */

var Option = _Select.Option;
var Submission = observer(function () {
  var _useReportsStore = useReportsStore(),
      formatMessage = _useReportsStore.intl.formatMessage,
      AppState = _useReportsStore.AppState,
      ReportsStore = _useReportsStore.ReportsStore,
      _useReportsStore$Repo = _useReportsStore.ReportsStore,
      getProRole = _useReportsStore$Repo.getProRole,
      getAllApps = _useReportsStore$Repo.getAllApps,
      getCommits = _useReportsStore$Repo.getCommits,
      getCommitsRecord = _useReportsStore$Repo.getCommitsRecord,
      getCommitLoading = _useReportsStore$Repo.getCommitLoading,
      getIsRefresh = _useReportsStore$Repo.getIsRefresh,
      getHistoryLoad = _useReportsStore$Repo.getHistoryLoad,
      loadAllApps = _useReportsStore$Repo.loadAllApps,
      loadCommits = _useReportsStore$Repo.loadCommits,
      loadCommitsRecord = _useReportsStore$Repo.loadCommitsRecord,
      changeIsRefresh = _useReportsStore$Repo.changeIsRefresh,
      history = _useReportsStore.history,
      _useReportsStore$hist = _useReportsStore.history.location,
      state = _useReportsStore$hist.state,
      search = _useReportsStore$hist.search;

  var _useSubmissionStore = useSubmissionStore(),
      SubmissionSelectDataSet = _useSubmissionStore.SubmissionSelectDataSet;

  var _useState = useState(null),
      _useState2 = _slicedToArray(_useState, 2),
      appId = _useState2[0],
      setAppId = _useState2[1];

  var _useState3 = useState(1),
      _useState4 = _slicedToArray(_useState3, 2),
      page = _useState4[0],
      setPage = _useState4[1];

  var _useState5 = useState('seven'),
      _useState6 = _slicedToArray(_useState5, 2),
      dateType = _useState6[0],
      setDateType = _useState6[1];

  var _useState7 = useState(null),
      _useState8 = _slicedToArray(_useState7, 2),
      index = _useState8[0],
      setIndex = _useState8[1];

  var record = SubmissionSelectDataSet.current;
  useEffect(function () {
    ReportsStore.changeIsRefresh(true);
    loadData();
    return function () {
      ReportsStore.setAllApps([]);
      ReportsStore.setCommits({});
      ReportsStore.setCommitsRecord([]);
      ReportsStore.setStartTime(moment().subtract(6, 'days'));
      ReportsStore.setEndTime(moment());
      ReportsStore.setStartDate(null);
      ReportsStore.setEndDate(null);
    };
  }, []);
  useEffect(function () {
    record.set('apps', appId);
  }, [appId]);

  var handleRefresh = function handleRefresh() {
    return loadData();
  };

  var handleBack = useCallback(function () {
    history.push(backPath || "/devops/charts/develop".concat(search));
  }, [backPath, search]);

  function formatData(data) {
    var totalCommitsDate = data.totalCommitsDate,
        commitFormUserVOList = data.commitFormUserVOList;
    var total = {};
    var user = [];

    if (totalCommitsDate && commitFormUserVOList) {
      // total.items = _.countBy(totalCommitsDate, item => item.slice(0, 10));
      total.items = totalCommitsDate.slice();
      total.count = totalCommitsDate.length;

      _.forEach(commitFormUserVOList, function (item) {
        var name = item.name,
            imgUrl = item.imgUrl,
            commitDates = item.commitDates,
            id = item.id;
        var userTotal = {
          name: name,
          avatar: imgUrl
        };
        userTotal.id = id; // userTotal.items = _.countBy(commitDates, cit => cit.slice(0, 10));

        userTotal.items = commitDates.slice();
        userTotal.count = commitDates.length;
        user.push(userTotal);
      });
    }

    return {
      total: total,
      user: user
    };
  }
  /**
   * 应用选择
   * @param e
   */


  var handleSelect = function handleSelect(e) {
    if (e.length === 0) {
      ReportsStore.setAllApps([]);
      ReportsStore.setCommits({});
      ReportsStore.setCommitsRecord([]);
    } else {
      var projectId = AppState.currentMenuType.id;
      var startTime = ReportsStore.getStartTime.format('YYYY-MM-DD HH:mm:ss');
      var endTime = ReportsStore.getEndTime.format('YYYY-MM-DD HH:mm:ss');
      setAppId(e);
      loadCommits(projectId, startTime, endTime, e);
      loadCommitsRecord(projectId, startTime, endTime, e, 1);
    }
  };

  var handlePageChange = function handlePageChange(pageCurrent) {
    var projectId = AppState.currentMenuType.id;
    var startTime = ReportsStore.getStartTime.format('YYYY-MM-DD HH:mm:ss');
    var endTime = ReportsStore.getEndTime.format('YYYY-MM-DD HH:mm:ss');
    setPage(pageCurrent);
    loadCommitsRecord(projectId, startTime, endTime, appId, pageCurrent);
  };

  var loadData = function loadData() {
    var repoAppId = [];

    if (state && state.appId) {
      repoAppId = state.appId;
    }

    var projectId = AppState.currentMenuType.id;
    var startTime = ReportsStore.getStartTime.format('YYYY-MM-DD HH:mm:ss');
    var endTime = ReportsStore.getEndTime.format('YYYY-MM-DD HH:mm:ss');
    changeIsRefresh(true);
    loadAllApps(projectId).then(function (data) {
      changeIsRefresh(false);
      var appData = data;

      if (appData.length) {
        var selectApp = appId || _.map(appData, function (item) {
          return item.id;
        });

        if (!appId) {
          if (repoAppId.length) {
            selectApp = repoAppId;
          }

          setAppId(selectApp);
        }

        loadCommits(projectId, startTime, endTime, selectApp);
        loadCommitsRecord(projectId, startTime, endTime, selectApp, page);
      } else {
        ReportsStore.judgeRole(['choerodon.code.project.develop.app-service.ps.create']);
      }
    });
  };

  function handleRefreshChartByTimePicker() {
    var projectId = AppState.currentMenuType.id;
    var startTime = ReportsStore.getStartTime.format('YYYY-MM-DD HH:mm:ss');
    var endTime = ReportsStore.getEndTime.format('YYYY-MM-DD HH:mm:ss');
    loadCommits(projectId, startTime, endTime, appId);
    loadCommitsRecord(projectId, startTime, endTime, appId, index);
  }
  /**
   * 选择今天、近7天和近30天的选项，当使用DatePick的时候清空type
   * @param type 时间范围类型
   */


  var handleDateChoose = function handleDateChoose(type) {
    setDateType(type);
  };

  var maxTagNode = function maxTagNode(data, value) {
    return /*#__PURE__*/React.createElement(MaxTagPopover, {
      dataSource: data,
      value: value
    });
  };

  var backPath = state && state.backPath;
  var _AppState$currentMenu = AppState.currentMenuType,
      id = _AppState$currentMenu.id,
      name = _AppState$currentMenu.name,
      type = _AppState$currentMenu.type,
      organizationId = _AppState$currentMenu.organizationId;

  var _formatData = formatData(getCommits),
      total = _formatData.total,
      user = _formatData.user;

  var options = _.map(getAllApps, function (item) {
    return /*#__PURE__*/React.createElement(Option, {
      key: item.id,
      value: item.id
    }, item.name);
  });

  var personChart = _.map(user, function (item) {
    return /*#__PURE__*/React.createElement("div", {
      key: item.id,
      className: "c7n-report-submission-item"
    }, /*#__PURE__*/React.createElement(LineChart, {
      languageType: "report",
      loading: getCommitLoading,
      name: item.name || 'Unknown',
      color: "#ff9915",
      style: {
        width: '100%',
        height: 176
      },
      data: item,
      start: ReportsStore.getStartTime,
      end: ReportsStore.getEndTime,
      hasAvatar: true
    }));
  });

  var content = getAllApps.length ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    className: "c7n-report-control c7n-report-select"
  }, /*#__PURE__*/React.createElement(_Form, {
    dataSet: SubmissionSelectDataSet,
    className: "c7n-report-control-select"
  }, /*#__PURE__*/React.createElement(_Select, {
    name: "apps",
    searchable: true,
    placeholder: formatMessage({
      id: 'report.app.noselect'
    }),
    maxTagCount: 3,
    maxTagPlaceholder: function maxTagPlaceholder(omittedValues) {
      return maxTagNode(getAllApps, omittedValues);
    },
    onChange: handleSelect
  }, options)), /*#__PURE__*/React.createElement(TimePicker, {
    unlimit: true,
    startTime: ReportsStore.getStartDate,
    endTime: ReportsStore.getEndDate,
    func: handleRefreshChartByTimePicker,
    store: ReportsStore,
    type: dateType,
    onChange: handleDateChoose
  })), /*#__PURE__*/React.createElement("div", {
    className: "c7n-report-submission clearfix"
  }, /*#__PURE__*/React.createElement("div", {
    className: "c7n-report-submission-overview"
  }, /*#__PURE__*/React.createElement(LineChart, {
    languageType: "report",
    loading: getCommitLoading,
    name: "\u63D0\u4EA4\u60C5\u51B5",
    color: "#4677dd",
    style: {
      width: '100%',
      height: 276
    },
    data: total,
    hasAvatar: false,
    start: ReportsStore.getStartTime,
    end: ReportsStore.getEndTime
  })), /*#__PURE__*/React.createElement("div", {
    className: "c7n-report-submission-history"
  }, /*#__PURE__*/React.createElement(CommitHistory, {
    loading: getHistoryLoad,
    onPageChange: handlePageChange,
    dataSource: getCommitsRecord
  }))), /*#__PURE__*/React.createElement("div", {
    className: "c7n-report-submission-wrap clearfix"
  }, personChart)) : /*#__PURE__*/React.createElement(NoChart, {
    getProRole: getProRole,
    type: "app"
  });
  return /*#__PURE__*/React.createElement(Page, {
    className: "c7n-region"
  }, /*#__PURE__*/React.createElement(Header, {
    title: formatMessage({
      id: 'report.submission.head'
    })
  }, /*#__PURE__*/React.createElement(HeaderButtons, {
    refresh: handleRefresh,
    backPath: backPath,
    reportKey: "submission",
    reportType: "develop"
  })), /*#__PURE__*/React.createElement(Breadcrumb, {
    title: formatMessage({
      id: 'report.submission.head'
    })
  }), /*#__PURE__*/React.createElement(Content, null, getIsRefresh ? /*#__PURE__*/React.createElement(LoadingBar, {
    display: "getIsRefresh"
  }) : content));
});
export default withRouter(injectIntl(Submission));