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";
import "choerodon-ui/pro/lib/table/style";
import _Table from "@hzero-front-ui/c7n-ui/lib/TablePro";

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, { Component, useState, useEffect } from 'react';
import { Page, Header, Content, Breadcrumb } from '@choerodon/boot';
import ReactEcharts from 'echarts-for-react';
import { observer } from 'mobx-react-lite';
import map from 'lodash/map';
import filter from 'lodash/filter';
import moment from 'moment';
import StatusTags from "../../../components/status-tag";
import LoadingBar from "../../../components/loading";
import MouserOverWrapper from "../../../components/MouseOverWrapper";
import HeaderButtons from "../Component/HeaderButtons";
import TimePicker from "../Component/TimePicker";
import NoChart from "../Component/NoChart";
import MaxTagPopover from "../Component/MaxTagPopover";
import { useDeployDurationStore } from "./stores";
import { useReportsStore } from "../stores";
import "./DeployDuration.less";
var Column = _Table.Column;
var COLOR = ['50,198,222', '116,59,231', '87,170,248', '255,177,0', '237,74,103'];
var LENGEND = ['data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNiIgaGVpZ2h0PSIyNiIgdmlld0JveD0iMCAwIDI2IDI2Ij4KICA8Y2lyY2xlIGN4PSI0OTkiIGN5PSI2MiIgcj0iMTIiIGZpbGw9IiMzMkM2REUiIGZpbGwtb3BhY2l0eT0iLjYiIGZpbGwtcnVsZT0iZXZlbm9kZCIgc3Ryb2tlPSIjMzJDNkRFIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtNDg2IC00OSkiLz4KPC9zdmc+Cg==', 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNiIgaGVpZ2h0PSIyNiIgdmlld0JveD0iMCAwIDI2IDI2Ij4KICA8Y2lyY2xlIGN4PSI0NDkiIGN5PSI1NyIgcj0iMTIiIGZpbGw9IiM3NDNCRTciIGZpbGwtb3BhY2l0eT0iLjYiIGZpbGwtcnVsZT0iZXZlbm9kZCIgc3Ryb2tlPSIjNzQzQkU3IiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtNDM2IC00NCkiLz4KPC9zdmc+Cg==', 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNiIgaGVpZ2h0PSIyNiIgdmlld0JveD0iMCAwIDI2IDI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0cmFuc2Zvcm09InRyYW5zbGF0ZSgtNDg2IC00NCkiLz4KPC9zdmc+Cg=='];
var DeployDuration = observer(function () {
  var _useReportsStore = useReportsStore(),
      ReportsStore = _useReportsStore.ReportsStore,
      _useReportsStore$Repo = _useReportsStore.ReportsStore,
      isRefresh = _useReportsStore$Repo.isRefresh,
      getProRole = _useReportsStore$Repo.getProRole;

  var _useDeployDurationSto = useDeployDurationStore(),
      formatMessage = _useDeployDurationSto.intl.formatMessage,
      detailDs = _useDeployDurationSto.detailDs,
      appServiceDs = _useDeployDurationSto.appServiceDs,
      chartsDs = _useDeployDurationSto.chartsDs,
      permissions = _useDeployDurationSto.permissions,
      envDs = _useDeployDurationSto.envDs,
      tableDs = _useDeployDurationSto.tableDs,
      history = _useDeployDurationSto.history,
      search = _useDeployDurationSto.location.search;

  var _useState = useState([]),
      _useState2 = _slicedToArray(_useState, 2),
      dateArr = _useState2[0],
      setDateArr = _useState2[1];

  var _useState3 = useState([]),
      _useState4 = _slicedToArray(_useState3, 2),
      appArr = _useState4[0],
      setAppArr = _useState4[1];

  var _useState5 = useState([]),
      _useState6 = _slicedToArray(_useState5, 2),
      seriesArr = _useState6[0],
      setSeriesArr = _useState6[1];

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

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

    var res = chartsDs.current.toData();

    if (res) {
      var creationDates = res.creationDates,
          deployAppVOS = res.deployAppVOS;
      setDateArr(creationDates);
      var newSeriesArr = [];
      var newAppArr = [];
      map(deployAppVOS, function (v, index) {
        var series = {
          name: v.appServiceName,
          symbolSize: 24,
          itemStyle: {
            color: "rgba(".concat(COLOR[index], ", 0.6)"),
            borderColor: "rgb(".concat(COLOR[index], ")")
          },
          data: map(v.deployDetailVOS, function (c) {
            return Object.values(c);
          }),
          type: 'scatter'
        };
        var obj = {};
        obj.name = v.appServiceName;
        obj.icon = "image://".concat(LENGEND[index]);
        newSeriesArr.push(series);
        newAppArr.push(obj);
      });
      setSeriesArr(newSeriesArr);
      setAppArr(newAppArr);
    }
  }, [chartsDs.current]);

  function handleRefresh() {
    envDs.query();
    appServiceDs.query();
    chartsDs.query();
    tableDs.query();
  }
  /**
   * 加载数据
   */


  function loadData() {
    var startTime = ReportsStore.getStartTime.format('YYYY-MM-DD HH:mm:ss');
    var endTime = ReportsStore.getEndTime.format('YYYY-MM-DD HH:mm:ss');
    chartsDs.setQueryParameter('startTime', startTime);
    chartsDs.setQueryParameter('endTime', endTime);
    tableDs.setQueryParameter('startTime', startTime);
    tableDs.setQueryParameter('endTime', endTime);
    chartsDs.query();
    tableDs.query();
  }
  /**
   * 图表函数
   * @returns {*}
   */


  function getOption() {
    return {
      legend: {
        data: appArr,
        borderColor: '#000',
        borderWidth: '5px',
        itemWidth: 12,
        itemHeight: 12
      },
      toolbox: {
        feature: {
          dataZoom: {},
          brush: {
            type: ['']
          }
        },
        right: '3%'
      },
      brush: {},
      tooltip: {
        trigger: 'item',
        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, ticket) {
          var time = params.value[1];

          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: 'branch.issue.date'
          }), "\uFF1A").concat(params.data[0], "</div>\n                <div><span style=\"display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:").concat(params.color, ";\"></span>").concat(params.seriesName, "\uFF1A").concat(time, "</div>\n              <div>");
        }
      },
      grid: {
        left: '2%',
        right: '2%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'time',
        scale: true,
        boundaryGap: false,
        axisLine: {
          lineStyle: {
            color: '#eee',
            type: 'solid',
            width: 2
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          margin: 13,
          textStyle: {
            color: 'rgba(0, 0, 0, 0.65)',
            fontSize: 12
          }
        }
      },
      yAxis: {
        nameTextStyle: {
          fontSize: 13,
          color: '#000',
          padding: [0, 0, 0, 22]
        },
        axisTick: {
          show: false
        },
        axisLine: {
          lineStyle: {
            color: '#eee',
            type: 'solid',
            width: 2
          }
        },
        axisLabel: {
          margin: 18,
          textStyle: {
            color: 'rgba(0, 0, 0, 0.65)',
            fontSize: 12
          }
        },
        splitLine: {
          lineStyle: {
            show: true,
            type: 'solid'
          }
        },
        boundaryGap: false,
        name: formatMessage({
          id: 'minTime'
        }),
        min: seriesArr.length ? null : 0,
        max: seriesArr.length ? null : 4,
        scale: true
      },
      series: seriesArr
    };
  }

  function renderTableStatus(_ref) {
    var value = _ref.value,
        record = _ref.record;
    var error = record.get('status');
    return /*#__PURE__*/React.createElement(StatusTags, {
      name: formatMessage({
        id: value
      }),
      colorCode: value || '',
      error: error
    });
  }

  function renderText(_ref2) {
    var value = _ref2.value;
    return /*#__PURE__*/React.createElement(MouserOverWrapper, {
      text: value,
      width: 0.2
    }, value);
  }

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

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

  function getContent() {
    var envData = envDs.toData();
    var envs = filter(envData, ['permission', true]);
    return envs && envs.length ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
      className: "c7n-report-screen c7n-report-select"
    }, /*#__PURE__*/React.createElement(_Form, {
      dataSet: detailDs,
      columns: 3,
      style: {
        paddingRight: '.2rem'
      }
    }, /*#__PURE__*/React.createElement(_Select, {
      name: "envId",
      searchable: true,
      colSpan: 1,
      clearButton: false
    }), /*#__PURE__*/React.createElement(_Select, {
      name: "appServiceIds",
      searchable: true,
      maxTagCount: 3,
      maxTagPlaceholder: maxTagNode,
      showCheckAll: false,
      colSpan: 2
    })), /*#__PURE__*/React.createElement(TimePicker, {
      startTime: ReportsStore.getStartDate,
      endTime: ReportsStore.getEndDate,
      func: loadData,
      type: dateType,
      onChange: handleDateChoose,
      store: ReportsStore
    })), /*#__PURE__*/React.createElement("div", {
      className: "c7n-report-content"
    }, /*#__PURE__*/React.createElement(_Spin, {
      spinning: chartsDs.status === 'loading'
    }, /*#__PURE__*/React.createElement(ReactEcharts, {
      option: getOption(),
      notMerge: true,
      lazyUpdate: true,
      style: {
        height: '350px',
        width: '100%'
      }
    }))), /*#__PURE__*/React.createElement("div", {
      className: "c7n-report-table"
    }, /*#__PURE__*/React.createElement(_Table, {
      dataSet: tableDs,
      queryBar: "none"
    }, /*#__PURE__*/React.createElement(Column, {
      name: "status",
      renderer: renderTableStatus
    }), /*#__PURE__*/React.createElement(Column, {
      name: "creationDate"
    }), /*#__PURE__*/React.createElement(Column, {
      name: "appServiceInstanceCode",
      renderer: renderText
    }), /*#__PURE__*/React.createElement(Column, {
      name: "appServiceName",
      renderer: renderText
    }), /*#__PURE__*/React.createElement(Column, {
      name: "appServiceVersion",
      renderer: renderText
    }), /*#__PURE__*/React.createElement(Column, {
      name: "lastUpdatedName"
    })))) : /*#__PURE__*/React.createElement(NoChart, {
      type: "env",
      getProRole: getProRole
    });
  }

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

  return /*#__PURE__*/React.createElement(Page, {
    className: "c7n-region"
  }, /*#__PURE__*/React.createElement(Header, {
    title: formatMessage({
      id: 'report.deploy-duration.head'
    })
  }, /*#__PURE__*/React.createElement(HeaderButtons, {
    refresh: handleRefresh,
    reportKey: "deploy-duration",
    reportType: "deploy"
  })), /*#__PURE__*/React.createElement(Breadcrumb, {
    title: formatMessage({
      id: 'report.deploy-duration.head'
    })
  }), /*#__PURE__*/React.createElement(Content, null, isRefresh ? /*#__PURE__*/React.createElement(LoadingBar, {
    display: isRefresh
  }) : getContent()));
});
export default DeployDuration;