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 { BizGlobalDataContext, IconFont } from '@zgfe/business-lib';
import { Form, Input, Select, Skeleton } from 'antd';
import React, { useContext, useEffect, useRef, useState, useImperativeHandle } from 'react';
import apis from '../../constants/api';
import TaskContext from '../../modules/createJob/context';
import request from '../../utils/ajax';
import './styles/tableSelect.less';
import { CdpContext } from '../../context';
var TableSelect = function TableSelect(props, ref) {
  var task = props.task;
  var _useContext = useContext(TaskContext),
    mode = _useContext.mode;
  var classPrefix = 'cdp-table-select';
  var _useContext2 = useContext(BizGlobalDataContext),
    currentProject = _useContext2.currentProject;
  // 数据源列表
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    sourceList = _useState2[0],
    setSourceList = _useState2[1];
  var _useState3 = useState(),
    _useState4 = _slicedToArray(_useState3, 2),
    database = _useState4[0],
    setDatabase = _useState4[1];
  var _useState5 = useState([]),
    _useState6 = _slicedToArray(_useState5, 2),
    tableList = _useState6[0],
    setTableList = _useState6[1];
  var _useState7 = useState(),
    _useState8 = _slicedToArray(_useState7, 2),
    table = _useState8[0],
    setTable = _useState8[1];
  var _useState9 = useState(''),
    _useState10 = _slicedToArray(_useState9, 2),
    dataset = _useState10[0],
    setDataset = _useState10[1];
  var _useState11 = useState(false),
    _useState12 = _slicedToArray(_useState11, 2),
    sourceLoading = _useState12[0],
    setSourceLoading = _useState12[1];
  var _useState13 = useState(false),
    _useState14 = _slicedToArray(_useState13, 2),
    tableLoading = _useState14[0],
    setTableLoading = _useState14[1];
  var _useContext3 = useContext(CdpContext),
    categoryList = _useContext3.categoryList;
  var _useState15 = useState(),
    _useState16 = _slicedToArray(_useState15, 2),
    dbType = _useState16[0],
    setDbType = _useState16[1];
  var _useState17 = useState(false),
    _useState18 = _slicedToArray(_useState17, 2),
    initing = _useState18[0],
    setIniting = _useState18[1];
  var formRef = useRef(null);
  useEffect(function () {
    if (!task) return;
    setIniting(true);
    // 初始化数据库类型
    setDbType({
      name: task.dbType,
      label: task.dbType
    });
    setDataset(task.datasetName);
  }, []);
  /**
   * 切换数据库类型时，根据类型动态切换数据源列表
   */
  useEffect(function () {
    var _formRef$current;
    if (!dbType) return;
    /**
     * 编辑模式不再查询数据源，因为数据源有可能被删除
     */
    if (mode === 'edit') {
      var list = [{
        id: task === null || task === void 0 ? void 0 : task.dbSourceId,
        name: task === null || task === void 0 ? void 0 : task.dbSourceName,
        type: task === null || task === void 0 ? void 0 : task.dbType
      }];
      setSourceList(list);
      setDatabase(list[0]);
      setSourceLoading(false);
      return;
    }
    setSourceList([]);
    setTableList([]);
    setSourceLoading(true);
    (_formRef$current = formRef.current) === null || _formRef$current === void 0 ? void 0 : _formRef$current.resetFields(['database', 'table']);
    request(apis.queryLinkSimpleList, {
      method: 'get',
      params: {
        projectId: currentProject === null || currentProject === void 0 ? void 0 : currentProject.projectId,
        type: dbType === null || dbType === void 0 ? void 0 : dbType.name
      }
    }).then(function (res) {
      if (!res) throw new Error();
      setSourceList(res.data || []);
      // 如果当前处于初始化进度中，则初始化默认数据源
      if (initing) {
        var _res$data;
        (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.forEach(function (item) {
          if ((task === null || task === void 0 ? void 0 : task.dbSourceId) === item.id) {
            setDatabase(item);
          }
        });
      }
    }).catch(function (err) {
      console.error('检索数据源列表失败', err);
    }).finally(function () {
      setSourceLoading(false);
    });
  }, [dbType]);
  /**
   * 根据数据源，查询表列表
   */
  useEffect(function () {
    var _formRef$current2;
    setTableList([]);
    setTable(undefined);
    if ((dbType === null || dbType === void 0 ? void 0 : dbType.name) === 'api') {
      setIniting(false);
      return;
    }
    if (!database) return;
    (_formRef$current2 = formRef.current) === null || _formRef$current2 === void 0 ? void 0 : _formRef$current2.resetFields(['table']);
    setTableLoading(true);
    request(apis.queryTable, {
      method: 'get',
      params: {
        id: database === null || database === void 0 ? void 0 : database.id
      }
    }).then(function (res) {
      if (!res) throw new Error();
      var list = res.data.map(function (table) {
        return {
          id: table,
          label: table
        };
      });
      setTableList(list);
      if (initing) {
        list.forEach(function (item) {
          if ((task === null || task === void 0 ? void 0 : task.dbTableName) === item.id) {
            setTable(item);
          }
        });
        setIniting(false);
      }
    }).catch(function (err) {
      console.error('查询数据表列表失败', err);
    }).finally(function () {
      setTableLoading(false);
    });
  }, [database]);
  useImperativeHandle(ref, function () {
    return {
      formSubmit: function formSubmit() {
        var _formRef$current3;
        (_formRef$current3 = formRef.current) === null || _formRef$current3 === void 0 ? void 0 : _formRef$current3.submit();
      }
    };
  });
  function _onChange() {
    var _formRef$current4;
    (_formRef$current4 = formRef.current) === null || _formRef$current4 === void 0 ? void 0 : _formRef$current4.submit();
  }
  useEffect(function () {
    var _formRef$current5;
    if (initing) return;
    (_formRef$current5 = formRef.current) === null || _formRef$current5 === void 0 ? void 0 : _formRef$current5.submit();
  }, [initing]);
  // 提交表单
  useEffect(function () {
    var _formRef$current6;
    (_formRef$current6 = formRef.current) === null || _formRef$current6 === void 0 ? void 0 : _formRef$current6.submit();
  }, [dbType, database, table, dataset]);
  function onSubmit(formData) {
    if (props.onChange) props.onChange(formData);
  }
  if (initing) {
    return /*#__PURE__*/React.createElement("div", {
      className: classPrefix
    }, /*#__PURE__*/React.createElement(Skeleton.Input, null));
  }
  return /*#__PURE__*/React.createElement("div", {
    className: classPrefix
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-title")
  }, "\u6570\u636E\u5E93\u4FE1\u606F"), /*#__PURE__*/React.createElement(Form, {
    ref: formRef,
    layout: "inline",
    colon: false,
    className: "".concat(classPrefix, "-form"),
    initialValues: mode === 'edit' ? {
      dbType: dbType === null || dbType === void 0 ? void 0 : dbType.name,
      database: database === null || database === void 0 ? void 0 : database.id,
      table: table === null || table === void 0 ? void 0 : table.id,
      dataset: dataset
    } : undefined,
    autoComplete: "off",
    onFinish: onSubmit
  }, /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u6570\u636E\u96C6\u540D\u79F0",
    name: "dataset"
  }, /*#__PURE__*/React.createElement(Input, {
    disabled: mode === 'edit',
    placeholder: "\u8BF7\u8F93\u5165\u6570\u636E\u96C6\u540D\u79F0",
    onChange: function onChange(e) {
      e.persist();
      setDataset(e.target.value);
      _onChange();
    },
    maxLength: 50,
    showCount: true
  })), /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-form-div-box")
  }, /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u6570\u636E\u5E93\u7C7B\u578B",
    name: "dbType"
  }, /*#__PURE__*/React.createElement(Select, {
    options: categoryList,
    suffixIcon: /*#__PURE__*/React.createElement(IconFont, {
      type: "xiangxia"
    }),
    placeholder: "\u8BF7\u9009\u62E9\u6570\u636E\u5E93\u7C7B\u578B",
    fieldNames: {
      value: 'name',
      label: 'label'
    },
    showSearch: true,
    filterOption: function filterOption(input, option) {
      var _option$label;
      return ((_option$label = option === null || option === void 0 ? void 0 : option.label) !== null && _option$label !== void 0 ? _option$label : '').toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    disabled: mode === 'edit',
    onChange: function onChange(value, option) {
      setDbType(option);
      _onChange();
    }
  })), /*#__PURE__*/React.createElement(Form.Item, {
    label: "\u6570\u636E\u6E90",
    name: "database"
  }, sourceLoading ? /*#__PURE__*/React.createElement(Skeleton.Input, {
    active: true
  }) : /*#__PURE__*/React.createElement(Select, {
    options: sourceList,
    suffixIcon: /*#__PURE__*/React.createElement(IconFont, {
      type: "xiangxia"
    }),
    placeholder: "\u8BF7\u9009\u62E9\u6570\u636E\u6E90",
    fieldNames: {
      value: 'id',
      label: 'name'
    },
    showSearch: true,
    filterOption: function filterOption(input, option) {
      var _option$name;
      return ((_option$name = option === null || option === void 0 ? void 0 : option.name) !== null && _option$name !== void 0 ? _option$name : '').toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    disabled: mode === 'edit',
    onChange: function onChange(val, database) {
      var _formRef$current7;
      (_formRef$current7 = formRef.current) === null || _formRef$current7 === void 0 ? void 0 : _formRef$current7.resetFields(['table']);
      setDatabase(database);
      _onChange();
    }
  })), (dbType === null || dbType === void 0 ? void 0 : dbType.name) !== 'api' && /*#__PURE__*/React.createElement(Form.Item, {
    label: (dbType === null || dbType === void 0 ? void 0 : dbType.name) === 'excel' ? '选择文件' : '数据表',
    name: "table"
  }, tableLoading ? /*#__PURE__*/React.createElement(Skeleton.Input, {
    active: true
  }) : /*#__PURE__*/React.createElement(Select, {
    options: tableList,
    suffixIcon: /*#__PURE__*/React.createElement(IconFont, {
      type: "xiangxia"
    }),
    placeholder: (dbType === null || dbType === void 0 ? void 0 : dbType.name) === 'excel' ? '请选择文件' : '请选择数据表',
    fieldNames: {
      value: 'id',
      label: 'label'
    },
    showSearch: true,
    filterOption: function filterOption(input, option) {
      var _option$label2;
      return ((_option$label2 = option === null || option === void 0 ? void 0 : option.label) !== null && _option$label2 !== void 0 ? _option$label2 : '').toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    disabled: mode === 'edit',
    onChange: function onChange(val, table) {
      setTable(table);
      _onChange();
    }
  })))));
};
export default /*#__PURE__*/React.forwardRef(TableSelect);