import "choerodon-ui/lib/spin/style";
import _Spin from "@hzero-front-ui/c7n-ui/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";
import "choerodon-ui/pro/lib/tooltip/style";
import _Tooltip from "choerodon-ui/pro/lib/tooltip";
import "choerodon-ui/lib/breadcrumb/style";
import _Breadcrumb from "choerodon-ui/lib/breadcrumb";

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, { useState, useEffect } from 'react';
import { observer } from 'mobx-react-lite';
import { Link, withRouter } from 'react-router-dom';
import { Page, Header, Content, Breadcrumb } from '@choerodon/boot';
import { HeaderButtons } from '@choerodon/master';
import ReactEcharts from 'echarts-for-react';
import map from 'lodash/map';
import moment from 'moment';
import ChartSwitch from "../Component/ChartSwitch";
import TimePicker from "../Component/TimePicker";
import NoChart from "../Component/NoChart";
import LoadingBar from "../../../components/loading";
import { useReportsStore } from "../stores";
import { useCodeQualityStore } from "./stores";
import "./index.less";
var Item = _Breadcrumb.Item;
var OBJECT_TYPE = {
  issue: [{
    name: 'bugs',
    color: '#5266d4'
  }, {
    name: 'codeSmells',
    color: '#2196f3'
  }, {
    name: 'vulnerabilities',
    color: '#00bcd4'
  }],
  coverage: [{
    name: 'linesToCover',
    color: '#2196f3'
  }, {
    name: 'coverLines',
    color: '#00bcd4'
  }],
  duplicate: [{
    name: 'nclocs',
    color: '#2196f3'
  }, {
    name: 'duplicatedLines',
    color: '#00bcd4'
  }]
};
var CodeQuality = withRouter(observer(function () {
  var _useReportsStore = useReportsStore(),
      ReportsStore = _useReportsStore.ReportsStore,
      _useReportsStore$Repo = _useReportsStore.ReportsStore,
      isRefresh = _useReportsStore$Repo.isRefresh,
      getProRole = _useReportsStore$Repo.getProRole;

  var _useCodeQualityStore = useCodeQualityStore(),
      _useCodeQualityStore$ = _useCodeQualityStore.AppState.currentMenuType,
      projectId = _useCodeQualityStore$.projectId,
      name = _useCodeQualityStore$.name,
      formatMessage = _useCodeQualityStore.intl.formatMessage,
      history = _useCodeQualityStore.history,
      search = _useCodeQualityStore.location.search,
      detailDs = _useCodeQualityStore.detailDs,
      appServiceDs = _useCodeQualityStore.appServiceDs,
      chartsDs = _useCodeQualityStore.chartsDs,
      backPath = _useCodeQualityStore.backPath,
      permissions = _useCodeQualityStore.permissions;

  var record = detailDs.current;

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

  useEffect(function () {
    ReportsStore.changeIsRefresh(true);
    return function () {
      ReportsStore.setStartTime(moment().subtract(6, 'days'));
      ReportsStore.setEndTime(moment());
      ReportsStore.setStartDate();
      ReportsStore.setEndDate();
    };
  }, []);

  function loadCharts() {
    var getStartTime = ReportsStore.getStartTime,
        getEndTime = ReportsStore.getEndTime,
        getAppId = ReportsStore.getAppId;
    var startTime = getStartTime.format('YYYY-MM-DD HH:mm:ss');
    var endTime = getEndTime.format('YYYY-MM-DD HH:mm:ss');
    chartsDs.setQueryParameter('startTime', startTime);
    chartsDs.setQueryParameter('endTime', endTime);
    chartsDs.query();
  }

  function handleRefresh() {
    appServiceDs.query();
    chartsDs.query();
  }
  /**
   * 选择时间
   * @param type
   */


  function handleDateChoose(value) {
    setDateType(value);
  }
  /**
   * 图表函数
   */


  function getOption() {
    var getCodeQuality = chartsDs.current ? chartsDs.current.toData() : {};
    var objectType = record.get('objectType');
    var series = [];
    var legend = [];
    var dates = getCodeQuality.dates || [];
    map(OBJECT_TYPE[objectType], function (_ref) {
      var objectName = _ref.name,
          color = _ref.color;

      if (getCodeQuality[objectName]) {
        series.push({
          name: formatMessage({
            id: "report.code-quality.".concat(objectName)
          }),
          type: 'line',
          symbol: 'circle',
          showSymbol: false,
          itemStyle: {
            color: color
          },
          data: map(dates, function (item, index) {
            return [item, getCodeQuality[objectName][index]];
          })
        });
        legend.push({
          name: formatMessage({
            id: "report.code-quality.".concat(name)
          }),
          icon: 'line'
        });
      }
    });
    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line'
        },
        backgroundColor: 'rgba(0,0,0,0.75)',
        textStyle: {
          color: '#fff'
        },
        extraCssText: '0px 2px 8px 0px rgba(0,0,0,0.12);padding:15px 17px',
        formatter: function formatter(params) {
          var percent = (params[1].value[1] / (params[0].value[1] * 100)).toFixed(1);
          var list = map(params, function (_ref2) {
            var color = _ref2.color,
                value = _ref2.value,
                seriesName = _ref2.seriesName;
            return "<div>\n              <span style=\"display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:".concat(color, ";\"></span>\n              <span>").concat(seriesName, "\uFF1A").concat(value[1], "</span>\n            </div>");
          });
          return "<div>\n            <div><span>".concat(formatMessage({
            id: 'report.date'
          }), "\uFF1A").concat(params[0].value[0].split('+')[0].replace(/T/g, ' '), "</span></div>\n    ").concat(objectType !== 'issue' ? "<div><span>".concat(formatMessage({
            id: "report.code-quality.type.".concat(objectType)
          }), "\uFF1A").concat(percent, "%</span></div>") : '', "\n            ").concat(list.join(''), "\n          </div>");
        }
      },
      legend: {
        data: legend,
        left: 'right',
        itemGap: 40,
        itemWidth: 34,
        selectedMode: false,
        padding: [5, 10, 5, 0]
      },
      grid: {
        left: 'left',
        right: 10,
        bottom: '3%',
        containLabel: true
      },
      dataZoom: [{
        startValue: dates[0]
      }, {
        type: 'inside'
      }],
      xAxis: {
        type: 'time',
        axisTick: {
          show: false
        },
        axisLine: {
          lineStyle: {
            color: '#eee',
            type: 'solid',
            width: 2
          }
        },
        axisLabel: {
          margin: 13,
          textStyle: {
            color: 'rgba(0, 0, 0, 0.65)',
            fontSize: 12
          },
          align: 'right'
        },
        splitLine: {
          lineStyle: {
            color: ['#eee'],
            width: 1,
            type: 'solid'
          }
        }
      },
      yAxis: {
        name: formatMessage({
          id: objectType === 'issue' ? 'report.code-quality.number' : 'report.code-quality.rows'
        }),
        type: 'value',
        nameTextStyle: {
          fontSize: 13,
          color: '#000',
          padding: dates && dates.length ? null : [0, 0, 0, 25]
        },
        axisTick: {
          show: false
        },
        axisLine: {
          lineStyle: {
            color: '#eee',
            type: 'solid',
            width: 2
          }
        },
        axisLabel: {
          margin: 13,
          textStyle: {
            color: 'rgba(0, 0, 0, 0.65)',
            fontSize: 12
          }
        },
        splitLine: {
          lineStyle: {
            color: '#eee',
            type: 'solid',
            width: 1
          }
        },
        min: dates && dates.length ? null : 0,
        max: dates && dates.length ? null : 4,
        scale: true
      },
      series: series
    };
  }

  function renderAppServiceOption(_ref3) {
    var appServiceRecord = _ref3.record,
        text = _ref3.text;
    return /*#__PURE__*/React.createElement(_Tooltip, {
      title: appServiceRecord.get('code')
    }, text);
  }

  function getContent() {
    var getStartDate = ReportsStore.getStartDate,
        getEndDate = ReportsStore.getEndDate;
    return appServiceDs.length ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
      className: "c7n-codeQuality-select"
    }, /*#__PURE__*/React.createElement(_Form, {
      dataSet: detailDs,
      columns: 2,
      style: {
        width: '5.7rem'
      }
    }, /*#__PURE__*/React.createElement(_Select, {
      name: "appServiceId",
      searchable: true,
      optionRenderer: renderAppServiceOption,
      className: "c7ncd-codeQuality-select-item",
      clearButton: false
    }), /*#__PURE__*/React.createElement(_Select, {
      name: "objectType",
      clearButton: false,
      className: "c7ncd-codeQuality-select-item"
    })), /*#__PURE__*/React.createElement(TimePicker, {
      startTime: getStartDate,
      endTime: getEndDate,
      func: loadCharts,
      type: dateType,
      onChange: handleDateChoose,
      store: ReportsStore
    })), /*#__PURE__*/React.createElement(_Spin, {
      spinning: chartsDs.status === 'loading'
    }, /*#__PURE__*/React.createElement(ReactEcharts, {
      className: "c7n-codeQuality-charts",
      option: getOption(),
      notMerge: true,
      lazyUpdate: true
    }))) : /*#__PURE__*/React.createElement(NoChart, {
      type: "app",
      getProRole: getProRole
    });
  }

  if (!record) {
    return /*#__PURE__*/React.createElement(LoadingBar, {
      display: true
    });
  }

  return /*#__PURE__*/React.createElement(Page, {
    className: "c7n-region c7n-report-codeQuality-wrapper",
    service: permissions
  }, /*#__PURE__*/React.createElement(Header, {
    title: formatMessage({
      id: 'report.code-quality.head'
    }),
    backPath: function () {
      var params = new URLSearchParams(search);

      if (params.get('from') === 'ci') {
        params["delete"]('from');
        return "/devops/pipeline-manage?".concat(params.toString());
      }

      return "".concat(backPath).concat(search);
    }()
  }, /*#__PURE__*/React.createElement(ChartSwitch, {
    history: history,
    current: "code-quality",
    reportType: "develop"
  }), /*#__PURE__*/React.createElement(HeaderButtons, {
    items: [{
      icon: 'refresh',
      handler: handleRefresh,
      display: true
    }]
  })), /*#__PURE__*/React.createElement(Breadcrumb, {
    title: formatMessage({
      id: 'report.code-quality.head'
    })
  }), /*#__PURE__*/React.createElement(Content, null, isRefresh ? /*#__PURE__*/React.createElement(LoadingBar, {
    display: isRefresh
  }) : getContent()));
}));
export default CodeQuality;