import React, { useState, useEffect } from 'react';
import { Dropdown, Input, Tabs, List, Spin, Empty, Avatar, Typography } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import LocalStorage from 'local-storage';

import useDebounce from './useDebounce';

import './FullSearch.less';

const { TabPane } = Tabs;

const recordsKey = 'records';
const keywordKey = 'keyword';

const modes = [
  {
    title: '数据源',
    shortTitle: '源',
    key: 'data-source',
  },
  {
    title: '元数据',
    shortTitle: '元',
    key: 'data-meta',
  },
  {
    title: '数据标准',
    shortTitle: '标',
    key: 'data-standard',
  },
  {
    title: '数据模型',
    shortTitle: '模',
    key: 'data-model',
  },
  {
    title: '数据资产',
    shortTitle: '资',
    key: 'data-asset',
  },
]

const list = [
  {
    title: 'test',
    did: '609a4eaf9e14e664f6fee2ee',
    id: '60b9978f9e14e64eb2ec5384',
    desc: '模型描述'
  },
  {
    title: 'test9',
    did: '608b99d19e14e66dea274bbe',
    id: '60b83b7f9e14e64eb2ec5382',
    desc: '模型描述'
  },
  {
    title: 'test',
    did: '609a4eaf9e14e664f6fee2ee',
    id: '60b9978f9e14e64eb2ec5384',
    desc: '模型描述'
  },
  {
    title: 'test9',
    did: '608b99d19e14e66dea274bbe',
    id: '60b83b7f9e14e64eb2ec5382',
    desc: '模型描述'
  },
  {
    title: 'test',
    did: '609a4eaf9e14e664f6fee2ee',
    id: '60b9978f9e14e64eb2ec5384',
    desc: '模型描述'
  },
  {
    title: 'test9',
    did: '608b99d19e14e66dea274bbe',
    id: '60b83b7f9e14e64eb2ec5382',
    desc: '模型描述'
  },
  {
    title: 'test',
    did: '609a4eaf9e14e664f6fee2ee',
    id: '60b9978f9e14e64eb2ec5384',
    desc: '模型描述'
  },
  {
    title: 'test9',
    did: '608b99d19e14e66dea274bbe',
    id: '60b83b7f9e14e64eb2ec5382',
    desc: '模型描述'
  },
  {
    title: 'test',
    did: '609a4eaf9e14e664f6fee2ee',
    id: '60b9978f9e14e64eb2ec5384',
    desc: '模型描述'
  },
  {
    title: 'test9',
    did: '608b99d19e14e66dea274bbe',
    id: '60b83b7f9e14e64eb2ec5382',
    desc: '模型描述'
  },
  {
    title: 'test',
    did: '609a4eaf9e14e664f6fee2ee',
    id: '60b9978f9e14e64eb2ec5384',
    desc: '模型描述'
  },
  {
    title: 'test9',
    did: '608b99d19e14e66dea274bbe',
    id: '60b83b7f9e14e64eb2ec5382',
    desc: '模型描述'
  },
  {
    title: 'test',
    did: '609a4eaf9e14e664f6fee2ee',
    id: '60b9978f9e14e64eb2ec5384',
    desc: '模型描述'
  },
  {
    title: 'test9',
    did: '608b99d19e14e66dea274bbe',
    id: '60b83b7f9e14e64eb2ec5382',
    desc: '模型描述'
  },
]

const saveRecord = (item) => {
  let records = getAllRecords();

  const index = records.findIndex((record) => record.id === item.id);

  if (index !== -1) {
    records.splice(index, 1);
  }

  records = [item, ...records];

  //最多只保存十条
  LocalStorage.set(recordsKey, JSON.stringify(records.slice(0, 10)));
}

const getAllRecords = () => {
  return (JSON.parse(LocalStorage.get(recordsKey)) || []);
}

const clearAllRecords = () => {
  LocalStorage.remove(recordsKey);
}

