import "choerodon-ui/pro/lib/spin/style";
import _Spin from "choerodon-ui/pro/lib/spin";
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; }

/* eslint-disable max-len */
import React, { useState, useEffect } from 'react';
import { observer } from 'mobx-react-lite';
import { injectIntl, FormattedMessage } from 'react-intl';
import { Page, Header, Content, Breadcrumb } from '@choerodon/boot';
import ReactEcharts from 'echarts-for-react';
import _ from 'lodash';
import moment from 'moment';
import LoadingBar from "../../../components/loading";
import HeaderButtons from "../Component/HeaderButtons";
import TimePicker from "../Component/TimePicker";
import NoChart from "../Component/NoChart";
import BuildTable from "../BuildNumber/BuildTable/BuildTable";
import "./BuildDuration.less";
import { useReportsStore } from "../stores";
import { useBuildDurationStore } from "./stores";
var Option = _Select.Option;
var BuildDuration = observer(function () {
  var _useReportsStore = useReportsStore(),
      AppState = _useReportsStore.AppState,
      ReportsStore = _useReportsStore.ReportsStore,
      history = _useReportsStore.history,
      formatMessage = _useReportsStore.intl.formatMessage,
      search = _useReportsStore.location.search;

  var _useBuildDurationStor = useBuildDurationStore(),
      BuildDurationSelectDataSet = _useBuildDurationStor.BuildDurationSelectDataSet;

  var record = BuildDurationSelectDataSet.current;

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

  useEffect(function () {
    ReportsStore.changeIsRefresh(true);
    loadDatas();
    return function () {
      ReportsStore.setAllData([]);
      ReportsStore.setBuildDuration({});
      ReportsStore.setStartTime(moment().subtract(6, 'days'));
      ReportsStore.setEndTime(moment());
      ReportsStore.setAppId(null);
      ReportsStore.setPageInfo({
        pageNum: 1,
        total: 0,
        pageSize: 10
      });
      ReportsStore.setStartDate();
      ReportsStore.setEndDate();
      ReportsStore.setAllApps([]);
    };
  }, []);
  useEffect(function () {
    record.set('buildDurationApps', ReportsStore.getAppId);
  }, [ReportsStore.getAppId]);
  /**
   * 加载数据
   */

  var loadDatas = function loadDatas() {
    var id = AppState.currentMenuType.id;
    ReportsStore.loadAllApps(id).then(function (data) {
      if (data && data.length) {
        ReportsStore.setAppId(data[0].id);
        loadCharts();
      } else {
        ReportsStore.judgeRole(['choerodon.code.project.develop.app-service.ps.create']);
      }
    });
  };
  /**
   * 刷新
   */


  var handleRefresh = function handleRefresh() {
    var id = AppState.currentMenuType.id;
    var pageInfo = ReportsStore.pageInfo;
    ReportsStore.loadAllApps(id);
    loadCharts(pageInfo);
  };
  /**
   * 选择应用
   * @param value
   */


  var handleAppSelect = function handleAppSelect(value) {
    ReportsStore.setAppId(value);
    loadCharts();
  };
  /**
   * 图表函数
   */


  function getOption() {
    var _ReportsStore$getBuil = ReportsStore.getBuildDuration,
        pipelineTime = _ReportsStore$getBuil.pipelineTime,
        refs = _ReportsStore$getBuil.refs,
        versions = _ReportsStore$getBuil.versions,
        createDates = _ReportsStore$getBuil.createDates;
    var averageDuration = [];
    averageDuration.length = pipelineTime && pipelineTime.length ? pipelineTime.length : 0;
    var ava = pipelineTime && pipelineTime.length ? _.reduce(pipelineTime, function (sum, n) {
      return sum + parseFloat(n);
    }, 0) / pipelineTime.length : 0;

    _.fill(averageDuration, ava);

    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'none'
        },
        backgroundColor: 'rgba(0,0,0,0.75)',
        textStyle: {
          color: '#fff'
        },
        padding: [10, 15],
        extraCssText: 'box-shadow: 0px 2px 8px 0px rgba(0,0,0,0.12);padding:15px 17px',
        formatter: function formatter(params, ticket) {
          var version = versions[params[0].dataIndex] ? "".concat(versions[params[0].dataIndex]) : "".concat(formatMessage({
            id: 'report.build-duration.noversion'
          }));
          var time = params[0].value;

          if (time.split('.')[1] === '00') {
            time = "".concat(time.toString().split('.')[0]).concat(formatMessage({
              id: 'minutes'
            }));
          } else if (time.split('.')[0] === '0') {
            time = "".concat((Number(time.toString().split('.')[1]) * 0.6).toFixed()).concat(formatMessage({
              id: 'seconds'
            }));
          } else if (time.split('.').length === 2) {
            time = "".concat(time.toString().split('.')[0]).concat(formatMessage({
              id: 'minutes'
            })).concat((Number(time.toString().split('.')[1]) * 0.6).toFixed()).concat(formatMessage({
              id: 'seconds'
            }));
          } else {
            time = null;
          }

          return "<div>\n            <div>".concat(formatMessage({
            id: 'ist.time'
          }), "\uFF1A").concat(createDates[params[0].dataIndex], "</div>\n            <div>").concat(formatMessage({
            id: 'network.column.version'
          }), "\uFF1A").concat(version, "</div>\n            <div>").concat(formatMessage({
            id: 'report.build-duration.duration'
          }), "\uFF1A").concat(time, "</div>\n          </div>");
        }
      },
      grid: {
        left: '2%',
        right: '3%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        axisTick: {
          show: false
        },
        axisLine: {
          lineStyle: {
            color: '#eee',
            type: 'solid',
            width: 2
          }
        },
        axisLabel: {
          margin: 13,
          textStyle: {
            color: 'rgba(0, 0, 0, 0.65)',
            fontSize: 12
          },
          rotate: 40,
          formatter: function formatter(value) {
            return "".concat(value.substr(0, value.indexOf('-') + 5));
          }
        },
        splitLine: {
          lineStyle: {
            color: ['#eee'],
            width: 1,
            type: 'solid'
          }
        },
        data: refs
      },
      yAxis: {
        name: "".concat(formatMessage({
          id: 'minTime'
        })),
        type: 'value',
        nameTextStyle: {
          fontSize: 13,
          color: '#000'
        },
        axisTick: {
          show: false
        },
        axisLine: {
          lineStyle: {
            color: '#eee',
            type: 'solid',
            width: 2
          }
        },
        axisLabel: {
          margin: 19.3,
          textStyle: {
            color: 'rgba(0, 0, 0, 0.65)',
            fontSize: 12
          }
        },
        splitLine: {
          lineStyle: {
            color: '#eee',
            type: 'solid',
            width: 1
          }
        },
        min: pipelineTime && pipelineTime.length ? null : 0,
        max: pipelineTime && pipelineTime.length ? null : 4
      },
      series: [{
        type: 'bar',
        barWidth: '30%',
        itemStyle: {
          color: 'rgba(77, 144, 254, 0.60)',
          borderColor: '#4D90FE',
          emphasis: {
            shadowBlur: 10,
            shadowColor: 'rgba(0,0,0,0.20)'
          }
        },
        data: pipelineTime
      }, {
        type: 'line',
        symbol: 'none',
        lineStyle: {
          color: 'rgba(0, 0, 0, 0.36)',
          width: 2,
          type: 'dashed',
          border: '1px solid #4D90FE'
        },
        data: averageDuration
      }]
    };
  }

  var loadCharts = function loadCharts(pageInfo) {
    var projectId = AppState.currentMenuType.id;
    var appId = ReportsStore.getAppId;
    var startTime = ReportsStore.getStartTime.format('YYYY-MM-DD HH:mm:ss');
    var endTime = ReportsStore.getEndTime.format('YYYY-MM-DD HH:mm:ss');
    ReportsStore.loadBuildDuration(projectId, appId, startTime, endTime);

    if (pageInfo) {
      ReportsStore.loadBuildTable(projectId, appId, startTime, endTime, pageInfo.current, pageInfo.pageSize);
    } else {
      ReportsStore.loadBuildTable(projectId, appId, startTime, endTime);
    }
  };

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

  var _AppState$currentMenu = AppState.currentMenuType,
      id = _AppState$currentMenu.id,
      name = _AppState$currentMenu.name,
      type = _AppState$currentMenu.type,
      organizationId = _AppState$currentMenu.organizationId;
  var getAllApps = ReportsStore.getAllApps,
      appId = ReportsStore.appId,
      echartsLoading = ReportsStore.echartsLoading,
      isRefresh = ReportsStore.isRefresh;
  var content = getAllApps && getAllApps.length ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    className: "c7n-buildDuration-select"
  }, /*#__PURE__*/React.createElement(_Form, {
    dataSet: BuildDurationSelectDataSet,
    className: "c7n-app-select_247"
  }, /*#__PURE__*/React.createElement(_Select, {
    name: "buildDurationApps" // defaultValue={appId}
    // value={appId}
    ,
    searchable: true,
    optionFilterProp: "children",
    filterOption: function filterOption(input, option) {
      return option.props.children.props.children.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    filter: true,
    onChange: handleAppSelect,
    clearButton: false
  }, _.map(getAllApps, function (app, index) {
    return /*#__PURE__*/React.createElement(Option, {
      value: app.id,
      key: index
    }, app.name);
  }))), /*#__PURE__*/React.createElement(TimePicker, {
    startTime: ReportsStore.getStartDate,
    endTime: ReportsStore.getEndDate,
    func: loadCharts,
    type: dateType,
    onChange: handleDateChoose,
    store: ReportsStore
  })), /*#__PURE__*/React.createElement(_Spin, {
    spinning: echartsLoading
  }, /*#__PURE__*/React.createElement(ReactEcharts, {
    className: "c7n-buildDuration-echarts",
    option: getOption()
  })), /*#__PURE__*/React.createElement(BuildTable, null)) : /*#__PURE__*/React.createElement(NoChart, {
    getProRole: ReportsStore.getProRole,
    type: "app"
  });
  return /*#__PURE__*/React.createElement(Page, {
    className: "c7n-region c7n-ciPipeline"
  }, /*#__PURE__*/React.createElement(Header, {
    title: formatMessage({
      id: 'report.build-duration.head'
    })
  }, /*#__PURE__*/React.createElement(HeaderButtons, {
    refresh: handleRefresh,
    reportKey: "build-duration",
    reportType: "develop"
  })), /*#__PURE__*/React.createElement(Breadcrumb, {
    title: formatMessage({
      id: 'report.build-duration.head'
    })
  }), /*#__PURE__*/React.createElement(Content, {
    className: "c7n-buildDuration-content"
  }, isRefresh ? /*#__PURE__*/React.createElement(LoadingBar, {
    display: isRefresh
  }) : content));
});
export default injectIntl(BuildDuration);