import { Input, Radio, Select } from '@easyv/antd';
import classNames from 'classnames';
import EasyvButton from 'components/EasyvButton';
import message from 'components/message';
import { RootState } from 'models';
import { getScreens } from 'models/screens';
import { addNavigation, getPortalDetailById, updateNavigationById } from 'models/spaceship';
import { NavItemType, SpaceShipState } from 'models/spaceship.types';
import React, { useEffect, useMemo, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getLevelToChinese } from 'utils/spaceship';
import { deepFindOne } from 'utils/utils';
import NavTreeSelect from '../NavListSidebar/NavTreeSelect';
import styles from './style.less';

const { Option } = Select;
const RadioGroup = Radio.Group;

// 内容设置
const ContentSet = () => {
  const [navName, setNavName] = useState<string>();
  const [quotelink, setQuotelink] = useState<NavItemType['quotelink']>();
  const spaceShip = useSelector<RootState>((state) => state.spaceShip) as SpaceShipState;
  const { curSelectedKeys, curPortalBaseInfo, curPortalNavigation } = spaceShip;
  const data = deepFindOne(
    curPortalNavigation || [],
    (item) => item.id === curSelectedKeys,
    `children`,
  );
  const curSelectedNavData: NavItemType = useMemo(() => {
    setNavName(data?.name);
    setQuotelink(data?.quotelink);
    return data;
  }, [curPortalBaseInfo, curSelectedKeys]);

  const id = Number(window.location.pathname.split('/').pop());
  const dispatch = useDispatch();

  const screens = useSelector<RootState>((state) => state.screens) as RootState['screens'];
  const { list = [] } = screens;
  useEffect(() => {
    if (!list.length) {
      dispatch(getScreens());
    }
  }, []);
  const updateContentSet = (
    navConfig: Partial<
      Pick<
        NavItemType,
        'name' | 'openWay' | 'parentId' | 'quoteType' | 'quotelink' | 'rank' | 'screenId'
      >
    > &
      Pick<NavItemType, 'id' | 'portalId'>,
  ) => {
    dispatch(updateNavigationById(navConfig));
  };

  return (
    <>
      <div className={styles.afterBorder}>
        <div className={styles.contentSetHeader}>
          <span className={styles.contentSetTitle}>菜单配置</span>
          <EasyvButton
            theme="primary"
            onClick={() => {
              addNavigation({
                parentId: 0,
                name: getLevelToChinese(1),
                portalId: id,
                quoteType: -1,
                quotelink: '',
                screenId: 0,
                openWay: 1,
                rank: (curPortalNavigation?.length || 0) + 1,
              }).then((res) => {
                if (res) {
                  dispatch(getPortalDetailById(id, res.id));
                }
              });
            }}
            style={{ color: '#fff', fontSize: '12px' }}
            className={styles.btn}>
            新建一级菜单
          </EasyvButton>
        </div>
        <NavTreeSelect type="navSet" />
      </div>
      <div>
        <div className={styles.contentSetHeader}>
          <span className={styles.contentSetTitle} title={curSelectedNavData?.name}>
            {getLevelToChinese(curSelectedNavData?.level)}
          </span>
        </div>
        <div className={styles.contentSetHeader}>
          <span className={styles.btn}>菜单名称</span>
          <Input
            value={navName}
            onChange={(v: any) => setNavName(v.target.value)}
            className={styles.inputWrapper}
            onBlur={(e) => {
              const newValue = e.target.value.trim();
              if (newValue.length > 30) {
                message.error('菜单名称不为空且长度不超过30个字符');
                setNavName(curSelectedNavData?.name);
                return;
              }
              if (newValue !== curSelectedNavData.name && newValue) {
                updateContentSet({
                  id: curSelectedNavData?.id,
                  name: newValue,
                  portalId: id,
                });
                return;
              }
              setNavName(curSelectedNavData?.name);
            }}
          />
          <span className={styles.btn}>引用内容</span>
          <Select
            style={{ width: '100%' }}
            dropdownClassName={styles.selectStyle}
            placeholder="请选择引用类型"
            value={
              curSelectedNavData?.quoteType === -1
                ? '请选择引用类型'
                : curSelectedNavData?.quoteType
            }
            onChange={(v: 0 | 1 | 2) => {
              updateContentSet({
                id: curSelectedNavData?.id,
                portalId: id,
                quoteType: v,
              });
            }}
            getPopupContainer={() =>
              document.getElementById('space-ship-config-content') as HTMLElement
            }>
            <Option value={2}>可视化应用</Option>
            <Option value={1}>外部链接</Option>
            <Option value={0}>空节点</Option>
          </Select>
          {[1, 2].includes(curSelectedNavData?.quoteType) &&
            (curSelectedNavData?.quoteType === 2 ? (
              <div className={styles.refContainer}>
                <Select
                  style={{ width: '100%' }}
                  value={
                    curSelectedNavData?.screenId === 0
                      ? '请选择可视化应用'
                      : curSelectedNavData?.screenId
                  }
                  onSelect={(v: number) => {
                    if (v === curSelectedNavData.screenId) {
                      return;
                    }
                    updateContentSet({
                      id: curSelectedNavData?.id,
                      portalId: id,
                      screenId: v,
                      quoteType: curSelectedNavData?.quoteType,
                    });
                  }}
                  getPopupContainer={() =>
                    document.getElementById('space-ship-config-content') as HTMLElement
                  }
                  dropdownClassName={styles.selectStyle}>
                  {list
                    .filter((item) => !item.deletedAt)
                    .map((item) => (
                      <Option key={item.screenId} value={item.screenId} label={item.screenName}>
                        {item.screenName}
                      </Option>
                    ))}
                </Select>
              </div>
            ) : (
              <div className={styles.refContainer} style={{ minHeight: 78 }}>
                <Input.TextArea
                  value={quotelink}
                  onChange={(v) => setQuotelink(v.target.value)}
                  onBlur={(v) => {
                    if (!v.target.value.length) {
                      return;
                    }
                    if (v.target.value === curSelectedNavData?.quotelink) {
                      return;
                    }
                    if (!/[a-zA-z]+:\/\/[^\s]*/.test(v.target.value)) {
                      message.error('请输入合法的url');
                      return;
                    }
                    updateContentSet({
                      id: curSelectedNavData?.id,
                      portalId: id,
                      quotelink: v.target.value,
                      quoteType: curSelectedNavData?.quoteType,
                    });
                  }}
                  placeholder="请输入外部链接"
                  allowClear
                  className={styles.inputWrapper}
                />
              </div>
            ))}
          {[1, 2].includes(curSelectedNavData?.quoteType) && (
            <>
              <span className={styles.btn}>打开方式</span>
              <div className={classNames(styles.right, styles.radioWrapper)}>
                <RadioGroup
                  value={curSelectedNavData?.openWay}
                  onChange={(v) =>
                    updateContentSet({
                      id: curSelectedNavData?.id,
                      openWay: v.target.value,
                      portalId: id,
                    })
                  }>
                  <Radio className={styles.radioItem} value={1}>
                    当前页打开
                  </Radio>
                  <Radio className={styles.radioItem} value={2}>
                    新窗口打开
                  </Radio>
                </RadioGroup>
              </div>
            </>
          )}
        </div>
      </div>
    </>
  );
};

export default ContentSet;
