import EasyvButton from 'components/EasyvButton';
import { getPortalList, addPortal, updatePortalById, deletePortalById, copyPortalById } from 'models/spaceship';
import { PortalType } from 'models/spaceship.types';
import React, { useEffect, useMemo, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import styles from './style.less';
import FileCard from 'components/FileCard';
import EasyvSearchHeader from 'components/EasyvSearchHeader';
import { Icon } from 'components/easyDesign';
import { NavLink } from 'react-router-dom';
import EditableText from 'components/EditableText';
import classNames from 'classnames';
import EasyvTooltip from 'components/EasyvTooltip';
import EasyvModal, { useActionModalRef, useConfirmRef } from 'components/EasyvModal';
import PublishContent from '../component/PublishContent';
import orderBy from 'lodash/orderBy';
import { useTitle } from 'components/easyUse';
import { RootState } from 'models';
import { SpaceState } from 'models/space.types';
import message from 'components/message';

const Spaceship = () => {
  const space = (useSelector<RootState>((state) => state.space) || {}) as SpaceState;
  const [portalList, setPoralList] = useState<PortalType[]>([]);
  const { current } = space;
  const [search, setSearch] = useState<string>('');
  const [sortType, setSortType] = useState<'byCreatedAt' | 'byUpdatedAt'>('byUpdatedAt');
  const deletedModalRef = useConfirmRef();
  const [curActionPortalInfo, setCurActionPortalInfo] = useState<Omit<PortalType, 'navBarLayout' | 'thumbColor' | 'navigation'>>();
  const publishedModalRef = useActionModalRef();
  const dispatch = useDispatch();
  useTitle('门户管理');
  useEffect(() => {
    getPortalsData();
  }, [current]);

  const getPortalsData = () => {
    getPortalList().then((res) => {
      if (res) {
        setPoralList(res || []);
      }
    });
  };

  const publishedStatusChange = (v) => {
    updatePortalById({ ...v }).then((res) => {
      if (res) {
        setCurActionPortalInfo(res);
        getPortalsData();
      }
    });
  };

  const filterData =
    useMemo(() => {
      return orderBy(
        portalList.filter((d) => d.title.toLowerCase().includes(search.toLowerCase())),
        sortType === 'byCreatedAt' ? 'createdAt' : 'updatedAt',
        'desc'
      );
    }, [sortType, portalList, search]) || [];

  return (
    <div className={styles.spaceShipList}>
      <EasyvSearchHeader
        search={search}
        onSearchChange={(e) => setSearch(e.target.value)}
        onSelectSortTypeChange={(e) => setSortType(e)}
        currentAllScreenLength={filterData.length}
        filterScreenLength={filterData.length}
        currentGroupName="全部门户"
        isNoTrashedScreen={false}
      />
      <div className={styles.container}>
        <div onClick={() => dispatch(addPortal())} className={styles.addSpaceShip}>
          <Icon type="addPortalIcon" style={{ fontSize: '44px', lineHeight: '44px', color: 'inherit' }} />
          <span style={{ lineHeight: '20px', fontSize: '14px' }}>新建门户</span>
        </div>
        {filterData.map((item) => (
          <FileCard
            key={item.id}
            hoverRenderNode={
              <div className={styles.hoverWrapper}>
                <div className={styles.actionIcon} style={{ marginBottom: 12 }}>
                  <EasyvTooltip title="发布">
                    <i
                      className="icon iconfont icon-btn_publishhomepage"
                      onClick={() => {
                        setCurActionPortalInfo(item);
                        publishedModalRef.current?.show();
                      }}
                    />
                  </EasyvTooltip>
                  <EasyvTooltip title="复制">
                    <i
                      className={'icon iconfont icon-fuzhi1'}
                      onClick={() => {
                        const hide = message.loading('正在复制门户', 0);
                        copyPortalById(item.id).then((res) => {
                          hide();
                          if (res) {
                            message.success('复制成功');
                            getPortalsData();
                          }
                        });
                      }}
                    />
                  </EasyvTooltip>
                  <EasyvTooltip title="删除">
                    <i
                      className="icon iconfont icon-btn_delete"
                      onClick={() => {
                        setCurActionPortalInfo(item);
                        deletedModalRef.current?.show();
                      }}
                    />
                  </EasyvTooltip>
                </div>
                <div className={styles.actionIcon} style={{ justifyContent: 'space-between' }}>
                  <NavLink target="_blank" to={`/spaceShipPreview/${item.id}`}>
                    <EasyvButton theme="default">预览</EasyvButton>
                  </NavLink>
                  <NavLink to={`/spaceShipEdit/${item.id}`}>
                    <EasyvButton theme="primary">编辑</EasyvButton>
                  </NavLink>
                </div>
              </div>
            }
            renderFooter={
              <div className={styles.editaleText}>
                <EditableText
                  className={styles.screenName}
                  text={item.title}
                  onCommit={(e) => updatePortalById({ id: item.id, title: e })}
                  suffix={
                    <div className={styles.box}>
                      <i className={classNames('icon iconfont icon-bianji screenItem-content-editIcon')} />
                      {item.published ? (
                        <span className={styles.publishContainer}>
                          <i className={styles.publishedIcon} />
                          已发布
                        </span>
                      ) : (
                        <span className={styles.publishContainer}>
                          <i className={classNames(styles.publishedIcon, { [styles.noPublish]: !item.published })} />
                          未发布
                        </span>
                      )}
                    </div>
                  }
                />
              </div>
            }
          />
        ))}
      </div>

      <EasyvModal.Confirm
        ref={deletedModalRef}
        onOk={() => {
          const hide = message.loading('删除中', 0);
          deletePortalById(curActionPortalInfo?.id).then((res) => {
            hide();
            if (res) {
              message.success('删除成功');
              getPortalsData();
              return;
            }
          });
        }}
        title="提示"
        iconType="warning"
        content={<p>此操作执行后不可逆，是否确认删除?</p>}
      />

      <EasyvModal.ActionModal
        ref={publishedModalRef}
        footer={null}
        title="发布"
        content={<PublishContent curPortalBaseInfo={curActionPortalInfo} onChange={publishedStatusChange} />}
      />
    </div>
  );
};

export default Spaceship;
