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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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, { createContext, createRef, useContext, useEffect, useState } from 'react';
import { Button, Form, Input, message } from 'antd';
import { BizGlobalDataContext, ajax } from '@zgfe/business-lib';
import './index.less';
import FileTypeSwitch from './typeSwitch';
import FileList from './fileList';
import apis from '../../constants/api';
import LinkLayout from '../linkEditor/layout';
export var classPrefix = 'cdp-file';
export var LinkNameColumn = function LinkNameColumn() {
  return /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u6570\u636E\u5E93\u8FDE\u63A5\u540D\u79F0",
    name: "name",
    rules: [{
      required: true,
      validator: function validator(rule, value, callback) {
        // 输入内容不允许包含空格
        if (value === null || value === void 0 ? void 0 : value.includes(' ')) {
          return Promise.reject('不允许包含空格');
        }
        if (!value) {
          return Promise.reject('连接名称不能为空');
        }
        return Promise.resolve();
      }
    }]
  }, /*#__PURE__*/React.createElement(Input, {
    type: "text",
    placeholder: "\u8BF7\u8F93\u5165",
    maxLength: 20
  }));
};
export var ExcelLinkContext = /*#__PURE__*/createContext({});
var FileLink = function FileLink(_ref) {
  var _category$columns3;
  var data = _ref.data,
    category = _ref.category,
    onOk = _ref.onOk,
    onCancel = _ref.onCancel;
  var _useContext = useContext(BizGlobalDataContext),
    isDemo = _useContext.isDemo;
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    fileList = _useState2[0],
    setFileList = _useState2[1];
  var _useState3 = useState('ftp'),
    _useState4 = _slicedToArray(_useState3, 2),
    type = _useState4[0],
    setType = _useState4[1];
  var formRef = /*#__PURE__*/createRef();
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    loading = _useState6[0],
    setLoading = _useState6[1];
  var _useState7 = useState(false),
    _useState8 = _slicedToArray(_useState7, 2),
    inTesting = _useState8[0],
    setInTesting = _useState8[1];
  var _useContext2 = useContext(BizGlobalDataContext),
    currentProject = _useContext2.currentProject;
  var _message$useMessage = message.useMessage(),
    _message$useMessage2 = _slicedToArray(_message$useMessage, 2),
    messageApi = _message$useMessage2[0],
    contextHolder = _message$useMessage2[1];
  var _useState9 = useState(),
    _useState10 = _slicedToArray(_useState9, 2),
    ftpInfo = _useState10[0],
    setFtpInfo = _useState10[1];
  function onUpload(fileName) {
    // 如果文件已覆盖，则跳过
    if (fileList.includes(fileName)) return;
    setFileList(function (list) {
      return [].concat(_toConsumableArray(list), [fileName]);
    });
  }
  useEffect(function () {
    if (data) {
      var _data$cdpExcelColumns;
      setFileList(data === null || data === void 0 ? void 0 : (_data$cdpExcelColumns = data.cdpExcelColumns) === null || _data$cdpExcelColumns === void 0 ? void 0 : _data$cdpExcelColumns.map(function (item) {
        return item.fileName;
      }));
    }
  }, []);
  function onSubmit(values) {
    setLoading(true);
    ajax(apis.createExcelLink, {
      method: 'post',
      data: _objectSpread(_objectSpread({}, values), {}, {
        id: data === null || data === void 0 ? void 0 : data.id,
        projectId: currentProject === null || currentProject === void 0 ? void 0 : currentProject.projectId
      })
    }).then(function (res) {
      if (!res) return;
      if (onOk) onOk(res.data);
      messageApi.success('保存成功');
    }).catch(function (err) {
      console.error('创建excel数据源失败', err);
    }).finally(function () {
      setLoading(false);
    });
  }
  function onTest() {
    var _formRef$current, _category$columns;
    (_formRef$current = formRef.current) === null || _formRef$current === void 0 ? void 0 : _formRef$current.validateFields(category === null || category === void 0 ? void 0 : (_category$columns = category.columns) === null || _category$columns === void 0 ? void 0 : _category$columns.map(function (item) {
      return item.name;
    })).then(function (data) {
      setInTesting(true);
      ajax(apis.ftpTest, {
        method: 'post',
        data: data
      }).then(function (res) {
        if (!res) return;
        if (res) {
          messageApi.success('连接成功');
        }
        setFtpInfo(data);
        setFileList(res.data);
      }).catch(function (err) {
        console.error('测试失败', err);
        messageApi.error('连接失败');
      }).finally(function () {
        setInTesting(false);
      });
    });
  }
  return /*#__PURE__*/React.createElement(ExcelLinkContext.Provider, {
    value: {
      editLink: data,
      linkType: type,
      ftpInfo: ftpInfo,
      fileList: fileList
    }
  }, contextHolder, /*#__PURE__*/React.createElement(LinkLayout, {
    editLink: data,
    category: category,
    footer: /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Button, {
      onClick: onCancel
    }, "\u53D6\u6D88"), type === 'ftp' && /*#__PURE__*/React.createElement(Button, {
      type: "primary",
      onClick: onTest,
      disabled: isDemo,
      loading: inTesting
    }, "\u6D4B\u8BD5\u8FDE\u63A5"), /*#__PURE__*/React.createElement(Button, {
      type: "primary",
      disabled: isDemo,
      onClick: function onClick() {
        var _formRef$current2;
        (_formRef$current2 = formRef.current) === null || _formRef$current2 === void 0 ? void 0 : _formRef$current2.submit();
      },
      loading: loading
    }, "\u4FDD\u5B58"))
  }, /*#__PURE__*/React.createElement(Form, {
    ref: formRef,
    onFinish: onSubmit,
    colon: false,
    initialValues: _objectSpread(_objectSpread({}, data), {}, {
      uploadFiles: data === null || data === void 0 ? void 0 : data.cdpExcelColumns
    })
  }, /*#__PURE__*/React.createElement(LinkNameColumn, null), /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u65B9\u5F0F",
    name: "type"
  }, /*#__PURE__*/React.createElement(FileTypeSwitch, {
    onUpload: onUpload,
    onChange: function onChange(t) {
      var _formRef$current3, _category$columns2;
      setType(t);
      setFtpInfo(undefined);
      setFileList([]);
      (_formRef$current3 = formRef.current) === null || _formRef$current3 === void 0 ? void 0 : _formRef$current3.resetFields(category === null || category === void 0 ? void 0 : (_category$columns2 = category.columns) === null || _category$columns2 === void 0 ? void 0 : _category$columns2.map(function (item) {
        return item.name;
      }));
    }
  })), type === 'ftp' && /*#__PURE__*/React.createElement(React.Fragment, null, category === null || category === void 0 ? void 0 : (_category$columns3 = category.columns) === null || _category$columns3 === void 0 ? void 0 : _category$columns3.map(function (item) {
    return /*#__PURE__*/React.createElement(Form.Item, {
      label: item.label,
      name: item.name,
      key: item.name,
      rules: [{
        required: item.required,
        pattern: item.rules ? new RegExp(item.rules) : undefined,
        message: item.message || "\u8BF7\u8F93\u5165\u6B63\u786E\u7684".concat(item.label)
      }]
    }, /*#__PURE__*/React.createElement(Input, {
      type: item.type || 'text',
      placeholder: "\u8BF7\u8F93\u5165"
    }));
  })), /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u6587\u4EF6\u5217\u8868",
    name: "uploadFiles",
    className: "".concat(classPrefix, "-list-label")
  }, /*#__PURE__*/React.createElement(FileList, {
    onRemove: function onRemove(file) {
      setFileList(function (list) {
        return list.filter(function (item) {
          return item !== file;
        });
      });
    }
  })))));
};
export default FileLink;