import message from 'components/message';
import SwitchWithLoading from 'components/SwitchWithLoading';
import Publish from 'containers/screen-edit/components/ScreenHeader/Publish';
import React, { useEffect, useRef, useState } from 'react';
import styles from './style.less';
import { Input, Radio } from '@easyv/antd';
import EasyvButton from 'components/EasyvButton';
import classnames from 'classnames';
import { PortalType, SpaceShipState } from 'models/spaceship.types';
import { useProductionInfo } from 'components/easyUse';
import { pwdValidate } from 'utils/utils';

interface Props {
  curPortalBaseInfo: SpaceShipState['curPortalBaseInfo'];
  onChange: (v: Partial<Omit<PortalType, 'navBarLayout' | 'thumbColor' | 'navigation' | 'id'>> & { id: number }) => void;
}

const getCopyBtnText = (encryption: boolean, encryptionType: PortalType['encryptionType']) => {
  if (encryption) {
    return encryptionType === 1 ? '复制链接及密码' : '复制链接及密钥';
  }
  return '复制';
};

const getShareUrlByPortalInfo = (curPortalBaseInfo: SpaceShipState['curPortalBaseInfo']) => {
  const baseUrl = `${window.location.origin}${BASENAME}`;
  const btoaPortalId = `${window.btoa(JSON.stringify({ portalId: curPortalBaseInfo?.id }))}`;
  if (curPortalBaseInfo?.encryption) {
    return curPortalBaseInfo.encryptionType === 2
      ? `${baseUrl}/sharedPortal/${btoaPortalId}?secretKey=${curPortalBaseInfo.shareToken}`
      : `${baseUrl}/sharedPortal/${btoaPortalId}?（密码：${curPortalBaseInfo.sharePassword}）`;
  }
  return `${baseUrl}/sharedPortal/${btoaPortalId}`;
};

const PublishContent = (props: Props) => {
  const linkRef = useRef<Input>();
  const productionInfo = useProductionInfo();
  const { skuId } = productionInfo;
  const { curPortalBaseInfo, onChange } = props;
  const [sharePassword, setSharePassword] = useState(curPortalBaseInfo?.sharePassword);
  useEffect(() => {
    setSharePassword(curPortalBaseInfo?.sharePassword);
  }, [curPortalBaseInfo]);

  const handleCopyLink = () => {
    linkRef.current?.select();
    document.execCommand('Copy');
    message.success('复制成功');
  };

  return (
    <div>
      {curPortalBaseInfo?.published ? (
        <>
          <div className={styles.item}>
            <label className={styles.label}>发布</label>
            <span>
              <SwitchWithLoading
                checked={curPortalBaseInfo.published}
                onChange={() => onChange({ id: curPortalBaseInfo?.id, published: !curPortalBaseInfo.published })}
              />
            </span>
          </div>
          <div className={styles.item}>
            <label className={styles.label}>发布链接</label>
            <div style={{ flex: 1, display: 'flex', alignItems: 'center' }}>
              <div style={{ flex: 1, marginRight: 16 }}>
                <Input value={getShareUrlByPortalInfo(curPortalBaseInfo)} id="share" readOnly placeholder="发布获取发布链接" />
              </div>
              <Input
                ref={linkRef}
                value={getShareUrlByPortalInfo(curPortalBaseInfo)}
                readOnly
                style={{ position: 'absolute', width: 300, top: -3000 }}
              />
              <EasyvButton theme="primary" onClick={handleCopyLink} disabled={!curPortalBaseInfo.published}>
                {getCopyBtnText(curPortalBaseInfo?.encryption, curPortalBaseInfo?.encryptionType)}
              </EasyvButton>
            </div>
          </div>

          <div className={styles.item}>
            <label className={styles.label}>加密分享</label>
            <SwitchWithLoading
              checked={curPortalBaseInfo.encryption}
              onChange={() =>
                onChange({
                  id: curPortalBaseInfo.id,
                  encryption: !curPortalBaseInfo.encryption,
                  encryptionType: curPortalBaseInfo.encryptionType
                })
              }
            />
          </div>
          {curPortalBaseInfo.encryption && (
            <div className={styles.item}>
              <label className={classnames(styles.label, { [styles.clearAfter]: curPortalBaseInfo.encryption })}>
                {!curPortalBaseInfo.encryption && '密码'}
              </label>
              <div className={styles.encryption}>
                <div className={styles.radioWrapper}>
                  <Radio.Group
                    value={curPortalBaseInfo.encryptionType}
                    onChange={(e) => onChange({ id: curPortalBaseInfo.id, encryptionType: e.target.value })}>
                    <Radio value={1}>密码</Radio>
                    {[3, 6].includes(skuId) && <Radio value={2}>Token验证</Radio>}
                  </Radio.Group>
                  {curPortalBaseInfo.encryptionType === 2 && (
                    <a
                      target="_blank"
                      href="https://www.yuque.com/docs/share/8630f574-0b58-4f27-847e-e2f5cfb4fa2d"
                      style={{ marginLeft: -8 }}>
                      使用教程 &gt;
                    </a>
                  )}
                </div>
                <div style={{ marginTop: 5 }}>
                  {/* <Input readOnly /> */}
                  {curPortalBaseInfo.encryptionType === 1 ? (
                    <Input
                      value={sharePassword}
                      placeholder="字母或数字,长度6-20位"
                      onChange={(e) => {
                        setSharePassword(e.target.value);
                      }}
                      onBlur={(e) => {
                        if (pwdValidate(e.target.value)) {
                          onChange({ id: curPortalBaseInfo.id, sharePassword: e.target.value });
                          return;
                        }
                        message.error('请输入字母或数字,长度6-20位');
                      }}
                      id="sharePassword"
                    />
                  ) : (
                    <>
                      <Input value={curPortalBaseInfo.shareToken} readOnly />
                    </>
                  )}
                </div>
              </div>
            </div>
          )}
        </>
      ) : (
        <Publish onPublish={() => onChange({ id: curPortalBaseInfo?.id, published: true })} theme="black" />
      )}
    </div>
  );
};

export default PublishContent;
