import { useModel } from '@umijs/max';
import React, { useEffect, useRef, useState, MouseEvent } from 'react';
import ReactZmage from 'react-zmage';
import { ChartBoxTitle } from './ChartBox';
import ProjectList from './ProjectList';
import style from '../index.less';
import { LocalService, STORAGE_TYPE } from '@/Frameworks/SysStorage';
import {
  Alert,
  Button,
  Carousel,
  message,
  Modal,
  Result,
  Tabs,
  Upload,
} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import type { RcFile, UploadProps } from 'antd/es/upload';
import type { UploadFile } from 'antd/es/upload/interface';

const nodata = require('@/Project/assets/dataMeter/ProjectList/nodata.png');
const token = LocalService.getItem(STORAGE_TYPE.token);
const { TabPane } = Tabs;

function Map(props: DataMeter.IModelsProps) {
  const { subModule, isNew, edit, layout, hasModel } = props;
  let content: React.ReactElement;
  if (isNew) {
    content = <ProjectList {...props} />;
  } else if (subModule != 0 && hasModel) {
    content = <NoModelMap {...props} />;
  } else {
    content = (
      <ModelMap
        {...props}
        // type={type}
        // setType={setType}
      >
        <div className={style.mapWapper}>
          <div
            // ref={mapEle}
            className={style.mapBox}
          ></div>
        </div>
      </ModelMap>
    );
  }
  // mouseEvent = {
  //   onMouseEnter: () => {
  //     UnityAction.emit('mouseHandle', 1);
  //   },
  //   onMouseLeave: () => {
  //     UnityAction.emit('mouseHandle', 0);
  //   },
  // };
  return content;
}

function NoModelMap(props: DataMeter.IModelsProps) {
  const { layout, edit } = props;
  const { project: projectDetail } = useModel('project');
  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        height: '100%',
        border: '#2866B2 solid 1px',
      }}
    >
      <ChartBoxTitle title={'数字实景'} width={layout.w} />
      <div
        style={{
          width: '100%',
          height: '100%',
          marginTop: 28,

          justifyContent: 'space-between',
        }}
      >
        <div
          onClick={() => {
            if (edit) return;
            // document.getElementsByClassName('reactZmage')[0].click();
          }}
          style={{
            backgroundImage: `url(${projectDetail?.ScreenShot || nodata})`,
            cursor: 'pointer',
            width: '100%',
            height: '100%',
            // backgroundSize: '100% 100%',
            backgroundSize: 'contain',
            backgroundPosition: 'center',
            backgroundRepeat: 'no-repeat',
          }}
        ></div>
        <ReactZmage
          controller={{
            close: true,
            rotate: true,
            zoom: false,
            download: false,
            flip: false,
            pagination: false,
          }}
          backdrop="rgba(255,255,255,0.5)"
          src={projectDetail?.ScreenShot || nodata}
        />
      </div>
    </div>
  );
}

