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 _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _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(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
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, { 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(),
    _useState0 = _slicedToArray(_useState9, 2),
    ftpInfo = _useState0[0],
    setFtpInfo = _useState0[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;