function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
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 = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
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),
    currentApp = _useContext2.currentApp;
  var _useState9 = useState(false),
    _useState10 = _slicedToArray(_useState9, 2),
    saving = _useState10[0],
    setSaving = _useState10[1];
  var _useState11 = useState(false),
    _useState12 = _slicedToArray(_useState11, 2),
    testLoading = _useState12[0],
    setTestLoading = _useState12[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,
          appId: currentApp === null || currentApp === void 0 ? void 0 : currentApp.appId,
          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;