function ModelMap(props: DataMeter.IModelsProps) {
  const [visible, setVisible] = useState(false);
  const [activeKey, setActiveKey] = useState('1');
  const [imgList, setImgList] = useState<UploadFile[]>([]);
  // const [videoList, setVideoList] = useState([]);
  const [projectList, setProjectList] = useState([]);
  const [type, setType] = useState<number>(1);
  const [uploadLoading, setUploadLoading] = useState(false);
  const mapEle = useRef<HTMLDivElement>(null);
  const videoEle = useRef<HTMLVideoElement>(null);
  // const token = getToken();
  const mediaImgList: any[] = [];
  const mediaVideo = { Url: '' };
  const loading = false;
  const {
    children,
    // type,
    // setType,
    edit,
    layout,
  } = props;
  const {
    initialState: { projectId },
  } = useModel('@@initialState');

  const imgProps: UploadProps = {
    name: 'file',
    action: `/api/v1/project-cabin-file/${projectId}/0`,
    headers: {
      'JWT-TOKEN': token,
    },
    fileList: imgList,
    listType: 'picture',
    className: style.uploadList,
    accept: 'image/*',
    onPreview() {
      return false;
    },
    beforeUpload: (file: RcFile) => {
      const isLt = file.size / 1024 / 1024 < 1;
      if (!isLt) {
        message.error('图片必须小于1 M');
      }
      // else {
      //   setImgList([...imgList, file]);
      // }
      return isLt;
    },
    onChange(info) {
      // if (info.file.status !== 'uploading') {
      // }
      // if (info.file.status === 'done') {
      //   message.success(`文件上传成功`);
      //   delete info.file.status;
      //   getMediaList();
      // } else if (info.file.status === 'error') {
      //   message.error(`文件上传失败`);
      // }
      let newFileList = [...info.fileList];

      // Read from response and show file link
      newFileList = newFileList.map((file) => {
        if (file.response) {
          // Component will show file.url as link
          file.url = file.response.url;
        }
        return file;
      });

      setImgList(newFileList);
    },
    onRemove(file) {
      // dispatch({
      //   type: 'dataMeterNew/deleteFile',
      //   payload: {
      //     id: file.uid,
      //     projectId,
      //   },
      // }).then(() => {
      //   message.success(`文件删除成功`);
      // });
    },
  };

  const deleteVideo = () => {
    Modal.confirm({
      title: '提醒',
      content: `确认删除视频？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        // dispatch({
        //   type: 'dataMeterNew/deleteFile',
        //   payload: {
        //     id: mediaVideo.ID,
        //     projectId,
        //   },
        // }).then(() => {
        //   message.success(`文件删除成功`);
        // });
      },
    });
  };

  const onHandleCancel = () => {
    if (videoEle.current) {
      videoEle.current.pause();
    }
    setVisible(false);
    // UnityAction.emit('mouseHandle', 1);
  };

  const getMediaList = () => {
    // dispatch({
    //   type: 'dataMeterNew/getMediaList',
    //   payload: {
    //     projectId,
    //   },
    // });
  };

  const sendUpload = (e: MouseEvent<HTMLElement>, info: string) => {
    // e.stopPropagation();
    if (info == 'image' && imgList.length >= 10) {
      message.error('图片不能超过10张');
      return;
    }
    if (info == 'video' && mediaVideo) {
      message.error('视频只能上传一个');
      return;
    }
    // if (!window.vuplex) return;
    // window.vuplex.postMessage({
    //   type: 'uploadFile',
    //   message: JSON.stringify(info),
    // });
    setUploadLoading(true);
  };

  useEffect(() => {
    // UnityAction.on('provinceList', (e) => setProjectList(e));
    // UnityAction.on('uploadState', (e) => {
    //   // console.log('============================upload response unity========================');
    //   // console.log(e);
    //   if (e == 'error') {
    //     message.error('上传失败');
    //     getMediaList();
    //   } else if (e == 'success') {
    //     message.success('上传成功');
    //     getMediaList();
    //   } else {
    //     message.info('取消上传');
    //   }
    //   setUploadLoading(false);
    // });
    // return () => {
    //   UnityAction.off('uploadState');
    //   UnityAction.off('provinceList');
    // };
  }, []);

  useEffect(() => {
    getMediaList();
  }, [projectId]);

  // useEffect(() => {
  //   setImgList(
  //     (mediaImgList || []).map((item) => ({
  //       uid: item.ID,
  //       url: item.Url,
  //       name: item.Name,
  //     })),
  //   );
  // }, [mediaImgList]);

  let content;
  if (edit) {
    const selectList = [
      {
        title: '三维模型',
        key: 1,
      },
      {
        title: '图片展示',
        key: 3,
      },
      {
        title: '视频展示',
        key: 2,
      },
    ];
    content = (
      <>
        <div
          className={style.mapControl}
          onMouseDown={(e) => {
            e.stopPropagation();
          }}
        >
          <ul className={style.selectList}>
            {selectList.map((item) => (
              <li
                key={item.key}
                className={`${type == item.key ? style.active : ''}`}
                onClick={() => {
                  setActiveKey(item.key == 2 ? '2' : '1');
                  setType(item.key);
                }}
              >
                {item.title}
              </li>
            ))}
          </ul>
          <div
            className={style.iconUpload}
            style={{ marginRight: 20 }}
            onClick={() => {
              setVisible(true);
              // UnityAction.emit('mouseHandle', 0);
            }}
          ></div>
        </div>
        <Result
          status="warning"
          title={<div style={{ color: '#fff' }}>模型将在编辑完成后显示</div>}
        />
      </>
    );
  } else {
    content = (
      <>
        {type == 1 && (
          <>
            <div
              style={{
                display: 'flex',
                flexDirection: 'column',
                height: '100%',
              }}
            >
              <ChartBoxTitle title={'数字实景'} width={layout.w} />
              {children}
            </div>
          </>
        )}
        {type == 2 && mediaVideo && (
          <div
            style={{ width: '100%', height: '100%', backgroundColor: '#000' }}
          >
            <video
              style={{ width: '100%', height: '100%' }}
              src={mediaVideo.Url}
              loop
              autoPlay={true}
            ></video>
          </div>
        )}
        {type == 3 && (
          <Carousel autoplay>
            {(imgList || []).map((item) => (
              <div key={item.uid} className={style.carousel}>
                <div
                  style={{
                    backgroundImage: `url('${item.url}')`,
                    height: mapEle.current?.clientHeight,
                  }}
                  className={style.carouselItem}
                ></div>
              </div>
            ))}
          </Carousel>
        )}
      </>
    );
  }

  return (
    <div
      className={`${style.mapContent} ${style.mapBg}`}
      style={{ overflow: 'hidden' }}
      ref={mapEle}
    >
      {content}
      <Modal
        title="上传文件"
        visible={visible}
        onOk={onHandleCancel}
        onCancel={onHandleCancel}
        cancelButtonProps={{ style: { display: 'none' } }}
        style={{ minHeight: 400 }}
        wrapClassName={style.uploadModal}
      >
        <Tabs activeKey={activeKey} tabPosition="left" onChange={setActiveKey}>
          <TabPane tab="图片" key="1">
            <Upload
              {...imgProps}
              // defaultFileList={[...defaultFileList]}
            >
              <Button
                loading={uploadLoading}
                onClick={(e: MouseEvent<HTMLElement>) => {
                  sendUpload(e, 'image');
                }}
              >
                {!uploadLoading && <UploadOutlined />} 上传
              </Button>
              <div
                style={{ marginTop: 10 }}
                onClick={(e) => e.stopPropagation()}
              >
                <Alert
                  message={`图片大小限制1M    已上传${imgList.length}/10张`}
                  type="warning"
                  showIcon
                />
              </div>
            </Upload>
          </TabPane>
          <TabPane tab="视频" key="2">
            <Button
              loading={uploadLoading}
              onClick={(e) => {
                sendUpload(e, 'video');
              }}
            >
              {!uploadLoading && <UploadOutlined />} 上传
            </Button>
            {mediaVideo && (
              <Button
                loading={loading}
                onClick={deleteVideo}
                style={{ marginLeft: 20 }}
                danger
              >
                删除视频
              </Button>
            )}

            {/* </Upload> */}
            <div style={{ marginTop: 10, marginBottom: 20 }}>
              <Alert
                message={`已上传${mediaVideo ? 1 : 0}/1个视频`}
                type="warning"
                showIcon
              />
            </div>
            {mediaVideo && (
              <video
                ref={videoEle}
                src={mediaVideo.Url}
                controls
                style={{ width: '100%' }}
              ></video>
            )}
          </TabPane>
        </Tabs>
      </Modal>
    </div>
  );
}

export default Map;
