function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

import { axios, store, stores, Choerodon } from '@choerodon/boot';
import moment from 'moment';
import { useLocalStore } from 'mobx-react-lite';
import { handlePromptError } from "../../../utils";
var HEIGHT = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
export default function useStore(AppState) {
  return useLocalStore(function () {
    return {
      pageInfo: {
        current: 1,
        total: 0,
        pageSize: 10
      },
      Info: {
        filters: {},
        sort: {
          columnKey: 'id',
          order: 'descend'
        },
        paras: []
      },
      startTime: moment().subtract(6, 'days'),
      startDate: null,
      endTime: moment(),
      endDate: null,
      envId: null,
      ddChart: [],
      dtChart: [],
      allData: [],
      loading: true,
      apps: [],
      appId: null,
      BuildNumber: {},
      BuildDuration: {},
      echartsLoading: false,
      commits: {},
      commitsRecord: [],
      commitLoading: false,
      historyLoad: false,
      isRefresh: false,
      allApps: [],
      proRole: '',
      codeQuality: {},
      envCard: [],
      appData: [],
      setProRole: function setProRole(data) {
        this.proRole = data;
      },

      get getProRole() {
        return this.proRole;
      },

      setAllApps: function setAllApps(data) {
        this.allApps = data;
      },

      get getAllApps() {
        return this.allApps.slice();
      },

      setHistoryLoad: function setHistoryLoad(flag) {
        this.historyLoad = flag;
      },

      get getHistoryLoad() {
        return this.historyLoad;
      },

      setCommitLoading: function setCommitLoading(flag) {
        this.commitLoading = flag;
      },

      get getCommitLoading() {
        return this.commitLoading;
      },

      setCommits: function setCommits(data) {
        this.commits = data;
      },

      get getCommits() {
        return this.commits;
      },

      setCommitsRecord: function setCommitsRecord(data) {
        this.commitsRecord = data;
      },

      get getCommitsRecord() {
        return this.commitsRecord;
      },

      setPageInfo: function setPageInfo(page) {
        this.pageInfo.current = page.pageNum;
        this.pageInfo.total = page.total;
        this.pageInfo.pageSize = page.pageSize;
      },

      get getPageInfo() {
        return this.pageInfo;
      },

      setInfo: function setInfo(Info) {
        this.Info = Info;
      },

      get getInfo() {
        return this.Info;
      },

      get getStartTime() {
        return this.startTime;
      },

      setStartTime: function setStartTime(data) {
        this.startTime = data;
      },

      get getStartDate() {
        return this.startDate;
      },

      setStartDate: function setStartDate(data) {
        this.startDate = data;
      },

      get getEndTime() {
        return this.endTime;
      },

      setEndTime: function setEndTime(data) {
        this.endTime = data;
      },

      get getEndDate() {
        return this.endDate;
      },

      setEndDate: function setEndDate(data) {
        this.endDate = data;
      },
      setEnvId: function setEnvId(id) {
        this.envId = id;
      },

      get getEnvId() {
        return this.envId;
      },

      setDdChart: function setDdChart(data) {
        this.ddChart = data;
      },

      get getDdChart() {
        return this.ddChart;
      },

      setDtChart: function setDtChart(data) {
        this.dtChart = data;
      },

      get getDtChart() {
        return this.dtChart;
      },

      get getAllData() {
        return this.allData.slice();
      },

      setAllData: function setAllData(data) {
        this.allData = data;
      },
      changeIsRefresh: function changeIsRefresh(flag) {
        this.isRefresh = flag;
      },

      get getIsRefresh() {
        return this.isRefresh;
      },

      changeLoading: function changeLoading(flag) {
        this.loading = flag;
      },

      get getLoading() {
        return this.loading;
      },

      get getApps() {
        return this.apps.slice();
      },

      get getAppId() {
        return this.appId;
      },

      get getBuildNumber() {
        return this.BuildNumber;
      },

      get getBuildDuration() {
        return this.BuildDuration;
      },

      get getEchartsLoading() {
        return this.echartsLoading;
      },

      setApps: function setApps(data) {
        this.apps = data;
      },
      setAppId: function setAppId(id) {
        this.appId = id;
      },
      setBuildNumber: function setBuildNumber(data) {
        this.BuildNumber = data;
      },
      setBuildDuration: function setBuildDuration(data) {
        this.BuildDuration = data;
      },
      setEchartsLoading: function setEchartsLoading(data) {
        this.echartsLoading = data;
      },

      get getCodeQuality() {
        return this.codeQuality;
      },

      setCodeQuality: function setCodeQuality(data) {
        this.codeQuality = data;
      },
      setEnvCard: function setEnvCard(envCard) {
        this.envCard = envCard;
      },

      get getEnvCard() {
        return this.envCard;
      },

      setAppDate: function setAppDate(data) {
        this.appData = data;
      },

      get getAppData() {
        return this.appData;
      },

      /**
       * 加载项目下已经部署的应用（本项目下或者服务市场在该项目下部署过的服务）
       * @param proId
       */
      loadApps: function loadApps(proId) {
        var _this = this;

        return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
          var resCurrent;
          return regeneratorRuntime.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  _context.next = 2;
                  return axios.get("/devops/v1/projects/".concat(proId, "/app_service/list_all")).then(function (data) {
                    var res = handlePromptError(data);

                    if (res) {
                      _this.handleAppsDate(data);

                      return data;
                    }
                  });

                case 2:
                  resCurrent = _context.sent;
                  return _context.abrupt("return", resCurrent);

                case 4:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee);
        }))();
      },

      /**
      * 加载项目下所有应用，代码提交报表使用
      * @param proId
      */
      loadAllApps: function loadAllApps(proId) {
        var _this2 = this;

        return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
          var resCurrent;
          return regeneratorRuntime.wrap(function _callee2$(_context2) {
            while (1) {
              switch (_context2.prev = _context2.next) {
                case 0:
                  _context2.next = 2;
                  return axios.get("/devops/v1/projects/".concat(proId, "/app_service/list_by_active")).then(function (data) {
                    var res = handlePromptError(data);

                    if (res) {
                      _this2.handleAppsDate(data);

                      return data;
                    }
                  });

                case 2:
                  resCurrent = _context2.sent;
                  return _context2.abrupt("return", resCurrent);

                case 4:
                case "end":
                  return _context2.stop();
              }
            }
          }, _callee2);
        }))();
      },
      handleAppsDate: function handleAppsDate(data) {
        if (data.length) {
          this.setAllApps(data);
        } else {
          this.setEchartsLoading(false);
          this.changeLoading(false); // this.judgeRole();
        }

        this.changeIsRefresh(false);
      },

      /**
      * 判断角色
      */
      judgeRole: function judgeRole(codes) {
        var _this3 = this;

        return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
          var _AppState$currentMenu, projectId, organizationId, type, datas;

          return regeneratorRuntime.wrap(function _callee3$(_context3) {
            while (1) {
              switch (_context3.prev = _context3.next) {
                case 0:
                  _AppState$currentMenu = AppState.currentMenuType, projectId = _AppState$currentMenu.projectId, organizationId = _AppState$currentMenu.organizationId, type = _AppState$currentMenu.type;
                  datas = ['devops-service.devops-environment.create'];
                  axios({
                    method: 'post',
                    url: '/iam/choerodon/v1/permissions/menus/check-permissions',
                    data: datas,
                    params: {
                      tenantId: organizationId,
                      projectId: projectId
                    }
                  }).then(function (data) {
                    var res = handlePromptError(data);

                    if (res && data && data.length) {
                      var approve = data[0].approve;

                      _this3.setProRole(approve ? 'owner' : 'member');
                    }
                  });

                case 3:
                case "end":
                  return _context3.stop();
              }
            }
          }, _callee3);
        }))();
      },

      /**
      * 加载构建次数
      * @param proId
      */
      loadBuildNumber: function loadBuildNumber(projectId, appId, startTime, endTime) {
        var _this4 = this;

        this.setEchartsLoading(true);
        return axios.get("/devops/v1/projects/".concat(projectId, "/pipeline/frequency?app_service_id=").concat(appId, "&start_time=").concat(startTime, "&end_time=").concat(endTime)).then(function (data) {
          var res = handlePromptError(data);

          if (res) {
            _this4.setBuildNumber(data);
          }

          _this4.setEchartsLoading(false);
        });
      },

      /**
      * 加载构建时长
      *
      */
      loadBuildDuration: function loadBuildDuration(projectId, appId, startTime, endTime) {
        var _this5 = this;

        this.setEchartsLoading(true);
        return axios.get("/devops/v1/projects/".concat(projectId, "/pipeline/time?app_service_id=").concat(appId, "&start_time=").concat(startTime, "&end_time=").concat(endTime)).then(function (data) {
          var res = handlePromptError(data);

          if (res) {
            _this5.setBuildDuration(data);
          }

          _this5.setEchartsLoading(false);
        });
      },

      /**
      * 加载构建情况表格
      *
      */
      loadBuildTable: function loadBuildTable(projectId, appId, startTime, endTime) {
        var _this6 = this;

        var page = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1;
        var size = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : this.pageInfo.pageSize;
        this.changeLoading(true);
        return axios.get("/devops/v1/projects/".concat(projectId, "/pipeline/page_by_options?app_service_id=").concat(appId, "&start_time=").concat(startTime, "&end_time=").concat(endTime, "&page=").concat(page, "&size=").concat(size)).then(function (data) {
          var res = handlePromptError(data);

          if (res) {
            _this6.handleData(data);
          }

          _this6.changeLoading(false);
        });
      },
      loadDeployDurationChart: function loadDeployDurationChart(projectId, envId, startTime, endTime, appIds) {
        var _this7 = this;

        this.setEchartsLoading(true);
        return axios.post("devops/v1/projects/".concat(projectId, "/app_service_instances/env_commands/time?envId=").concat(envId, "&endTime=").concat(endTime, "&startTime=").concat(startTime), JSON.stringify(appIds)).then(function (data) {
          _this7.setEchartsLoading(false);

          var res = handlePromptError(data);

          if (res) {
            _this7.setDdChart(data);

            return data;
          }

          return res;
        });
      },
      loadDeployTimesChart: function loadDeployTimesChart(projectId, appId, startTime, endTime, envIds) {
        var _this8 = this;

        this.setEchartsLoading(true);
        return axios.post("devops/v1/projects/".concat(projectId, "/app_service_instances/env_commands/frequency?app_service_id=").concat(appId, "&endTime=").concat(endTime, "&startTime=").concat(startTime), JSON.stringify(envIds)).then(function (data) {
          _this8.setEchartsLoading(false);

          var res = handlePromptError(data);

          if (res) {
            _this8.setDtChart(data);

            return data;
          }

          return res;
        });
      },
      loadDeployDurationTable: function loadDeployDurationTable(projectId, envId, startTime, endTime, appIds) {
        var _this9 = this;

        var page = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : this.pageInfo.current;
        var size = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : this.pageInfo.pageSize;
        this.changeLoading(true);
        return axios.post("devops/v1/projects/".concat(projectId, "/app_service_instances/env_commands/timeTable?envId=").concat(envId, "&endTime=").concat(endTime, "&startTime=").concat(startTime, "&page=").concat(page, "&size=").concat(size), JSON.stringify(appIds)).then(function (data) {
          var res = handlePromptError(data);

          if (res) {
            _this9.handleData(data);
          }

          _this9.changeLoading(false);

          _this9.changeIsRefresh(false);
        });
      },
      loadDeployTimesTable: function loadDeployTimesTable(projectId, appId, startTime, endTime, envIds) {
        var _this10 = this;

        var page = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : this.pageInfo.current;
        var size = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : this.pageInfo.pageSize;
        this.changeLoading(true);
        return axios.post("devops/v1/projects/".concat(projectId, "/app_service_instances/env_commands/frequencyTable?app_service_id=").concat(appId, "&endTime=").concat(endTime, "&startTime=").concat(startTime, "&page=").concat(page, "&size=").concat(size), JSON.stringify(envIds)).then(function (data) {
          var res = handlePromptError(data);

          if (res) {
            _this10.handleData(data);
          }

          _this10.changeLoading(false);

          _this10.changeIsRefresh(false);
        });
      },

      /**
      * 代码提交情况
      * @param projectId
      * @param start 开始时间
      * @param end 结束时间
      * @param apps 应用，字符串，逗号分隔
      */
      loadCommits: function loadCommits(projectId) {
        var _this11 = this;

        var start = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
        var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
        var apps = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
        this.setCommitLoading(true);
        axios.post("devops/v1/projects/".concat(projectId, "/commits?start_date=").concat(start, "&end_date=").concat(end), JSON.stringify(apps)).then(function (data) {
          var res = handlePromptError(data);

          if (res) {
            _this11.setCommits(data);
          }

          _this11.setCommitLoading(false);
        })["catch"](function (err) {
          _this11.setCommitLoading(false);

          Choerodon.handleResponseError(err);
        });
      },

      /**
      * 提交历史纪录
      * @param projectId
      * @param start
      * @param end
      * @param apps
      * @param page
      */
      loadCommitsRecord: function loadCommitsRecord(projectId) {
        var _this12 = this;

        var start = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
        var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
        var apps = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
        var page = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1;
        this.setHistoryLoad(true);
        axios.post("devops/v1/projects/".concat(projectId, "/commits/record?page=").concat(page, "&size=5&start_date=").concat(start, "&end_date=").concat(end), JSON.stringify(apps)).then(function (data) {
          var res = handlePromptError(data);

          if (res) {
            _this12.setCommitsRecord(data);
          }

          _this12.setHistoryLoad(false);
        })["catch"](function (err) {
          _this12.setHistoryLoad(false);

          Choerodon.handleResponseError(err);
        });
      },

      /**
      * 加载代码质量
      */
      loadCodeQuality: function loadCodeQuality(projectId, appId, type, startTime, endTime) {
        var _this13 = this;

        this.setEchartsLoading(true);
        return axios.get("/devops/v1/projects/".concat(projectId, "/app_service/").concat(appId, "/sonarqube_table?type=").concat(type, "&startTime=").concat(startTime, "&endTime=").concat(endTime)).then(function (data) {
          var res = handlePromptError(data);

          if (res) {
            _this13.setCodeQuality(data);
          }

          _this13.setEchartsLoading(false);
        });
      },
      handleData: function handleData(data) {
        var pageNum = data.pageNum,
            pageSize = data.pageSize,
            total = data.total,
            list = data.list;
        this.setAllData(list || []);
        var page = {
          pageNum: pageNum,
          pageSize: pageSize,
          total: total
        };
        this.setPageInfo(page);
      },
      loadActiveEnv: function loadActiveEnv(projectId) {
        var _this14 = this;

        return axios.get("devops/v1/projects/".concat(projectId, "/envs/list_by_active?active=true")).then(function (data) {
          if (data && data.failed) {
            Choerodon.prompt(data.message);
          } else {
            _this14.setEnvCard(data);
          }

          return data;
        });
      },
      cancelPipeline: function cancelPipeline(gitlabProjectId, pipelineId) {
        return axios.post("/devops/v1/projects/".concat(AppState.currentMenuType.id, "/gitlab_projects/").concat(gitlabProjectId, "/pipelines/").concat(pipelineId, "/cancel")).then(function (datas) {
          return handlePromptError(datas, false);
        });
      },
      retryPipeline: function retryPipeline(gitlabProjectId, pipelineId) {
        return axios.post("/devops/v1/projects/".concat(AppState.currentMenuType.id, "/gitlab_projects/").concat(gitlabProjectId, "/pipelines/").concat(pipelineId, "/retry")).then(function (datas) {
          return handlePromptError(datas, false);
        });
      },

      /**
      *
      * @param projectId
      * @param envId
      * @param appId 返回的数据中必须包含被传入的appId
      */
      loadAppDataByEnv: function loadAppDataByEnv(projectId, envId) {
        var _this15 = this;

        var appId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
        axios.get("devops/v1/projects/".concat(projectId, "/app_service/list_by_env?envId=").concat(envId).concat(appId ? "&status=running$app_service_id=".concat(appId) : '')).then(function (data) {
          var res = handlePromptError(data);

          if (res) {
            _this15.setAppDate(data);

            return data;
          }

          return res;
        });
      }
    };
  });
}