import "choerodon-ui/lib/button/style";
import _Button from "choerodon-ui/lib/button";

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); }); }; }

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 { inject } from 'mobx-react';
import { FormattedMessage, injectIntl } from 'react-intl';
import isEmpty from 'lodash/isEmpty';

var AuditModal = function AuditModal(_ref) {
  var _ref$AppState = _ref.AppState,
      projectId = _ref$AppState.currentMenuType.projectId,
      userId = _ref$AppState.userInfo.id,
      formatMessage = _ref.intl.formatMessage,
      cdRecordId = _ref.cdRecordId,
      _ref$checkData = _ref.checkData,
      type = _ref$checkData.type,
      stageRecordId = _ref$checkData.stageRecordId,
      taskRecordId = _ref$checkData.taskRecordId,
      stageName = _ref$checkData.stageName,
      mainStore = _ref.mainStore,
      modal = _ref.modal,
      onClose = _ref.onClose,
      name = _ref.name;

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      stopLoading = _useState2[0],
      changeStopLoading = _useState2[1];

  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      passLoading = _useState4[0],
      changePassLoading = _useState4[1];

  var _useState5 = useState(false),
      _useState6 = _slicedToArray(_useState5, 2),
      canCheck = _useState6[0],
      setCanCheck = _useState6[1];

  var _useState7 = useState(null),
      _useState8 = _slicedToArray(_useState7, 2),
      checkTips = _useState8[0],
      setCheckTips = _useState8[1];

  useEffect(function () {
    check();
  }, []);

  function changeModalFooter(flag) {
    if (flag) {
      modal.update({
        footer: [/*#__PURE__*/React.createElement(_Button, {
          key: "back",
          onClick: handClose.bind(this, false),
          disabled: stopLoading || passLoading
        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "pipelineRecord.check.cancel"
        })), /*#__PURE__*/React.createElement(_Button, {
          key: "stop",
          loading: stopLoading,
          type: "primary",
          onClick: handleSubmit.bind(this, 'refused'),
          disabled: passLoading
        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "pipelineRecord.check.stop"
        })), /*#__PURE__*/React.createElement(_Button, {
          key: "pass",
          loading: passLoading,
          type: "primary",
          onClick: handleSubmit.bind(this, 'passed'),
          disabled: stopLoading
        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "pipelineRecord.check.pass"
        }))]
      });
    } else {
      modal.update({
        footer: [/*#__PURE__*/React.createElement(_Button, {
          key: "back",
          type: "primary",
          onClick: handClose.bind(this, true)
        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "pipelineRecord.check.tips.button"
        }))]
      });
    }
  }

  function check() {
    return _check.apply(this, arguments);
  }
  /**
   * 中止或通过人工审核
   * @param flag 是否通过
   */


  function _check() {
    _check = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var postData, data;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              postData = {
                sourceId: type === 'stage' ? stageRecordId : taskRecordId,
                sourceType: type
              };
              _context.next = 4;
              return mainStore.canCheck(projectId, cdRecordId, postData);

            case 4:
              data = _context.sent;

              if (data && !data.failed) {
                if (data.auditStatusChanged) {
                  // 会签已被终止、或签已被审核
                  setCanCheck(false);
                  changeModalFooter(false);
                  setCheckTips(formatMessage({
                    id: "c7ncd.pipelineManage.canCheck.tips.".concat(data.currentStatus)
                  }, {
                    userName: data.auditUserName
                  }));
                } else {
                  // 预检通过
                  setCanCheck(true);
                  changeModalFooter(true);
                }
              }

              _context.next = 12;
              break;

            case 8:
              _context.prev = 8;
              _context.t0 = _context["catch"](0);
              modal.close();
              return _context.abrupt("return", false);

            case 12:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[0, 8]]);
    }));
    return _check.apply(this, arguments);
  }

  function handleSubmit(_x) {
    return _handleSubmit.apply(this, arguments);
  }
  /**
   * 关闭弹窗
   * @param flag 是否重新加载列表数据
   */


  function _handleSubmit() {
    _handleSubmit = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(result) {
      var postData, data, _ref2, auditedUserNameList, notAuditUserNameList, countersigned;

      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              postData = {
                projectId: projectId,
                cdRecordId: cdRecordId,
                stageRecordId: stageRecordId,
                result: result
              };
              result === 'passed' ? changePassLoading(true) : changeStopLoading(true);
              _context2.prev = 2;

              if (!(type === 'stage')) {
                _context2.next = 9;
                break;
              }

              _context2.next = 6;
              return mainStore.auditStage(postData);

            case 6:
              data = _context2.sent;
              _context2.next = 13;
              break;

            case 9:
              postData.jobRecordId = taskRecordId;
              _context2.next = 12;
              return mainStore.auditJob(postData);

            case 12:
              data = _context2.sent;

            case 13:
              if (data && !data.failed) {
                // 会签，非最后一人审核，返回数据：[{ audit: true 已审核 | false 未审核, loginName: "工号", realName: "姓名"}]
                _ref2 = data || {}, auditedUserNameList = _ref2.auditedUserNameList, notAuditUserNameList = _ref2.notAuditUserNameList, countersigned = _ref2.countersigned;

                if (countersigned === 1 && !isEmpty(auditedUserNameList) && !isEmpty(notAuditUserNameList)) {
                  setCanCheck(false);
                  changeModalFooter(false);
                  setCheckTips(formatMessage({
                    id: 'pipeline.check.tips.text'
                  }, {
                    checkUsers: auditedUserNameList.join('，'),
                    unCheckUsers: notAuditUserNameList.join('，')
                  }));
                } else {
                  // 或签、会签最后一人审核通过、审核终止，返回数据null
                  handClose(true);
                }
              }

              _context2.next = 19;
              break;

            case 16:
              _context2.prev = 16;
              _context2.t0 = _context2["catch"](2);
              return _context2.abrupt("return", false);

            case 19:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[2, 16]]);
    }));
    return _handleSubmit.apply(this, arguments);
  }

  function handClose(flag) {
    flag && onClose();
    modal.close();
  }

  return canCheck ? /*#__PURE__*/React.createElement(FormattedMessage, {
    id: "c7ncd.pipelineManage.record.check.".concat(type, ".des"),
    values: {
      name: name,
      stage: stageName
    }
  }) : /*#__PURE__*/React.createElement("span", null, checkTips);
};

export default injectIntl(inject('AppState')(observer(AuditModal)));