import React, { useState, useEffect, Fragment } from 'react';
import isEqual from 'lodash/isEqual';
import AceEditor from '@easyv/react-ace';
import styles from './API.less';
import { EasyBoolean, EasySelect, Input, Tooltip } from '@easyv/react-gui';
import { QuestionCircleOutlined } from '@ant-design/icons';

const methodOptions = [
  { name: 'GET', value: 'get' },
  { name: 'POST', value: 'post' },
  { name: 'PUT', value: 'put' },
  { name: 'DELETE', value: 'delete' },
  { name: 'PATCH', value: 'patch' }
];

const API = ({
  type,
  dataList = [],
  dataConfig = {},
  onChange
}: {
  type: string;
  dataList: any;
  dataConfig: any;
  onChange: (config) => any;
}) => {
  const [dataId, setDataId] = useState('');
  const [baseURL, setBaseURL] = useState('');
  const [method, setMethod] = useState('get');
  const [path, setPath] = useState('');
  const [params, setParams] = useState('');
  const [body, setBody] = useState('');
  const [headers, setHeaders] = useState('');
  const [update, setUpdate] = useState(false);
  const [needCookie, setNeedCookie] = useState(false);
  const [reqFromBack, setReqFromBack] = useState(false);

  // init base url
  useEffect(() => {
    const baseURL = (dataList.find((o) => o.id === dataConfig.data_id) || {}).baseURL;

    setBaseURL(baseURL);
  }, [dataList, dataConfig.data_id]);

  // init data config
  useEffect(() => {
    !isEqual(dataId, dataConfig.data_id) && setDataId(dataConfig.data_id || '');
    !isEqual(method, dataConfig.method) && setMethod(dataConfig.method || 'get');
    !isEqual(path, dataConfig.path) && setPath(dataConfig.path || '');
    !isEqual(headers, dataConfig.headers) && setHeaders(dataConfig.headers || '');
    !isEqual(params, dataConfig.params) && setParams(dataConfig.params || '');
    !isEqual(body, dataConfig.body) && setBody(dataConfig.body || '');
    dataConfig.needCookie
      ? dataConfig.needCookie === (true || false) && !isEqual(needCookie, dataConfig.needCookie) && setNeedCookie(dataConfig.needCookie)
      : setNeedCookie(false);
    dataConfig.reqFromBack
      ? dataConfig.reqFromBack === (true || false) &&
        !isEqual(reqFromBack, dataConfig.reqFromBack) &&
        setReqFromBack(dataConfig.reqFromBack)
      : setReqFromBack(type === 'api' ? false : true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dataConfig]);

  const updateDataConfig = (dataConfig) => {
    onChange({
      data: {
        data_id: dataId,
        method,
        path,
        params,
        needCookie,
        body,
        headers,
        reqFromBack,
        ...dataConfig
      }
    });
  };

  const onBlur = () => {
    if (update) {
      setUpdate(false);
      updateDataConfig({});
    }
  };

  const handleMethod = (value) => {
    setMethod(value);
    updateDataConfig({ method: value });
  };

  const handlePath = (e) => {
    const value = e.target.value;
    setPath(value);
    setUpdate(true);
  };

  const handleHeaders = (value) => {
    setHeaders(value);
    setUpdate(true);
  };

  const handleParams = (e) => {
    const value = e.target.value;
    setParams(value);
    setUpdate(true);
  };

  const handleBody = (value) => {
    setBody(value);
    setUpdate(true);
  };

  const handleNeedCookie = (value) => {
    setNeedCookie(value);
    updateDataConfig({ needCookie: value });
  };

  const handleReqFromBack = (value) => {
    setReqFromBack(value);
    updateDataConfig({ reqFromBack: value });
  };

  return (
    <div className={styles.apiContainer}>
      <div className={styles.apiWrap}>
        <label className={styles.label}>Base URL</label>
        <div style={{ flex: 1 }}>
          <Input value={baseURL} disabled title={baseURL} />
        </div>
      </div>
      <div className={styles.apiWrap}>
        <div className={styles.label}>请求方式</div>
        <div style={{ flex: 1 }}>
          <EasySelect value={method} options={methodOptions} onChange={handleMethod} placeholder="请选择" />
        </div>
      </div>
      <div className={styles.apiWrap}>
        <label className={styles.label} style={{ width: '100%' }}>
          请求头(JSON格式)
        </label>
      </div>
      <div className={styles.apiWrap}>
        <AceEditor
          className="dark"
          mode="json"
          theme="twilight"
          name="headers"
          width="100%"
          height="240px"
          onBlur={onBlur}
          onChange={handleHeaders}
          fontSize={14}
          showPrintMargin={true}
          showGutter={true}
          highlightActiveLine={true}
          value={type === 'dtInsight' && !headers ? '{\n\t"X-Auth-ActionId": ""\n}' : headers}
          setOptions={{
            enableBasicAutocompletion: false,
            enableLiveAutocompletion: false,
            enableSnippets: false,
            showLineNumbers: true,
            tabSize: 2,
            wrap: true
          }}
        />
      </div>
      <div className={styles.apiWrap}>
        <label className={styles.label}>路径</label>
        <div style={{ flex: 1 }}>
          <Input value={path} onChange={handlePath} onBlur={onBlur} />
        </div>
      </div>
      <div className={styles.apiWrap}>
        <label className={styles.label}>参数</label>
        <div style={{ flex: 1 }}>
          <Input value={params} onChange={handleParams} onBlur={onBlur} />
        </div>
      </div>

      {['post', 'put', 'patch'].includes(method) && (
        <Fragment>
          <div className={styles.apiWrap}>
            <label className={styles.label} style={{ width: '100%' }}>
              Body(JSON格式)
            </label>
          </div>
          <div className={styles.apiWrap}>
            <AceEditor
              className="dark"
              mode="json"
              theme="twilight"
              name="blah2"
              width="100%"
              height="240px"
              onBlur={onBlur}
              onChange={handleBody}
              fontSize={14}
              showPrintMargin={true}
              showGutter={true}
              highlightActiveLine={true}
              value={body}
              setOptions={{
                enableBasicAutocompletion: false,
                enableLiveAutocompletion: false,
                enableSnippets: false,
                showLineNumbers: true,
                tabSize: 2
              }}
            />
          </div>
        </Fragment>
      )}
      {type === 'api' && (
        <React.Fragment>
          <div style={{ color: '#AFBAC0', marginBottom: 20 }}>
            <EasyBoolean value={reqFromBack} onChange={handleReqFromBack}>
              后端发起请求
            </EasyBoolean>
            <Tooltip title="存在跨域问题可勾选">
              <QuestionCircleOutlined className="whiteHover" />
            </Tooltip>
          </div>
          <div style={{ color: '#AFBAC0' }}>
            <EasyBoolean value={needCookie} onChange={handleNeedCookie}>
              需要cookie
            </EasyBoolean>
          </div>
        </React.Fragment>
      )}
    </div>
  );
};

export default API;
