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/table/style";
import _Table from "@hzero-front-ui/c7n-ui/lib/TablePro";
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 { Page, Header, Content, Breadcrumb } from '@choerodon/boot';
import ReactEcharts from 'echarts-for-react';
import _ from 'lodash';
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 "../DeployDuration/DeployDuration.less";
import { getAxis } from "../util";
import { useReportsStore } from "../stores";
import { useDeployTimesStore } from "./stores";
import MaxTagPopover from "../Component/MaxTagPopover";
import "./DeployTimes.less";
var Option = _Select.Option;
var Column = _Table.Column;
var DeployTimes = observer(function () {
  var _useReportsStore = useReportsStore(),
      AppState = _useReportsStore.AppState,
      ReportsStore = _useReportsStore.ReportsStore,
      history = _useReportsStore.history,
      formatMessage = _useReportsStore.intl.formatMessage,
      _useReportsStore$hist = _useReportsStore.history.location,
      state = _useReportsStore$hist.state,
      search = _useReportsStore$hist.search;

  var _useDeployTimesStore = useDeployTimesStore(),
      DeployTimesSelectDataSet = _useDeployTimesStore.DeployTimesSelectDataSet,
      DeployTimesTableDataSet = _useDeployTimesStore.DeployTimesTableDataSet;

  var multilpleRecord = DeployTimesSelectDataSet.current;

  var _useState = useState([]),
      _useState2 = _slicedToArray(_useState, 2),
      env = _useState2[0],
      setEnv = _useState2[1];

  var _useState3 = useState([]),
      _useState4 = _slicedToArray(_useState3, 2),
      app = _useState4[0],
      setApp = _useState4[1];

  var _useState5 = useState([]),
      _useState6 = _slicedToArray(_useState5, 2),
      envIds = _useState6[0],
      setEnvIds = _useState6[1];

  var _useState7 = useState('all_appServices'),
      _useState8 = _slicedToArray(_useState7, 2),
      appId = _useState8[0],
      setAppId = _useState8[1];

  var _useState9 = useState([]),
      _useState10 = _slicedToArray(_useState9, 2),
      appArr = _useState10[0],
      setAppArr = _useState10[1];

  var _useState11 = useState([]),
      _useState12 = _slicedToArray(_useState11, 2),
      dateArr = _useState12[0],
      setDateArr = _useState12[1];

  var _useState13 = useState([]),
      _useState14 = _slicedToArray(_useState13, 2),
      successArr = _useState14[0],
      setSuccessArr = _useState14[1];

  var _useState15 = useState([]),
      _useState16 = _slicedToArray(_useState15, 2),
      failArr = _useState16[0],
      setFailArr = _useState16[1];

  var _useState17 = useState([]),
      _useState18 = _slicedToArray(_useState17, 2),
      allArr = _useState18[0],
      setAllArr = _useState18[1];

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

  var handleRefresh = function handleRefresh() {
    loadEnvCards();
    loadApps();
  };
  /**
   * 选择环境
   * @param ids 环境ID
   */


  var handleEnvSelect = function handleEnvSelect(ids) {
    if (ids) {
      setEnvIds(ids);
    } else {
      setEnvIds([]);
    }

    loadCharts(appId, ids || []);
  };
  /**
   * 选择应用
   * @param id 应用ID
   */


  var handleAppSelect = function handleAppSelect(id) {
    setAppId(id);
    loadCharts(id);
  };

  useEffect(function () {
    ReportsStore.changeIsRefresh(true);
    loadEnvCards();
    loadApps();
    return function () {
      ReportsStore.setAllData([]);
      ReportsStore.setStartTime(moment().subtract(6, 'days'));
      ReportsStore.setEndTime(moment());
      ReportsStore.setStartDate();
      ReportsStore.setEndDate();
      ReportsStore.setPageInfo({
        pageNum: 1,
        total: 0,
        pageSize: 10
      });
    };
  }, []);
  useEffect(function () {
    if (envIds.length) {
      multilpleRecord.set('deployTimeApps', envIds.slice());
    } else {
      multilpleRecord.set('deployTimeApps', []);
    }

    if (appDom) {
      if (appId) {
        multilpleRecord.set('deployTimeName', appId);
      }
    } // else {
    //   debugger;
    //   multilpleRecord.set('deployTimeName', null);
    // }

  }, [envIds, appId]);
  /**
   * 获取可用环境
   */

  var loadEnvCards = function loadEnvCards() {
    var projectId = AppState.currentMenuType.id;
    var historyEnvsId = null;

    if (state && state.envIds) {
      historyEnvsId = state.envIds;
    }

    ReportsStore.loadActiveEnv(projectId).then(function (data) {
      var envCurrent = data && data.length ? _.filter(data, ['permission', true]) : [];

      if (envCurrent.length) {
        var selectEnv = envIds.length ? envIds : [envCurrent[0].id];

        if (historyEnvsId) {
          selectEnv = historyEnvsId;
        }

        setEnv(envCurrent);
        setEnvIds(selectEnv);
        loadCharts(appId, selectEnv);
      } else {
        ReportsStore.judgeRole(['choerodon.code.project.deploy.environment.ps.detail-create-env']);
      }
    });
  };
  /**
   * 加载应用
   */


  var loadApps = function loadApps() {
    var id = AppState.currentMenuType.id;
    var historyAppId = null;

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

    ReportsStore.loadApps(id).then(function (appCurrent) {
      if (appCurrent.length) {
        var selectApp = appId || 'all_appServices';

        if (historyAppId) {
          selectApp = historyAppId;
        }

        setApp(appCurrent);
        setAppId(selectApp);
      }
    });
  };
  /**
   * 加载图表数据
   */


  var loadCharts = function loadCharts() {
    var id = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : appId;
    var eIds = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : envIds;
    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');
    var appIDCurrent = id === 'all_appServices' ? [] : id;
    ReportsStore.loadDeployTimesChart(projectId, appIDCurrent, startTime, endTime, eIds.slice()).then(function (res) {
      if (res) {
        setDateArr(res.creationDates);
        setSuccessArr(res.deploySuccessFrequency);
        setFailArr(res.deployFailFrequency);
        setAllArr(res.deployFrequencys);
      }
    });
    loadTables(id, eIds);
  };
  /**
   * 加载table数据
   */


  var loadTables = function loadTables() {
    var id = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'all_appServices';
    var eIds = arguments.length > 1 ? arguments[1] : undefined;
    var startTime = ReportsStore.getStartTime.format('YYYY-MM-DD HH:mm:ss');
    var endTime = ReportsStore.getEndTime.format('YYYY-MM-DD HH:mm:ss');
    var appIDCurrent = id === 'all_appServices' ? [] : id;
    DeployTimesTableDataSet.setQueryParameter('appId', appIDCurrent);
    DeployTimesTableDataSet.setQueryParameter('endTime', endTime);
    DeployTimesTableDataSet.setQueryParameter('startTime', startTime);
    DeployTimesTableDataSet.setQueryParameter('envIds', eIds.slice());
    DeployTimesTableDataSet.query();
  };
  /**
   * 渲染图表
   * @returns {*}
   */


  function getOption() {
    var val = [{
      name: "".concat(formatMessage({
        id: 'report.build-number.fail'
      }))
    }, {
      name: "".concat(formatMessage({
        id: 'report.build-number.success'
      }))
    }, {
      name: "".concat(formatMessage({
        id: 'report.build-number.total'
      }))
    }];
    val[0].value = _.reduce(failArr, function (sum, n) {
      return sum + n;
    }, 0);
    val[1].value = _.reduce(successArr, function (sum, n) {
      return sum + n;
    }, 0);
    val[2].value = _.reduce(allArr, function (sum, n) {
      return sum + n;
    }, 0);
    var startTime = ReportsStore.getStartTime;
    var endTime = ReportsStore.getEndTime;
    var successArrCurrent = successArr ? successArr.slice() : [];
    var failArrCurrent = failArr ? failArr.slice() : [];
    var allArrCurrent = allArr ? allArr.slice() : [];

    var _getAxis = getAxis(startTime, endTime, dateArr ? dateArr.slice() : [], {
      successArrCurrent: successArrCurrent,
      failArrCurrent: failArrCurrent,
      allArrCurrent: allArrCurrent
    }),
        xAxis = _getAxis.xAxis,
        yAxis = _getAxis.yAxis;

    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'none'
        },
        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) {
          if (params[1].value || params[0].value) {
            var total = params[0].value + params[1].value;
            return "<div>\n                <div>".concat(formatMessage({
              id: 'branch.issue.date'
            }), "\uFF1A").concat(params[1].name, "</div>\n                <div><span style=\"display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:").concat(params[1].color, ";\"></span>").concat(formatMessage({
              id: 'appstore.deploy'
            })).concat(params[1].seriesName, "\uFF1A").concat(params[1].value, "</div>\n                <div><span style=\"display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:").concat(params[0].color, ";\"></span>").concat(formatMessage({
              id: 'appstore.deploy'
            })).concat(params[0].seriesName, "\uFF1A").concat(params[0].value, "</div>\n                <div>").concat(formatMessage({
              id: 'appstore.deploy'
            })).concat(formatMessage({
              id: 'report.build-number.total'
            }), "\uFF1A").concat(total, "</div>\n                <div>").concat(formatMessage({
              id: 'appstore.deploy'
            })).concat(formatMessage({
              id: 'report.build-number.success.rate'
            }), "\uFF1A").concat((params[0].value / total * 100).toFixed(2), "%</div>\n              <div>");
          }
        }
      },
      legend: {
        left: 'right',
        itemWidth: 14,
        itemGap: 20,
        formatter: function formatter(name) {
          var count = 0;

          _.map(val, function (data) {
            if (data.name === name) {
              count = data.value;
            }
          });

          return "".concat(name, "\uFF1A").concat(count);
        },
        selectedMode: false
      },
      grid: {
        left: '2%',
        right: '3%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        axisTick: {
          show: false
        },
        axisLine: {
          lineStyle: {
            color: '#eee',
            type: 'solid',
            width: 2
          }
        },
        splitLine: {
          lineStyle: {
            color: ['#eee'],
            width: 1,
            type: 'solid'
          }
        },
        data: xAxis,
        axisLabel: {
          margin: 13,
          textStyle: {
            color: 'rgba(0, 0, 0, 0.65)',
            fontSize: 12
          },
          formatter: function formatter(value) {
            return value.slice(5, 10).replace('-', '/');
          }
        }
      },
      yAxis: {
        name: "".concat(formatMessage({
          id: 'report.build-number.yAxis'
        })),
        min: yAxis.allArrCurrent.length ? null : 0,
        max: yAxis.allArrCurrent.length ? null : 4,
        type: 'value',
        nameTextStyle: {
          fontSize: 13,
          color: '#000'
        },
        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: {
            color: '#eee',
            type: 'solid',
            width: 1
          }
        }
      },
      series: [{
        name: "".concat(formatMessage({
          id: 'report.build-number.success'
        })),
        type: 'bar',
        itemStyle: {
          color: '#00BFA5',
          emphasis: {
            shadowBlur: 10,
            shadowColor: 'rgba(0,0,0,0.20)'
          }
        },
        barWidth: '40%',
        stack: 'total',
        data: yAxis.successArrCurrent
      }, {
        name: "".concat(formatMessage({
          id: 'report.build-number.fail'
        })),
        type: 'bar',
        itemStyle: {
          color: '#F44336',
          emphasis: {
            shadowBlur: 10,
            shadowColor: 'rgba(0,0,0,0.20)'
          }
        },
        barWidth: '40%',
        stack: 'total',
        data: yAxis.failArrCurrent
      }, {
        name: "".concat(formatMessage({
          id: 'report.build-number.total'
        })),
        type: 'bar',
        color: 'transparent',
        stack: 'total'
      }]
    };
  }
  /**
   * 表格函数
   * @returns {*}
   */


  function renderTable() {
    return /*#__PURE__*/React.createElement(_Table, {
      dataSet: DeployTimesTableDataSet,
      queryBar: "none"
    }, /*#__PURE__*/React.createElement(Column, {
      name: "status",
      renderer: function renderer(_ref) {
        var record = _ref.record;
        return /*#__PURE__*/React.createElement(StatusTags, {
          name: formatMessage({
            id: record.get('status')
          }),
          colorCode: record.get('status'),
          error: record.get('error')
        });
      }
    }), /*#__PURE__*/React.createElement(Column, {
      name: "creationDate"
    }), /*#__PURE__*/React.createElement(Column, {
      name: "appServiceInstanceCode",
      renderer: function renderer(_ref2) {
        var record = _ref2.record;
        return /*#__PURE__*/React.createElement(MouserOverWrapper, {
          text: record.get('appServiceInstanceCode'),
          width: 0.2
        }, record.get('appServiceInstanceCode'));
      }
    }), /*#__PURE__*/React.createElement(Column, {
      name: "appServiceName",
      renderer: function renderer(_ref3) {
        var record = _ref3.record;
        return /*#__PURE__*/React.createElement(MouserOverWrapper, {
          text: record.get('appServiceName'),
          width: 0.2
        }, record.get('appServiceName'));
      }
    }), /*#__PURE__*/React.createElement(Column, {
      name: "appServiceVersion",
      renderer: function renderer(_ref4) {
        var record = _ref4.record;
        return /*#__PURE__*/React.createElement(MouserOverWrapper, {
          text: record.get('appServiceVersion'),
          width: 0.2
        }, record.get('appServiceVersion'));
      }
    }), /*#__PURE__*/React.createElement(Column, {
      name: "lastUpdatedName"
    }));
  }

  var tableChange = function tableChange(pagination) {
    var startTime = ReportsStore.getStartTime.format('YYYY-MM-DD HH:mm:ss');
    var endTime = ReportsStore.getEndTime.format('YYYY-MM-DD HH:mm:ss');
    var appIDCurrent = appId === 'all_appServices' ? [] : appId;
    DeployTimesTableDataSet.setQueryParameter('appId', appIDCurrent);
    DeployTimesTableDataSet.setQueryParameter('endTime', endTime);
    DeployTimesTableDataSet.setQueryParameter('startTime', startTime);
    DeployTimesTableDataSet.setQueryParameter('envIds', envIds.slice());
    DeployTimesTableDataSet.query();
  };

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

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

  var echartsLoading = ReportsStore.getEchartsLoading;
  var envData = ReportsStore.getEnvCard;

  var envs = _.filter(envData, ['permission', true]);

  var isRefresh = ReportsStore.getIsRefresh;
  var backPath = search.includes('deploy-overview') ? '/devops/deploy-overview' : '/devops/charts/deploy';
  var envDom = env.length ? _.map(env, function (d) {
    return /*#__PURE__*/React.createElement(Option, {
      key: d.id,
      value: d.id
    }, d.name);
  }) : null;
  var appDom = app.length ? _.map(app, function (d) {
    return /*#__PURE__*/React.createElement(Option, {
      key: d.id,
      value: d.id
    }, d.name);
  }) : null;
  var content = envs && envs.length ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    className: "c7n-report-screen c7n-report-select"
  }, /*#__PURE__*/React.createElement(_Form, {
    style: {
      width: 620,
      marginRight: 60
    },
    dataSet: DeployTimesSelectDataSet,
    columns: 3
  }, /*#__PURE__*/React.createElement(_Select, {
    searchable: true,
    name: "deployTimeApps",
    notFoundContent: formatMessage({
      id: 'envoverview.noEnv'
    }),
    colSpan: 2,
    maxTagCount: 3,
    onChange: handleEnvSelect,
    maxTagPlaceholder: function maxTagPlaceholder(omittedValues) {
      return maxTagNode(omittedValues);
    },
    optionFilterProp: "children",
    filterOption: function filterOption(input, option) {
      return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    filter: true
  }, envDom), /*#__PURE__*/React.createElement(_Select, {
    colSpan: 1,
    searchable: true,
    name: "deployTimeName",
    notFoundContent: formatMessage({
      id: 'report.no.app.tips'
    }),
    onChange: handleAppSelect,
    optionFilterProp: "children",
    filterOption: function filterOption(input, option) {
      return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    filter: true,
    clearButton: false
  }, appDom, appDom ? /*#__PURE__*/React.createElement(Option, {
    key: "all",
    value: "all_appServices"
  }, formatMessage({
    id: 'report.all-app'
  })) : null)), /*#__PURE__*/React.createElement(TimePicker, {
    startTime: ReportsStore.getStartDate,
    endTime: ReportsStore.getEndDate,
    type: dateType,
    onChange: handleDateChoose,
    func: loadCharts,
    store: ReportsStore
  })), /*#__PURE__*/React.createElement("div", {
    className: "c7n-report-content"
  }, /*#__PURE__*/React.createElement(_Spin, {
    spinning: echartsLoading
  }, /*#__PURE__*/React.createElement(ReactEcharts, {
    option: getOption(),
    notMerge: true,
    lazyUpdate: true,
    style: {
      height: '350px',
      width: '100%'
    }
  }))), /*#__PURE__*/React.createElement("div", {
    className: "c7n-report-table"
  }, renderTable())) : /*#__PURE__*/React.createElement(NoChart, {
    getProRole: ReportsStore.getProRole,
    type: "env"
  });
  return /*#__PURE__*/React.createElement(Page, {
    className: "c7n-region"
  }, /*#__PURE__*/React.createElement(Header, {
    title: formatMessage({
      id: 'report.deploy-times.head'
    })
  }, /*#__PURE__*/React.createElement(HeaderButtons, {
    refresh: handleRefresh,
    backPath: backPath,
    reportKey: "deploy-times",
    reportType: "deploy"
  })), /*#__PURE__*/React.createElement(Breadcrumb, {
    title: formatMessage({
      id: 'report.deploy-times.head'
    })
  }), /*#__PURE__*/React.createElement(Content, null, isRefresh ? /*#__PURE__*/React.createElement(LoadingBar, {
    display: isRefresh
  }) : content));
});
DeployTimes.name = 'DeployTimes';
export default DeployTimes;