import React, { useState, useMemo } from 'react';
import { Tag, Typography, Input, Checkbox, message } from 'antd';
import { CheckboxChangeEvent } from 'antd/es/checkbox';
import { CheckOutlined } from '@ant-design/icons';
// @ts-ignore
import { useModel } from 'umi';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';

const defaultTestService = 'http://localhost:8080';

// 环境标志
const ENVTagColor = {
  dev: 'orange',
  qa: 'green',
  uat: '#87d068',
};

const EnvTag: React.FC = () => {
  const { env, setApiPrefix, getApiPrefix } = useModel('system');
  const defaultPrefix = useMemo(() => getApiPrefix(), []);

  const [lock, setLock] = useState(false);
  const [prefix, setPrefix] = useState(defaultTestService + defaultPrefix);
  const [visible, setVisible] = useState(false);

  // 生产环境不显示标志
  if (env === 'prod') {
    return null;
  }

  const apply = (e: CheckboxChangeEvent) => {
    const { checked } = e.target;

    // check
    if (checked && !/^http:\/\//.test(prefix)) {
      message.error('无效的请求地址格式');
      return;
    }
    setLock(checked);
    setApiPrefix(checked ? prefix : defaultPrefix);
  };

  const content = (
    <div className={styles.content}>
      <h4>后台调试通道</h4>
      <Typography.Text type="secondary">设置接口地址，请求转发到新的后台地址</Typography.Text>
      <div className={styles.inputWrap}>
        <Input
          value={prefix}
          style={{ width: 300 }}
          size="small"
          disabled={lock}
          onChange={(e) => setPrefix(e.target.value)}
        />
        <Checkbox checked={lock} onChange={apply}>
          启用
        </Checkbox>
      </div>
      {lock && (
        <div>
          <Typography.Text type="secondary">
            <CheckOutlined />
            设置成功，请确认调试地址已开启跨域
          </Typography.Text>
        </div>
      )}
    </div>
  );

  return (
    <HeaderDropdown
      overlay={content}
      placement="bottomRight"
      visible={visible}
      onVisibleChange={setVisible}
      disabled={env === 'uat'}
      trigger={['click']}
    >
      <span className={styles.action}>
        {lock ? <Tag color="#f50">调试</Tag> : <Tag color={ENVTagColor[env]}>{env}</Tag>}
      </span>
    </HeaderDropdown>
  );
};

export default EnvTag;
