//空间详情
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { connect } from 'dva';
import { Table, Button, Descriptions, Carousel, Icon, Spin, List } from 'antd';
import router from 'umi/router';
import styles from './LimitedSpace.less';
import ReactZmage from 'react-zmage';
import { UnityAction } from '@/utils/utils';
let tempType = localStorage.tempType;
let timer = null;

function Detail(props) {
  const { dispatch, currentUser, loading, config, spaceList, spaceData, dataConfig } = props;
  const { projectId, spaceId } = props.match.params;
  const { group_id } = props.location.query;
  const carouselRef = useRef();
  const [space, setSpace] = useState(spaceList.find(item => item.id == spaceId));
  const [tempType, setTempType] = useState(localStorage.tempType || 1);

  //图片列表
  const { picList, imageList } = useMemo(() => {
    let picList = [];
    let imageList = [];
    config.map(item => {
      if (item.type == 'file') {
        let i = item.en_name.indexOf('_pic');
        picList.push({ en_name: item.en_name.slice(0, i) });
      }
    });
    picList = picList.map(item => {
      let pic = JSON.parse(space[item.en_name + '_pic']);
      imageList = imageList.concat(pic);
      return { ...item, pic };
    });
    return { picList, imageList };
  }, [config, space]);

  const onBack = () => {
    router.go(-1);
    if (!group_id) UnityAction.sendMsg('BackToOverallFromWeb');
  };

  const getTempImg = () => {
    if (tempType == 1) {
      return `url(${require('@/assets/LimitedSpace/圆柱形2.gif')})`;
    } else if (tempType == 2) {
      return `url(${require('@/assets/LimitedSpace/池子形2.gif')})`;
    } else {
      return `url(${require('@/assets/LimitedSpace/方井形2.gif')})`;
    }
  };

  useEffect(() => {
    dispatch({
      type: 'limitedSpace/queryDataConfig',
      payload: { project_id: projectId },
    });

    //在unity中点击点位修改页面数据
    UnityAction.addEventListener('SelectSpaceFromUnity', e => {
      setSpace(spaceList.find(item => item.id == e));
    });

    // 使用tempType切换类型，展示所有GIF
    let type = tempType;
    if (tempType == 3) type = 1;
    else type++;
    localStorage.tempType = type;

    return () => {
      UnityAction.off('SelectSpaceFromUnity');
    };
  }, []);

  //随空间变动调用空间监测接口
  useEffect(() => {
    clearInterval(timer);
    timer = setInterval(() => {
      dispatch({
        type: 'limitedSpace/queryData',
        payload: { project_id: projectId, id: space.id },
      });
    }, 20 * 1000);

    dispatch({
      type: 'limitedSpace/queryData',
      payload: { project_id: projectId, id: space.id },
    });
    return () => {
      clearInterval(timer);
    };
  }, [space]);

  const getColorAndStrByStatus = status => {
    let str = '安全';
    let color = 'white';
    switch (status) {
      case 0:
        str = '-';
        color = 'white';
        break;
      case 1:
        str = '安全';
        color = 'white';
        break;
      case 2:
        str = '预警';
        color = 'yellow';
        break;
      case 3:
        str = '报警';
        color = 'red';
        break;
    }
    return { str, color };
  };

  //空间监测数据
  const tableData = useMemo(() => {
    let temp = spaceData.list[0];
    if (!temp) return [];
    return dataConfig.map(item => {
      const status = temp.statusObj[item.item_name];
      const { color } = getColorAndStrByStatus(status);
      return {
        text: `${item.item_alias}(${item.item_unit})`,
        value: temp[item.item_name],
        color,
      };
    });
  }, [dataConfig, spaceData]);

  //空间监测总提示
  const threshold = useMemo(() => {
    let temp = spaceData.list[0];
    if (!temp) return [];
    const maxStatus = Math.max(...Object.values(temp.statusObj));
    return getColorAndStrByStatus(maxStatus);
  }, [spaceData]);

  const goToPic = name => {
    let p = picList.find(item => item.en_name == name);
    carouselRef.current.goTo(imageList.findIndex(item => item == p.pic[0]));
  };

  return (
    <div className={styles.page}>
      {/* <div style={{height:'50vh', overflow:'auto'}}>
        {config.map(item => {
          if (item.type != 'file') {
            let p = picList.find(p => p.en_name == item.en_name);
            if (p && p.pic.length != 0) {
              return (
                <List.Item className={styles.listItem} style={{background: 'linear-gradient(to right, rgba(153, 231, 255, 0.1), rgba(96, 168, 255, 0.1))'}} >
                    {item.cn_name}：
                    {space[item.en_name]}
                    <a onClick={() => goToPic(item.en_name)}> 查看图片</a>
                </List.Item>
              );
            } else {
              return (
                <List.Item className={styles.listItem} style={{background: 'linear-gradient(to right, rgba(153, 231, 255, 0.1), rgba(96, 168, 255, 0.1))'}} >{item.cn_name}：{space[item.en_name]}</List.Item>
              );
            }
          }
          return <></>
        })}
      </div>
      <div style={{ display: 'flex', margin: '10px 0 23px', justifyContent:'space-around'}}>
        <div className={styles.detailBlock}>
          {imageList.length == 0 ? (
            <div className={styles.carousel}>暂无图片</div>
          ) : (
            <>
              <div
                className={styles.prev}
                onClick={() => carouselRef.current.prev()}
              />
              <div
                className={styles.next}
                onClick={() => carouselRef.current.next()}
              />
              <Carousel className={styles.carousel} ref={carouselRef}>
                {imageList.map(item => (
                  <ReactZmage src={item} />
                ))}
              </Carousel>
            </>
          )}
        </div>
        <div
          className={styles.detailBlock}
          style={{
            // backgroundImage: getTempImg(),
            width:'30vw',
            backgroundImage: `url(${space.gif_url})`,
            backgroundSize: '30vw, 30vw',
            backgroundRepeat: 'no-repeat',
          }}
        />
      </div>
      <div className={styles.message}>空间监测信息</div>
      <div className={styles.messageText}>
        <div className={styles.DataRowItem}>
          <span className={styles.DataItemLeft}>风险提示：</span>
          <span style={{ color: '#5ae416' }}>正常</span>
        </div>
        {tableData.map(item => (
          <div className={styles.DataRowItem}>
            <span className={styles.DataItemLeft}>{item.text}：{item.value}</span>
          </div>
        ))}
      </div>
      <div style={{width:'100%', marginTop:'12px', borderBottom:'1px solid #2866B2'}}></div> */}

      <Button className={styles.back} type="primary" onClick={() => onBack()}>
        返回
      </Button>
      <div className={styles.detail}>
        <div className={styles.detailBlock}>
          {imageList.length == 0 ? (
            <div className={styles.carousel}>暂无图片</div>
          ) : (
            <>
              <div className={styles.prev} onClick={() => carouselRef.current.prev()} />
              <div className={styles.next} onClick={() => carouselRef.current.next()} />
              <Carousel className={styles.carousel} ref={carouselRef}>
                {imageList.map(item => (
                  <ReactZmage src={item} />
                ))}
              </Carousel>
            </>
          )}
        </div>
        <div
          className={styles.detailBlock}
          style={{
            backgroundImage: getTempImg(),
            backgroundImage: `url(${space.gif_url})`,
            backgroundSize: '30vw, 30vw',
            backgroundRepeat: 'no-repeat',
          }}
        />
        <div className={styles.DataBlock}>
          <Spin spinning={loading}>
            <div className={styles.DataItem}>
              <div className={styles.DataTitle}>空间监测信息</div>
              <div className={styles.DataRowItem}>
                <div className={styles.DataItemLeft}>风险提示</div>
                <div style={{ width: '25%', color: threshold.color }}>{threshold.str}</div>
              </div>
              {tableData.map(item => (
                <div className={styles.DataRowItem}>
                  <div className={styles.DataItemLeft}>{item.text}</div>
                  <div style={{ width: '25%', color: item.color }}>{item.value}</div>
                </div>
              ))}
            </div>
          </Spin>
        </div>
      </div>
      <Descriptions className={styles.descriptions} title="空间详情" column={1} bordered>
        {config.map(item => {
          if (item.type != 'file') {
            let p = picList.find(p => p.en_name == item.en_name);
            if (p && p.pic.length != 0) {
              return (
                <Descriptions.Item label={item.cn_name}>
                  <div>
                    {space[item.en_name]}
                    {space[item.en_name] && <br />}
                    <a onClick={() => goToPic(item.en_name)}>查看图片</a>
                  </div>
                </Descriptions.Item>
              );
            } else {
              return (
                <Descriptions.Item label={item.cn_name}>{space[item.en_name]}</Descriptions.Item>
              );
            }
          }
        })}
      </Descriptions>
    </div>
  );
}

export default connect(({ limitedSpace, user, loading }) => ({
  currentUser: user.currentUser,
  loading: loading.models.limitedSpace,
  config: limitedSpace.config,
  dataConfig: limitedSpace.dataConfig,
  spaceData: limitedSpace.spaceData,
  spaceList: limitedSpace.space.list,
}))(Detail);
