import React, {
  useState,
  useEffect,
  useRef,
  useMemo,
  ChangeEvent,
} from 'react';
import { Input, Tooltip } from 'antd';
import style from './ProjectList.less';
import ReactZmage from 'react-zmage';
import PinyinMatch from 'pinyin-match';
import { ChartBoxTitle } from './ChartBox';
import { useRequest } from '@umijs/max';
import { getProjectList } from '@/Project/services/DataMeter';

let LoopTime: NodeJS.Timer;
let searchTimer: NodeJS.Timer;
const nodata = require('@/Project/assets/dataMeter/ProjectList/nodata.png');
const clickTimer = 20000;
const normalTimer = 15000;
function ProjectList(props: DataMeter.IProjectListProps) {
  const { edit, subModule, layout } = props;
  const [currentProject, setCurrentProject] = useState<Api.IProject>();
  const [currentIndex, setCurrentIndex] = useState(0);
  // const [queryList, setQueryList] = useState<Api.IProject[]>([]);
  const [isClick, setIsClick] = useState(false);
  const [isPlay, setIsPlay] = useState(false);
  const [value, setValue] = useState<string>('');
  const ulRef = useRef<HTMLUListElement>(null);
  const ProjectListRequest = useRequest(getProjectList, {
    cacheKey: 'projectList',
    staleTime: -1,
  });
  const projectList = ProjectListRequest.data?.list || [];
  const list = useMemo<Api.IProject[]>(() => {
    const arr = projectList.filter((item: Api.IProject) => {
      let flag = subModule == 0 || item?.Stage == subModule || item?.Stage == 3;
      if (!flag) return;
      if (value) {
        return PinyinMatch.match(item.Name, value);
      }
      return flag;
    });
    return arr;
  }, [projectList]);

  // const getProjectList = (params, callback) => {
  //   dispatch({
  //     type: 'dataMeterNew/getProjectList',
  //     payload: params,
  //     callback: (res) => {
  //       res = res.filter((item) => {
  //         if (isPlatform != undefined) return true;
  //         if (subModule == 0) return true;
  //         else {
  //           if (item?.Stage == subModule || item?.Stage == 3) return true;
  //         }
  //       });
  //       // console.log(subModule, res);
  //       setQueryList(res);
  //       setCurrentIndex(0);
  //       setCurrentProject(res[0] || {});
  //       callback && callback(res);
  //     },
  //   });
  // };
  // useEffect(() => {
  //   getProjectList();
  //   return () => {
  //     clearInterval(LoopTime);
  //   };
  // }, []);
  // useEffect(() => {
  //   if (isPlay) {
  //     getProjectList({ carousel: 1 }, (res) => {
  //       res = res.filter((item) => {
  //         if (isPlatform != undefined) return true;
  //         if (subModule == 0) return true;
  //         else {
  //           if (item?.Stage == subModule || item?.Stage == 3) return true;
  //         }
  //       });
  //       setQueryList(res);
  //       inputRef.current.value = '';
  //       setCurrentProject(res[0] || {});
  //       setProjectId(res[0].ID || 0);
  //       ChangedProject(res[0] || {});
  //       onPlayCallback && onPlayCallback();
  //       ulRef.current.scrollTop = 0;
  //     });
  //   } else {
  //     getProjectList({}, (res) => {
  //       clearInterval(LoopTime);
  //       inputRef.current.value = '';
  //       setProjectId(0);
  //     });
  //   }

  //   // // console.log(isPlay);
  //   return () => {};
  // }, [isPlay]);
  // useEffect(() => {
  //   UnityAction.on('projectCarousel', (isPlay) => {
  //     setIsPlay(() => isPlay);
  //     if (!isPlay) {
  //       // else
  //       OnPauseCallback && OnPauseCallback();
  //     }
  //   });
  //   return () => {
  //     UnityAction.off('projectCarousel');
  //     clearInterval(LoopTime);
  //   };
  // }, []);

  // const StartTimeout = (time:number) => {
  //   LoopTime = setInterval(() => {
  //     if (queryList.length > 0) {
  //       var count = queryList.length;
  //       var index;
  //       if (currentIndex < count - 1) {
  //         index = currentIndex + 1;
  //       } else {
  //         index = 0;
  //       }

  //       // console.log(currentIndex, queryList[index].Name);
  //       cleanProjectData && cleanProjectData();
  //       setCurrentIndex(index);
  //       setCurrentProject(queryList[index]);
  //       setProjectId(queryList[index].ID);
  //       ChangedProject(queryList[index]);
  //       // console.log(33333);
  //       ulRef.current.scrollTop =
  //         ulRef.current?.children &&
  //         ulRef.current.children[index].clientHeight * index -
  //           ulRef.current.clientHeight / 2 +
  //           ulRef.current.children[index].clientHeight * 0.5 +
  //           6 * index +
  //           28;
  //     }
  //   }, time);
  // };
  // const sendProjectToUnity = () => {
  //   UnityAction.sendMsg('project', JSON.stringify(currentProject));
  // };
  // const sendNoModelToUnity = () => {
  //   UnityAction.sendMsg('noModel', JSON.stringify(currentProject));
  // };

  const onChangeInput = (e: ChangeEvent<HTMLInputElement>) => {
    setValue(e.target.value);
  };

  // useEffect(() => {
  //   const timer = isClick ? clickTimer : normalTimer;
  //   if (isClick) setIsClick(false);
  //   if (isPlay) StartTimeout(timer);
  //   return () => {
  //     clearInterval(LoopTime);
  //   };
  // }, [currentIndex, queryList]);

  return (
    <div className={style.main}>
      <ChartBoxTitle title="数字实景" width={layout.w} />
      <div className={style.container}>
        <div className={style.left}>
          <div className={style.search}>
            <input
              onChange={onChangeInput}
              type="text"
              placeholder="请输入项目"
              placeholder-style={{ color: '#366CDA', fondSize: '18px' }}
            ></input>
            <img
              src={require('@/Project/assets/dataMeter/ProjectList/search_Icon.png')}
            ></img>
          </div>
          <ul ref={ulRef} className={style.list}>
            {list.map((item, index) => {
              return (
                <li
                  className={currentIndex == index ? style.active : ''}
                  key={item.ID}
                  onClick={() => {
                    // clearInterval(LoopTime);
                    // setIsClick(true);
                    setCurrentProject(item);
                    setCurrentIndex(index);
                    // if (isPlay) {
                    //   setProjectId(item.ID);
                    //   ChangedProject(item);
                    // }

                    // if (currentIndex == index) {
                    //   if (isClick) setIsClick(false);
                    //   if (isPlay) StartTimeout(clickTimer);
                    // }
                  }}
                >
                  {item.Name}
                </li>
              );
            })}
          </ul>
        </div>
        <div className={style.line}></div>
        <div className={style.right}>
          <div
            className={style.image}
            onClick={() => {
              if (edit) return;
              // document.getElementsByClassName('reactZmage')[0]?.click();
            }}
            style={{
              backgroundImage: `url('${currentProject?.ScreenShot || nodata}')`,
              cursor: 'pointer',
            }}
          ></div>
          <ReactZmage
            controller={{
              close: true,
              rotate: true,
              zoom: false,
              download: false,
              flip: false,
              pagination: false,
            }}
            backdrop="rgba(255,255,255,0.5)"
            src={currentProject?.ScreenShot || nodata}
            onBrowsing={(state) => {
              // if (state) {
              //   clearInterval(LoopTime);
              // } else {
              //   if (isPlay) StartTimeout(normalTimer);
              // }
            }}
          />
          <div className={style.bottom}>
            <div className={style.context}>{currentProject?.Remark}</div>

            <div className={style.right_bottom}>
              <div className={style.province}>
                {currentProject?.Province}
                <Tooltip title={currentProject?.Name}>
                  <div className={style.name}>{currentProject?.Name}</div>
                </Tooltip>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
export default ProjectList;