const FullSearchEmpty = (props) => {

  const [reports, setReports] = useState([]);

  useEffect(() => {
    setReports(getAllRecords);
  }, [])

  const onPreventMouseDown = (event) => {
    event.preventDefault();
    event.stopPropagation();
  }

  const onItemClick = (item) => {
    saveRecord(item);
    window.location.href=`data-model?did=${item.did}&id=${item.id}`;
  }

  const clear = () => {
    clearAllRecords();
    setReports([]);
  }

  return (
    <div className='full-search-empty' onMouseDown={onPreventMouseDown}>
    {
      (reports||[]).length===0 ? (
        <div className='no-record-content'>
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="输入关键字开始搜索" /> 
        </div>
      ) : (
        <div style={{ padding: 10 }}>
          <div className='header'>
            <span className='recent'>最近搜索</span>
            <span className='clear' onClick={clear}>清空</span>
          </div>
          <div className='content'>
          {
            (reports||[]).map((report, index) => {
              return (
                <div className='tag' key={index} onClick={() => { onItemClick(report); }}>
                  <div style={{ width: 24, height: 24, marginRight: 5, marginBottom: 2 }}>
                    <Avatar shape="square" size="small" title={report.mode?(report.mode.title||''):''}>{report.mode?(report.mode.shortTitle||''):''}</Avatar>
                  </div>
                  <Typography.Paragraph 
                    title={report.title||''}
                    ellipsis 
                  >
                  {report.title||''}
                  </Typography.Paragraph>
                </div>
              );
            })
          }
          </div>
        </div>
      )
    }
    </div>
  );
}

const FullSearchContent = (props) => {

  const { keyword } = props;

  const [currentModeKey, setCurrentModeKey] = useState('data-source');
  const [loading, setLoading] = useState(false);
  const debouncedKeyword = useDebounce(keyword, 300)
  
  useEffect(() => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1000)
  }, [debouncedKeyword])

  const onPreventMouseDown = (event) => {
    event.preventDefault();
    event.stopPropagation();
  }

  const onModeChange = (key) => {
    setCurrentModeKey(key);

    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1000)
  }

  const onItemClick = (item) => {

    const index = modes.findIndex((mode) => mode.key === currentModeKey);
    
    saveRecord({...item, mode: modes[index]});
    window.location.href=`data-model?did=${item.did}&id=${item.id}`;
  }

  return (
    <div className='full-search-content' onMouseDown={onPreventMouseDown}>
      <Tabs value={currentModeKey} onChange={onModeChange}> 
      {
        modes && modes.map(mode => {
          return (
            <TabPane tab={mode.title} key={mode.key}>
              <Spin spinning={loading}>
                <List
                  dataSource={list}
                  renderItem={(item, index) => {
                    return (
                      <>
                        <div className='list-item' onClick={() => { onItemClick(item); }}>
                          <div>{item.title||''}</div>
                          <div className='desc'>{item.desc||''}</div>
                        </div>
                        {
                          (index===list.length-1) && <div style={{ display: "flex", height: 44, fontSize: 12, alignItems: 'center', justifyContent: 'center', color: '#959899' }}>
                            已展示全部结果
                          </div>
                        }
                      </>
                    );
                  }}
                />
              </Spin>
            </TabPane>
          );
        })
      }
      </Tabs>
    </div>
  );
}

const FullSearch = (props) => {

  const [focused, setFocused] = useState(false);
  const [keyword, setKeyword] = useState(LocalStorage.get(keywordKey)||'');

  const onKeywordChange = (e) => {
    setKeyword(e.target.value||'');
    LocalStorage.set(keywordKey, e.target.value);
  }

  const onFocus = () => {
    triggerFocus(true);
  }

  const onBlur = () => {
    triggerFocus(false);
  }
  
  const triggerFocus = (focus) => {
    setFocused(focus);
  }

  return (
    <Dropdown
      overlay={
        (keyword||'') === '' ? <FullSearchEmpty /> : <FullSearchContent keyword={keyword} />
      }
      visible={focused}
    >
      <Input 
        prefix={<SearchOutlined style={{ color: '#ced4d9' }} />}
        placeholder='在数据治理系统中搜索' 
        style={{ 
          width: focused ? 390 : 200, 
        }}
        allowClear
        value={keyword}
        onChange={onKeywordChange}
        onFocus={onFocus}
        onBlur={onBlur}
      />
    </Dropdown>
  );
}

export default FullSearch;
