import "choerodon-ui/lib/spin/style";
import _Spin from "@hzero-front-ui/c7n-ui/lib/Spin";
import "choerodon-ui/pro/lib/pagination/style";
import _Pagination from "choerodon-ui/pro/lib/pagination";
import "choerodon-ui/pro/lib/text-field/style";
import _TextField from "choerodon-ui/pro/lib/text-field";
import "choerodon-ui/lib/icon/style";
import _Icon from "choerodon-ui/lib/icon";
import "choerodon-ui/pro/lib/button/style";
import _Button from "choerodon-ui/pro/lib/button";
import "choerodon-ui/pro/lib/tooltip/style";
import _Tooltip from "choerodon-ui/pro/lib/tooltip";
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 _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 = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

import React, { useMemo, useImperativeHandle, useState, useEffect, useCallback } from 'react';
import { TabPage, Content, Breadcrumb, Permission, Action } from '@choerodon/boot';
import { withRouter } from 'react-router-dom';
import { FormattedMessage } from 'react-intl';
import { observer } from 'mobx-react-lite';
import filter from 'lodash/filter';
import AppServiceServices from "../services";
import { useAppTopStore } from "../stores";
import { useServiceDetailStore } from "./stores";
import HeaderButtons from "./HeaderButtons";
import TimePopover from "../../../components/timePopover/TimePopover";
import Tips from "../../../components/new-tips";
import NoData from "./images/nodata.png";
import "./index.less";
var Column = _Table.Column;
var Version = withRouter(observer(function (props) {
  var _useAppTopStore = useAppTopStore(),
      prefixCls = _useAppTopStore.prefixCls,
      intlPrefix = _useAppTopStore.intlPrefix;

  var _useServiceDetailStor = useServiceDetailStore(),
      detailDs = _useServiceDetailStor.detailDs,
      versionDs = _useServiceDetailStor.versionDs,
      formatMessage = _useServiceDetailStor.intl.formatMessage,
      AppState = _useServiceDetailStor.AppState;

  var _useState = useState([]),
      _useState2 = _slicedToArray(_useState, 2),
      selectedVersionList = _useState2[0],
      setSelectedVersionList = _useState2[1];

  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      isProjectOwner = _useState4[0],
      setIsProjectOwner = _useState4[1];

  var selectedRecordLength = useMemo(function () {
    return selectedVersionList.length;
  }, [selectedVersionList]);
  useEffect(function () {
    // 左侧详情变更后 重置选中list
    if (selectedVersionList && selectedVersionList.length && selectedVersionList.length > 0) {
      setSelectedVersionList([]);
    }
  }, [detailDs.current]);
  useEffect(function () {
    // 初始化如果有records 设置默认选中为false 防止切换tab 造成数据错误
    if (versionDs && versionDs.records && versionDs.records.length > 0) {
      versionDs.records.forEach(function (i) {
        if (i.get('checked')) {
          i.set('checked', false);
        }
      });
    }

    AppServiceServices.axiosGetCheckAdminPermission(AppState.currentMenuType.projectId).then(function (res) {
      setIsProjectOwner(res);
    });
  }, []);

  function refresh() {
    versionDs.query();
  }

  function renderTime(_ref) {
    var value = _ref.value;
    return /*#__PURE__*/React.createElement(TimePopover, {
      content: value
    });
  }

  function getTitle() {
    if (detailDs.current) {
      return detailDs.current.get('name');
    }

    return '';
  }

  function openDetail(appServiceIds) {
    var history = props.history,
        location = props.location;
    history.push("/rducm/code-lib-management/assign".concat(location.search, "&appServiceIds=").concat(appServiceIds)); // Modal.open({
    //   key: modalKey1,
    //   title: <Tips
    //     helpText={formatMessage({ id: `${intlPrefix}.detail.allocation.tips` })}
    //     title={formatMessage({ id: `${intlPrefix}.permission.manage` })}
    //   />,
    //   children: <ServicePermission
    //     dataSet={permissionDs}
    //     baseDs={detailDs}
    //     store={appServiceStore}
    //     nonePermissionDs={nonePermissionDs}
    //     intlPrefix="c7ncd.deployment"
    //     prefixCls={prefixCls}
    //     formatMessage={formatMessage}
    //     projectId={id}
    //     refresh={refresh}
    //   />,
    //   drawer: true,
    //   style: modalStyle,
    //   okText: formatMessage({ id: 'save' }),
    // });
  }

  function handleDelete(list, item) {
    var selectedRecords = list || [item];
    var version = selectedRecords[0] ? selectedRecords[0].get('version') : '';
    var modalProps = {
      title: formatMessage({
        id: "".concat(intlPrefix, ".version.delete.title")
      }),
      children: selectedRecords && selectedRecords.length > 1 ? formatMessage({
        id: "".concat(intlPrefix, ".version.delete.des")
      }, {
        version: version,
        length: selectedRecords.length
      }) : formatMessage({
        id: "".concat(intlPrefix, ".version.delete.des.single")
      }, {
        version: version
      }),
      okText: formatMessage({
        id: 'delete'
      }),
      okProps: {
        color: 'red'
      },
      cancelProps: {
        color: 'dark'
      },
      onOk: function onOk() {
        setSelectedVersionList([]);
        versionDs.records.forEach(function (i) {
          i.set('checked', false);
        });
      }
    };
    versionDs["delete"](selectedRecords, modalProps);
  }

  function renderCheckboxHeader() {
    var indeterminate = versionDs.some(function (record) {
      return record.selectable && record.isSelected;
    });
    var isSelectAll = !versionDs.some(function (record) {
      return record.selectable && !record.isSelected;
    });
    return /*#__PURE__*/React.createElement(_CheckBox, {
      checked: isSelectAll && indeterminate,
      indeterminate: !isSelectAll && indeterminate,
      onChange: function onChange(value) {
        versionDs.forEach(function (record) {
          if (record.selectable) {
            // eslint-disable-next-line no-param-reassign
            record.isSelected = value;
          }
        });
      }
    });
  }

  function renderCheckbox(_ref2) {
    var record = _ref2.record;
    return /*#__PURE__*/React.createElement(_Tooltip, {
      title: !record.selectable ? formatMessage({
        id: "".concat(intlPrefix, ".version.tips")
      }) : '',
      placement: "top"
    }, /*#__PURE__*/React.createElement(_CheckBox, {
      checked: record.isSelected,
      disabled: !record.selectable,
      onChange: function onChange(value) {
        // eslint-disable-next-line no-param-reassign
        record.isSelected = value;
      }
    }));
  }

  var renderVersionAction = function renderVersionAction(record) {
    return [{
      service: ['choerodon.code.project.develop.app-service.ps.version.delete'],
      text: formatMessage({
        id: "".concat(intlPrefix, ".version.delete")
      }),
      action: function action() {
        return handleDelete(null, record);
      },
      disabled: !selectedRecordLength
    }];
  };

  var handleChangeListPage = function handleChangeListPage(page, pageSize) {
    versionDs.pageSize = pageSize;
    versionDs.query(page);
  };

  function handleChangeSearch(value) {
    versionDs.setQueryParameter('params', value);
    versionDs.query();
  }

  var handleChangeSelectedVersionList = function handleChangeSelectedVersionList(v, record) {
    record.set('checked', v); // 如果选中

    if (v) {
      setSelectedVersionList([].concat(_toConsumableArray(selectedVersionList), [record]));
    } else {
      setSelectedVersionList(selectedVersionList.filter(function (i) {
        return i.get('id') !== record.get('id');
      }));
    }
  };

  function renderVersionButton() {
    return /*#__PURE__*/React.createElement(Permission, {
      service: ['choerodon.code.project.develop.app-service.ps.version.delete']
    }, /*#__PURE__*/React.createElement(_Tooltip, {
      title: selectedVersionList.length === 0 && '请在下方列表中选择服务版本'
    }, /*#__PURE__*/React.createElement(_Button, {
      disabled: selectedVersionList.length === 0,
      onClick: function onClick() {
        return handleDelete(selectedVersionList);
      },
      style: {
        position: 'absolute',
        zIndex: 100,
        right: 0,
        top: '-32px'
      },
      funcType: "flat",
      icon: "delete_sweep-o"
    }, "\u5220\u9664\u7248\u672C")));
  }

  var renderTheme4Version = useCallback(function () {
    return /*#__PURE__*/React.createElement(_Spin, {
      spinning: versionDs.status !== 'ready'
    }, renderVersionButton(), /*#__PURE__*/React.createElement("div", {
      className: "c7ncd-theme4-version"
    }, /*#__PURE__*/React.createElement(_TextField, {
      placeholder: "\u641C\u7D22\u670D\u52A1\u7248\u672C",
      style: {
        width: '100%'
      },
      prefix: /*#__PURE__*/React.createElement(_Icon, {
        type: "search"
      }),
      onEnterDown: function onEnterDown(e) {
        return handleChangeSearch(e.target.value);
      },
      onChange: handleChangeSearch
    }), versionDs.records && versionDs.records.length > 0 ? /*#__PURE__*/React.createElement(React.Fragment, null, versionDs.records.map(function (version) {
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
        className: "c7ncd-theme4-version-item"
      }, /*#__PURE__*/React.createElement("div", {
        className: "c7ncd-theme4-version-item-side"
      }, isProjectOwner && /*#__PURE__*/React.createElement(_CheckBox, {
        style: {
          marginRight: 5
        },
        checked: version.get('checked'),
        onChange: function onChange(value) {
          return handleChangeSelectedVersionList(value, version);
        }
      }), /*#__PURE__*/React.createElement("span", {
        className: "c7ncd-theme4-version-item-version"
      }, version.get('version')), /*#__PURE__*/React.createElement(Action, {
        data: renderVersionAction(version)
      })), /*#__PURE__*/React.createElement("div", {
        style: {
          justifyContent: 'flex-end'
        },
        className: "c7ncd-theme4-version-item-side"
      }, /*#__PURE__*/React.createElement("span", {
        className: "c7ncd-theme4-version-item-text"
      }, "\u521B\u5EFA\u4E8E"), /*#__PURE__*/React.createElement(TimePopover, {
        content: version.get('creationDate')
      }))), (version === null || version === void 0 ? void 0 : version.get('unfold')) && /*#__PURE__*/React.createElement("div", {
        className: "c7ncd-theme4-version-unfold"
      }, /*#__PURE__*/React.createElement("p", {
        className: "c7ncd-theme4-version-unfold-list"
      }, "\u5173\u8054\u5236\u54C1\u6E05\u5355")));
    }), /*#__PURE__*/React.createElement(_Pagination, {
      total: versionDs.totalCount,
      pageSize: versionDs.pageSize,
      page: versionDs.currentPage,
      onChange: handleChangeListPage,
      style: {
        marginTop: '17px',
        "float": 'right'
      }
    })) : [/*#__PURE__*/React.createElement("img", {
      className: "c7ncd-theme4-version-item-nodata",
      src: NoData,
      alt: ""
    }), /*#__PURE__*/React.createElement("p", {
      className: "c7ncd-theme4-version-item-nodataText"
    }, "\u6682\u65E0\u670D\u52A1\u7248\u672C")]));
  }, [versionDs.records, selectedVersionList, isProjectOwner]);
  return AppState.getCurrentTheme === 'theme4' ? /*#__PURE__*/React.createElement(HeaderButtons, {
    theme4: true
  }, renderTheme4Version()) : /*#__PURE__*/React.createElement(TabPage, {
    service: []
  }, /*#__PURE__*/React.createElement(HeaderButtons, null, /*#__PURE__*/React.createElement(Permission, {
    service: ['choerodon.code.project.develop.app-service.ps.permission.update']
  }, /*#__PURE__*/React.createElement(_Button, {
    icon: "authority",
    onClick: function onClick() {
      return openDetail(props.match.params.id);
    },
    className: "".concat(prefixCls, "-detail-content-version-btn")
  }, "\u6743\u9650\u7BA1\u7406")), /*#__PURE__*/React.createElement(Permission, {
    service: ['choerodon.code.project.develop.app-service.ps.version.delete']
  }, /*#__PURE__*/React.createElement(_Tooltip, {
    title: selectedRecordLength ? '' : formatMessage({
      id: "".concat(intlPrefix, ".version.delete.disable")
    })
  }, /*#__PURE__*/React.createElement(_Button, {
    icon: "delete",
    onClick: handleDelete,
    disabled: !selectedRecordLength
  }, formatMessage({
    id: "".concat(intlPrefix, ".version.delete")
  })))), /*#__PURE__*/React.createElement(_Button, {
    icon: "refresh",
    onClick: refresh
  }, /*#__PURE__*/React.createElement(FormattedMessage, {
    id: "refresh"
  }))), /*#__PURE__*/React.createElement(Breadcrumb, {
    title: getTitle()
  }), /*#__PURE__*/React.createElement(Content, {
    className: "".concat(prefixCls, "-detail-content")
  }, /*#__PURE__*/React.createElement(_Table, {
    dataSet: versionDs
  }, /*#__PURE__*/React.createElement(Column, {
    header: renderCheckboxHeader,
    renderer: renderCheckbox,
    width: 50
  }), /*#__PURE__*/React.createElement(Column, {
    name: "version",
    sortable: true
  }), /*#__PURE__*/React.createElement(Column, {
    name: "creationDate",
    renderer: renderTime,
    sortable: true
  }))));
}));
export default Version;