import "choerodon-ui/pro/lib/form/style";
import _Form from "@hzero-front-ui/c7n-ui/lib/FormPro";
import "choerodon-ui/pro/lib/text-field/style";
import _TextField from "choerodon-ui/pro/lib/text-field";
import "choerodon-ui/pro/lib/icon/style";
import _Icon from "choerodon-ui/pro/lib/icon";
import "choerodon-ui/pro/lib/select/style";
import _Select from "choerodon-ui/pro/lib/select";
import "choerodon-ui/pro/lib/button/style";
import _Button from "choerodon-ui/pro/lib/button";
import "choerodon-ui/pro/lib/spin/style";
import _Spin from "choerodon-ui/pro/lib/spin";
import "choerodon-ui/pro/lib/check-box/style";
import _CheckBox from "choerodon-ui/pro/lib/check-box";
import "choerodon-ui/pro/lib/table/style";
import _Table from "@hzero-front-ui/c7n-ui/lib/TablePro";

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

/* eslint-disable no-param-reassign */
import React, { useCallback } from 'react';
import { observer } from 'mobx-react-lite';
import { forEach, isEmpty } from 'lodash';
import { useMarketTableStore } from "./stores";
import "./index.less";
var Column = _Table.Column;
var MarketSourceTable = observer(function () {
  var _useMarketTableStore = useMarketTableStore(),
      formatMessage = _useMarketTableStore.formatMessage,
      intlPrefix = _useMarketTableStore.intlPrefix,
      prefixCls = _useMarketTableStore.prefixCls,
      modal = _useMarketTableStore.modal,
      selectedDs = _useMarketTableStore.selectedDs,
      tableDs = _useMarketTableStore.tableDs,
      searchDs = _useMarketTableStore.searchDs,
      checkData = _useMarketTableStore.checkData,
      setAppChildren = _useMarketTableStore.setAppChildren,
      setVersionChildren = _useMarketTableStore.setVersionChildren,
      getChecked = _useMarketTableStore.getChecked,
      getIndeterminate = _useMarketTableStore.getIndeterminate,
      getAppIndeterminate = _useMarketTableStore.getAppIndeterminate,
      handleMarketServiceCheck = _useMarketTableStore.handleMarketServiceCheck,
      handleAppExpand = _useMarketTableStore.handleAppExpand,
      handleVersionExpand = _useMarketTableStore.handleVersionExpand;

  modal.handleOk( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
    var records;
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            records = [];
            tableDs.forEach(function (record) {
              if (record.isSelected || record.get('indeterminate')) {
                var childDs = record.get('childrenDataSet');

                if (childDs && childDs.length) {
                  childDs.forEach(function (eachRecord) {
                    if (eachRecord.isSelected || eachRecord.get('indeterminate')) {
                      var marketDs = eachRecord.get('childrenDataSet');

                      if (marketDs && !isEmpty(marketDs.selected)) {
                        forEach(marketDs.selected, function (childRecord) {
                          var selected = selectedDs.find(function (selectedRecord) {
                            return selectedRecord.get('deployObjectId') === childRecord.get('deployObjectId');
                          });

                          if (!selected) {
                            var newRecord = selectedDs.create({
                              id: childRecord.get('deployObjectId'),
                              name: childRecord.get('marketServiceName'),
                              sourceProject: record.get('sourceProject'),
                              deployObjectId: childRecord.get('deployObjectId'),
                              versionName: childRecord.get('marketServiceVersion'),
                              marketAppId: record.get('id'),
                              marketAppVersionId: eachRecord.get('id'),
                              sourceApp: "".concat(record.get('name'), "-").concat(eachRecord.get('versionNumber'))
                            });
                            records.push(newRecord);
                          } else {
                            records.push(selected);
                          }
                        });
                      }
                    }
                  });
                }
              }
            }, []);
            selectedDs.removeAll();
            _context.next = 5;
            return selectedDs.push.apply(selectedDs, records);

          case 5:
            checkData();

          case 6:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  })));
  var handleTableHeaderCheck = useCallback(function (checked) {
    if (checked) {
      tableDs.selectAll();
    } else {
      tableDs.unSelectAll();
    }
  }, []);
  var handleVersionHeaderCheck = useCallback(function (_ref2) {
    var checked = _ref2.checked,
        record = _ref2.record;

    if (checked) {
      tableDs.select(record);
    } else {
      tableDs.unSelect(record);
    }
  }, []);
  var handleVersionCheck = useCallback( /*#__PURE__*/function () {
    var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(_ref3) {
      var checked, childRecord, childDs, parentRecord;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              checked = _ref3.checked, childRecord = _ref3.childRecord, childDs = _ref3.childDs, parentRecord = _ref3.parentRecord;

              if (checked) {
                childDs.select(childRecord);
              } else {
                childDs.unSelect(childRecord);
              }

              parentRecord.isSelected = getChecked(parentRecord) && !getIndeterminate(parentRecord);
              parentRecord.set('indeterminate', getAppIndeterminate(parentRecord));

            case 4:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));

    return function (_x) {
      return _ref4.apply(this, arguments);
    };
  }(), []);

  var renderCheckBoxHeader = function renderCheckBoxHeader() {
    return /*#__PURE__*/React.createElement(_CheckBox, {
      checked: !isEmpty(tableDs.selected) && tableDs.selected.length === tableDs.length,
      indeterminate: tableDs.some(function (record) {
        return record.get('indeterminate');
      }) || !!tableDs.selected.length && tableDs.selected.length !== tableDs.length,
      onChange: handleTableHeaderCheck
    });
  };

  var renderCheckBox = useCallback(function (_ref5) {
    var record = _ref5.record;
    return /*#__PURE__*/React.createElement(_CheckBox, {
      checked: record.isSelected,
      indeterminate: !record.isSelected && record.get('indeterminate'),
      onChange: function onChange(checked) {
        return handleVersionHeaderCheck({
          checked: checked,
          record: record
        });
      }
    });
  }, []);
  var renderExpandedRow = useCallback(function (_ref6) {
    var dataSet = _ref6.dataSet,
        record = _ref6.record;
    var childrenDataSet = record.get('childrenDataSet');

    if (!childrenDataSet || childrenDataSet.status === 'loading') {
      return /*#__PURE__*/React.createElement(_Spin, null);
    }

    return /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-expand")
    }, /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-expand-header")
    }, /*#__PURE__*/React.createElement(_CheckBox, {
      checked: record.isSelected,
      indeterminate: !record.isSelected && record.get('indeterminate'),
      onChange: function onChange(checked) {
        return handleVersionHeaderCheck({
          checked: checked,
          record: record
        });
      },
      style: {
        width: 40
      }
    }), /*#__PURE__*/React.createElement("span", {
      style: {
        width: '30%'
      }
    }, "\u5E94\u7528\u7248\u672C"), /*#__PURE__*/React.createElement("span", {
      style: {
        width: '30%'
      }
    }, "\u53D1\u5E03\u65F6\u95F4"), /*#__PURE__*/React.createElement("span", {
      style: {
        width: '30%'
      }
    }, "\u6700\u8FD1\u66F4\u65B0"), /*#__PURE__*/React.createElement("span", {
      style: {
        width: 30
      }
    })), /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-expand-main")
    }, record.get('childrenDataSet').map(function (eachRecord) {
      return /*#__PURE__*/React.createElement("div", {
        key: eachRecord.id,
        className: "".concat(prefixCls, "-expand-content")
      }, /*#__PURE__*/React.createElement("span", {
        className: "".concat(prefixCls, "-expand-content-border")
      }), /*#__PURE__*/React.createElement("div", {
        className: "".concat(prefixCls, "-expand-item")
      }, /*#__PURE__*/React.createElement("div", {
        className: "".concat(prefixCls, "-expand-item-header")
      }, /*#__PURE__*/React.createElement(_CheckBox, {
        checked: eachRecord.isSelected,
        indeterminate: !eachRecord.isSelected && eachRecord.get('indeterminate'),
        onChange: function onChange(checked) {
          return handleVersionCheck({
            checked: checked,
            childRecord: eachRecord,
            childDs: record.get('childrenDataSet'),
            parentRecord: record
          });
        },
        style: {
          width: 40
        }
      }), /*#__PURE__*/React.createElement("span", {
        style: {
          width: '30%'
        }
      }, eachRecord.get('versionNumber')), /*#__PURE__*/React.createElement("span", {
        style: {
          width: '30%'
        }
      }, eachRecord.get('releaseDate')), /*#__PURE__*/React.createElement("span", {
        style: {
          width: '30%'
        }
      }, eachRecord.get('lastUpdateDate')), /*#__PURE__*/React.createElement("span", {
        style: {
          width: 30
        }
      }, /*#__PURE__*/React.createElement(_Button, {
        icon: eachRecord.get('expand') ? 'expand_less' : 'navigate_next',
        onClick: function onClick() {
          return handleVersionExpand(eachRecord);
        }
      }))), eachRecord.get('expand') && /*#__PURE__*/React.createElement("div", {
        className: "".concat(prefixCls, "-expand-market-service")
      }, !eachRecord.get('childrenDataSet') || eachRecord.get('childrenDataSet').status === 'loading' ? /*#__PURE__*/React.createElement(_Spin, null) : eachRecord.get('childrenDataSet').map(function (childRecord) {
        return /*#__PURE__*/React.createElement("div", {
          key: childRecord.id,
          className: "".concat(prefixCls, "-expand-market-service-item ").concat(childRecord.isSelected ? "".concat(prefixCls, "-expand-market-service-item-selected") : '')
        }, /*#__PURE__*/React.createElement("div", {
          className: "".concat(prefixCls, "-expand-market-service-item-content")
        }, /*#__PURE__*/React.createElement(_CheckBox, {
          checked: childRecord.isSelected,
          onChange: function onChange(checked) {
            return handleMarketServiceCheck({
              checked: checked,
              childRecord: childRecord,
              childDs: eachRecord.get('childrenDataSet'),
              parentDs: record.get('childrenDataSet'),
              parentRecord: eachRecord,
              record: record
            });
          }
        }), /*#__PURE__*/React.createElement("div", {
          className: "".concat(prefixCls, "-expand-market-service-item-text")
        }, /*#__PURE__*/React.createElement("div", null, "\u5E02\u573A\u670D\u52A1\u540D\u79F0\uFF1A", /*#__PURE__*/React.createElement("span", {
          className: "".concat(prefixCls, "-expand-market-service-item-span")
        }, childRecord.get('marketServiceName'))), /*#__PURE__*/React.createElement("div", null, "\u5E02\u573A\u670D\u52A1\u7248\u672C\uFF1A", /*#__PURE__*/React.createElement("span", {
          className: "".concat(prefixCls, "-expand-market-service-item-span")
        }, childRecord.get('marketServiceVersion'))))));
      }))));
    })));
  }, []);
  return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-tips")
  }, /*#__PURE__*/React.createElement("span", null, "\u6B64\u9875\u9762\u4EC5\u4F1A\u663E\u793A\u51FA\u53D1\u5E03\u4E86\u6E90\u4EE3\u7801\u7684\u5E02\u573A\u670D\u52A1\u3002")), /*#__PURE__*/React.createElement(_Form, {
    dataSet: searchDs,
    columns: 4
  }, /*#__PURE__*/React.createElement(_Select, {
    name: "app",
    searchable: true
  }), /*#__PURE__*/React.createElement(_Select, {
    name: "market_app_version_id"
  }), /*#__PURE__*/React.createElement(_TextField, {
    name: "params",
    colSpan: 2,
    prefix: /*#__PURE__*/React.createElement(_Icon, {
      type: "search",
      className: "".concat(prefixCls, "-prefix-icon")
    }),
    placeholder: formatMessage({
      id: 'search.placeholder'
    })
  })), /*#__PURE__*/React.createElement(_Table, {
    dataSet: tableDs,
    queryBar: 'none',
    expandedRowRenderer: renderExpandedRow,
    expandIconColumnIndex: 1 // @ts-ignore
    ,
    expandIconAsCell: false,
    selectionMode: 'node',
    onExpand: handleAppExpand
  }, /*#__PURE__*/React.createElement(Column, {
    name: "checked",
    renderer: renderCheckBox // header={renderCheckBoxHeader}
    ,
    width: 45
  }), /*#__PURE__*/React.createElement(Column, {
    name: "name"
  }), /*#__PURE__*/React.createElement(Column, {
    name: "sourceProject"
  }), /*#__PURE__*/React.createElement(Column, {
    name: "lastUpdateDate",
    width: 170
  })));
});
export default MarketSourceTable;