function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _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(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
import React, { createRef, useContext, useEffect, useState } from 'react';
import LinkLayout from '../linkEditor/layout';
import { Button, Form, Input, Radio, Space, message, notification } from 'antd';
import { BizGlobalDataContext, ajax } from '@zgfe/business-lib';
import { LinkNameColumn } from '../fileLink';
import RequestParam from './request';
import './index.less';
import ApiResponse from './response';
import ResStructure from './resStructure';
import apis from '../../constants/api';
export var classPrefix = 'cdp-api';
var ApiLink = function ApiLink(_ref) {
  var data = _ref.data,
    category = _ref.category,
    onCancel = _ref.onCancel,
    onOk = _ref.onOk;
  var _useContext = useContext(BizGlobalDataContext),
    isDemo = _useContext.isDemo;
  var formRef = /*#__PURE__*/createRef();
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    inputStructure = _useState2[0],
    setInputStructure = _useState2[1];
  var _useState3 = useState([]),
    _useState4 = _slicedToArray(_useState3, 2),
    outputStructure = _useState4[0],
    setOutputStructure = _useState4[1];
  var _useState5 = useState(),
    _useState6 = _slicedToArray(_useState5, 2),
    response = _useState6[0],
    setResponse = _useState6[1];
  var _useState7 = useState(''),
    _useState8 = _slicedToArray(_useState7, 2),
    responseKey = _useState8[0],
    setResponseKey = _useState8[1];
  var _useContext2 = useContext(BizGlobalDataContext),
    currentProject = _useContext2.currentProject;
  var _useState9 = useState(false),
    _useState0 = _slicedToArray(_useState9, 2),
    saving = _useState0[0],
    setSaving = _useState0[1];
  var _useState1 = useState(false),
    _useState10 = _slicedToArray(_useState1, 2),
    testLoading = _useState10[0],
    setTestLoading = _useState10[1];
  useEffect(function () {
    if (!data) return;
    try {
      setInputStructure(JSON.parse(data.resStructure || '[]'));
    } catch (e) {
      console.error('resStructure parse error', e);
    }
  }, []);
  function onSave() {
    var _formRef$current;
    if (saving) return;
    setSaving(true);
    (_formRef$current = formRef.current) === null || _formRef$current === void 0 ? void 0 : _formRef$current.validateFields().then(function (_ref2) {
      var name = _ref2.name,
        url = _ref2.url,
        method = _ref2.method,
        params = _ref2.params;
      ajax((data === null || data === void 0 ? void 0 : data.id) ? apis.editApi : apis.createLink, {
        method: 'post',
        data: _objectSpread({
          id: data === null || data === void 0 ? void 0 : data.id,
          name: name,
          url: url,
          method: method,
          type: category.name,
          projectId: currentProject === null || currentProject === void 0 ? void 0 : currentProject.projectId,
          resStructure: outputStructure
        }, params)
      }).then(function (res) {
        if (!res) return;
        onOk === null || onOk === void 0 ? void 0 : onOk(res.data);
        message.success('保存成功');
      }).catch(function (err) {
        console.error('接口保存失败', err);
      }).finally(function () {
        setSaving(false);
      });
    }).catch(function () {
      setSaving(false);
    });
  }
  function _onTest(callback) {
    var _formRef$current2;
    if (testLoading) {
      if (callback) callback(false);
      return;
    }
    setTestLoading(true);
    (_formRef$current2 = formRef.current) === null || _formRef$current2 === void 0 ? void 0 : _formRef$current2.validateFields().then(function (_ref3) {
      var url = _ref3.url,
        method = _ref3.method,
        name = _ref3.name,
        params = _ref3.params;
      setResponse({});
      setResponseKey(Math.random().toString());
      ajax(apis.testApi, {
        method: 'post',
        data: _objectSpread({
          url: url,
          method: method,
          name: name,
          type: category.name
        }, params)
      }).then(function (res) {
        if (!res) return;
        try {
          var resp = JSON.parse(res.data);
          setResponse(resp);
          setResponseKey(Math.random().toString());
        } catch (e) {
          notification.error({
            message: '接口测试失败'
          });
        }
      }).catch(function (error) {
        console.error('接口测试失败', error);
      }).finally(function () {
        setTestLoading(false);
        if (callback) callback(false);
      });
    }).catch(function () {
      setTestLoading(false);
      if (callback) callback(false);
    });
  }
  return /*#__PURE__*/React.createElement(LinkLayout, {
    editLink: data,
    category: category,
    footer: /*#__PURE__*/React.createElement(Space, {
      size: 0
    }, /*#__PURE__*/React.createElement(Button, {
      onClick: onCancel
    }, "\u53D6\u6D88"), /*#__PURE__*/React.createElement(Button, {
      type: "primary",
      onClick: function onClick() {
        _onTest();
      },
      loading: testLoading
    }, "\u6D4B\u8BD5\u8FDE\u63A5"), /*#__PURE__*/React.createElement(Button, {
      type: "primary",
      disabled: isDemo || testLoading,
      onClick: onSave,
      loading: saving
    }, "\u4FDD\u5B58"))
  }, /*#__PURE__*/React.createElement(Form, {
    autoComplete: "off",
    colon: false,
    ref: formRef,
    initialValues: {
      method: (data === null || data === void 0 ? void 0 : data.method) || 'get',
      name: data === null || data === void 0 ? void 0 : data.name,
      url: data === null || data === void 0 ? void 0 : data.url,
      params: function () {
        try {
          return {
            params: JSON.parse((data === null || data === void 0 ? void 0 : data.params) || '{}'),
            headers: JSON.parse((data === null || data === void 0 ? void 0 : data.headers) || '{}'),
            paramType: data === null || data === void 0 ? void 0 : data.paramType,
            body: JSON === null || JSON === void 0 ? void 0 : JSON.parse((data === null || data === void 0 ? void 0 : data.body) || '{}'),
            pageSizeColumn: data === null || data === void 0 ? void 0 : data.pageSizeColumn,
            pageNumberColumn: data === null || data === void 0 ? void 0 : data.pageNumberColumn
          };
        } catch (e) {
          console.error('params parse error', e);
          return {};
        }
      }()
    }
  }, /*#__PURE__*/React.createElement(LinkNameColumn, null), /*#__PURE__*/React.createElement(Form.Item, {
    label: "URL\u5730\u5740",
    name: "url",
    rules: [{
      required: true,
      // 接口url地址校验规则
      pattern: /^((https|http)?:\/\/)[^\s]+/,
      message: '请输入正确的URL地址'
    }]
  }, /*#__PURE__*/React.createElement(Input, null)), /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u8BF7\u6C42\u65B9\u5F0F",
    name: "method",
    rules: [{
      required: true
    }]
  }, /*#__PURE__*/React.createElement(Radio.Group, null, /*#__PURE__*/React.createElement(Space, {
    size: 48
  }, /*#__PURE__*/React.createElement(Radio, {
    value: "get"
  }, "GET"), /*#__PURE__*/React.createElement(Radio, {
    value: "post"
  }, "POST")))), /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u8BF7\u6C42\u53C2\u6570",
    name: "params",
    className: "".concat(classPrefix, "-request")
  }, /*#__PURE__*/React.createElement(RequestParam, null)), /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u8FD4\u56DE\u7ED3\u679C",
    className: "".concat(classPrefix, "-response")
  }, /*#__PURE__*/React.createElement(ApiResponse, {
    testing: testLoading,
    json: response,
    structure: inputStructure,
    key: responseKey,
    onChange: setInputStructure,
    onTest: function onTest(callback) {
      setTestLoading(true);
      _onTest(callback);
    }
  })), /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u6570\u636E\u7ED3\u6784"
  }, /*#__PURE__*/React.createElement(ResStructure, {
    value: inputStructure,
    onChange: setOutputStructure
  }))));
};
export default ApiLink;