import React, { Component } from 'react';
import moment from 'moment';
import { message, Radio, Tooltip, Button, Select } from 'antd';
import { formartRects, downloadImg, getPictureType, addPictureFavorite } from './utils';

import PictureView from '../CaptureImgView';
import IconFont from '../../themeComponents/IconFont';
import ContentBox from '../../themeComponents/ContentBox';
import LMap from '../LMap';
import Player from '../Player';
import { BaseStore, Dict, Shared as microShared, LMConfig, Service } from '@zenview/micro-basic-library';
import { fullScreenHelper, imageMethods, cache } from '@zenview/micro-utils';
import ServiceHttp from './service';
import { formatRectInfo } from './formatRectInfo';
import { formatTimeStamp } from '@zenview/micro-utils';
import { compact } from 'lodash';

import './index.less';

const radioArray = [
  { label: '看图片', value: 'image', iconType: 'icon-S_Photo_ContentsImage' },
  { label: '看视频', value: 'video', iconType: 'icon-S_Photo_ContentsVideo1' },
  { label: '看地图', value: 'map', iconType: 'icon-S_Photo_ContentsMap' },
];
@Dict.withTypeCodes
class DetailPictureMap extends Component {
  constructor(props) {
    super(props);
    this.videoTimer = null;
    this.state = {
      associationCids: [],
      radioType: 'image', // 当前选中的查看类型
      fileData: {},
      fileDatas: [],
      collectStatus: false,
      videoOptions: {
        overdue: false, // 视频已过期
        videoReady: false, // 视频可以播放
      },
      rects: [],
      switchTime: 5,
      nextTimes: 0,
    };
  }

  async componentDidMount() {
    const {
      resourceLibrary: { detailVideoSwitchTimes },
    } = LMConfig.BSConfig;
    this.setState({
      switchTime: detailVideoSwitchTimes || this.state.switchTime
    })
    const { data, setAssociationCids } = this.props;
    const imgId = data.imgId || data.captureId;
    const pictureCollection = cache.getCache('pictureCollection', 'session');
    if (pictureCollection) {
      this.pictureCollection = JSON.parse(pictureCollection);
      this.initCollectStatus(imgId);
    } else this.querySimplePictureFavorites(imgId);
    // 进入详情时会走两次didMount，第二次data才有数据
    data.cid && this.initVideoOptions();
    const id = BaseStore.device.getDeviceByCId(data.cid)?.id
    if (id) {
      let deviceRes = await ServiceHttp.queryDeviceInfoByCid(data.cid)
      const { associationCids } = deviceRes.data || {}
      this.setState({ associationCids: associationCids && compact(associationCids).filter(v => +v !== 0) }) //:['563020370','563019785']
      // this.setState({ associationCids }) //:['563020370','563019785']
      setAssociationCids && setAssociationCids(associationCids)
    }

    this.getDefaultRects();
    Service.logger.save({
      description: `查看【${data.deviceName || data.cameraName}】【${formatTimeStamp(data.captureTime)}】的抓拍图`,
      module: 104100,
      function: 104105,
    });
  }

  getDefaultRects = () => {
    let { data, type, dicts } = this.props;
    let typeCodes = [];
    try {
      typeCodes = dicts.typeCodes || this.props.typeCodes;
    } catch (error) { }
    let rects = formartRects(data, type, dicts, typeCodes);
    this.setState({ rects }, () => {
      data.imgId && this.queryCaptureAllTargetByImgId(data.imgId);
    });
  };

  queryCaptureAllTargetByImgId = (imgId) => {
    let { data, defaultId, dicts } = this.props;
    let { rects } = this.state;
    let typeCodes = [];
    try {
      typeCodes = dicts.typeCodes || this.props.typeCodes;
    } catch (error) { }
    ServiceHttp.queryCaptureAllTargetByImgId({ imgId }).then((res) => {
      let structuredInfo = res.data;
      let allRects = formatRectInfo(structuredInfo, defaultId || data.id, typeCodes, rects);
      this.setState({ rects: [...rects, ...allRects] });
    });
  };

  componentWillUnmount() {
    clearTimeout(this.videoTimer);
  }

  changeRadioType = (e) => {
    const radioType = e.target.value;
  
    if (radioType === 'video') {
      const { overdue, videoReady } = this.state.videoOptions;
      if (overdue) {
        return message.warn('视频已过期');
      }
      if (!videoReady && !overdue) {
        return;
      }
      this.queryHistoryAddress();
    }
    this.setState({ radioType });
  };

  frameSelectJumpPage = (params) => {
    let { history } = this.props;
    const { defaultUrl, frameUrl, searchData = {}, defaultRect: defaultItem, rects } = params;
    const pageInfo = microShared.resourcePageInfo[params.moduleName];
    const fnName = pageInfo.fnName;
    const { startTime, endTime, imgId, id } = searchData;
    microShared[fnName]({ history, id, imgId, frameUrl, defaultUrl, startTime, endTime, rects, defaultItem });
  };

  // 看视频相关方法：
  // 设置视频参数
  setVideoOptions = (options = {}) => {
    this.setState({
      videoOptions: { ...this.state.videoOptions, ...options },
    });
  };
  // 初始化视频相关参数
  initVideoOptions = async () => {
    let { data, isAccessControl } = this.props;
    if (isAccessControl) {
      // 是否是门禁
      return (
        data.videoUrl &&
        this.setVideoOptions({
          videoReady: true,
          overdue: false,
        })
      );
    }
    const storageLimit = await this.queryStorageLimit(data);
    const { systemTime } = BaseStore.app;
    // 视频是否已过期
    if (systemTime - data.captureTime > storageLimit * 24 * 60 * 60 * 1000) {
      return this.setVideoOptions({ overdue: true });
    }
    // 视频是否生成中
    if (systemTime - data.captureTime > 60000) {
      return this.setVideoOptions({ videoReady: true });
    }
    this.videoTimer = setTimeout(() => {
      this.setVideoOptions({ videoReady: true });
    }, systemTime - data.captureTime);
  };
  // 获取历史视频
  queryHistoryAddress = async () => {
    const { associationCids } = this.state
    const { data } = this.props;
    let arr = []
    if (associationCids && associationCids.length) {
      arr = associationCids
    } else {
      arr = [data.cid]
    }
    this.setState({
      fileDatas: arr.map(v => ({ cid: v }))
    },() => {
      arr.forEach((item, k) => {
        this.setFileDatas(item, k)
      })
    })


    // let fileData = await this.setFileDatas(cid)
    // let options = { fileData }
    // if (cid2) {
    //   let fileData2 = await this.setFileDatas(cid2)
    //   options.fileData2 = fileData2
    // }
    // this.setState(options)
  };


  setFileDatas = (cid, k) => {
    const { switchTime, nextTimes, fileDatas } = this.state
    const { data, afterTime = switchTime, beforeTime = switchTime } = this.props;
    const deviceData = BaseStore.device.getDeviceByCId(cid) || {};

    const option = {
      cid: cid,
      deviceName: deviceData.deviceName || deviceData.cameraName, // 接口返回有的还用cameraName
      startTime: parseInt(data.captureTime / 1000) - beforeTime + nextTimes,
      endTime: parseInt(data.captureTime / 1000) + afterTime + nextTimes,
    };


    const paramsObj = {
      startTime: option.startTime,
      endTime: option.endTime,
      deviceInfo: {
        cid: option.cid,
        deviceName: option.deviceName,
        isFrontEnd: !deviceData.hasStorage,
      },
    };
    microShared.getVideoRecord(paramsObj).then(videoRes => {

      let res = BaseStore.device.getDeviceByCId(option.cid);
      let fileData = this.getVideoFileDatas(res, videoRes, option)
      if(fileDatas[k]){
        fileDatas[k].fileData=fileData
      }else{
        fileDatas[k]={fileData,cid:option.cid}
      }
      this.setState({ fileDatas })
    })


    // return this.getVideoFileDatas(res, videoRes, option);

  }
  // 组合视频数据
  getVideoFileDatas = (res, item, option) => {
    return Object.assign({}, res, {
      historyList: item,
      isLiving: false,
      startTime: option.startTime,
      endTime: option.endTime,
      videoGroupType: option.videoGroupType,
    });
  };
  // 查询过期时间
  queryStorageLimit = async (data) => {
    let storageLimit;
    try {
      const result = await ServiceHttp.queryDeviceInfoByCid(data.cid);
      storageLimit = +result.data.extJson.cameraInfo.storage.video || 7;
    } catch {
      storageLimit = 7;
    }
    return storageLimit;
  };
  // 获取视频 Tab 提示信息
  getVideoRadioTitle = () => {
    const { overdue, videoReady } = this.state.videoOptions;
    if (!overdue && !videoReady) {
      return {
        disabeld: true,
        label: '看视频',
      };
    }
    if (overdue) {
      return {
        disabeld: true,
        label: '视频已过期',
      };
    }
    if (!videoReady) {
      return {
        disabeld: true,
        label: '视频生成中，请稍后再试',
      };
    }
    return {
      disabeld: false,
      label: '看视频',
    };
  };
  //下载图片
  imgDownload = () => {
    fullScreenHelper.exitFullscreen();
    const {
      funcConfig: { imageDownloadApprove = true },
    } = LMConfig.BSConfig;
    // 是否经过审批流
    const { data = {} } = this.props;
    const imagePath = data && (data.sceneUrl || data.url || data.pictureUrl || data.scenePath || data.imageUrl);
    const downloadName = this.props.downloadName || `${data.deviceName}_${moment(+data.captureTime).format('YYYYMMDDTHHmmss')}`;
    Service.logger.save({
      description: `下载【${data.deviceName || data.cameraName}】【${formatTimeStamp(data.captureTime)}】的抓拍图片`,
      module: 104100,
      function: 104108,
    });
    if (imageDownloadApprove) {
      downloadImg({ data, imagePath });
    } else {
      imageMethods.downloadLocalImage(imagePath, downloadName);
    }
  };
  // 获取所有收藏图片
  querySimplePictureFavorites = (imgId) => {
    const options = { pictureTypes: [1, 2, 3, 4] };
    ServiceHttp.querySimplePictureFavorites(options).then((res) => {
      const data = res.data || [];
      const mediaImageListIds = data.map((v) => v.pictureId);
      const obj = {
        mediaImageListIds,
        mediaImageListLevel: data, // 完整数据
      };
      this.pictureCollection = obj;
      cache.setCache('pictureCollection', JSON.stringify(obj), 'session');
      if (imgId) this.initCollectStatus(imgId);
    });
  };
  /**
   * @desc 判断图片收藏状态
   */
  initCollectStatus = (imgId = this.props.data.imgId) => {
    if (imgId) {
      const collectStatus = this.pictureCollection?.mediaImageListIds.includes(imgId);
      if (collectStatus) {
        this.setState({
          collectStatus,
        });
      }
    }
  };
  handleCollectiton = (event) => {
    const { collectStatus } = this.state;
    if (collectStatus) {
      this.cancelCollection();
    } else {
      this.addCollection(event);
    }
  };
  /**
   * @desc 取消收藏
   */
  cancelCollection = () => {
    const { data } = this.props;
    // 根据pictureId反查id
    const collectItem = this.pictureCollection.mediaImageListLevel.find((v) => v.pictureId === data.imgId || v.pictureId === data.captureId);
    if (collectItem?.id) {
      ServiceHttp.deleteFavorite(collectItem.id).then((res) => {
        if (res.code === 0) {
          Service.logger.save({
            description: `取消收藏【${collectItem.deviceName}】【${formatTimeStamp(collectItem.captureTime)}】的抓拍图`,
            module: 107300,
            function: 107303,
          });
          this.querySimplePictureFavorites();
          this.setState({ collectStatus: false });
        }
      });
    }
  };
  /**
   * @desc 添加收藏
   */
  addCollection = () => {
    const { data, type } = this.props;
    const pictureType = getPictureType(data, type);
    let cameraInfo = BaseStore.device.getDeviceByCId(data.cid) || BaseStore.device.getDeviceById(data.deviceId) || BaseStore.device.getDeviceById(data.cameraId) || {};
    const mediaOption = {
      pictureId: data.imgId || data.captureId,
      deviceId: cameraInfo.id||data.deviceId||data.cameraId||data.cid,
      deviceName: data.deviceName || cameraInfo.deviceName,
      captureTime: +data.captureTime,
      scenceImageUrl: data.sceneUrl || data.url || data.pictureUrl || data.scenePath || data.imageUrl,
      smallImageUrl: data.sceneUrl || data.url || data.pictureUrl || data.scenePath || data.imageUrl,
      pictureType,
      source: 2,
    };
    if (!mediaOption.scenceImageUrl) return message.warn('图片资源获取失败');
    addPictureFavorite(mediaOption)
      .then((res) => {
        if (res.code === 0) {
          Service.logger.save({
            description: `收藏【${mediaOption.deviceName}】【${formatTimeStamp(mediaOption.captureTime)}】的抓拍图`,
            module: 107300,
            function: 107301,
          });
          this.querySimplePictureFavorites();
          this.setState({ collectStatus: true });
        }
      })
      .catch((err) => {
        message.error('收藏失败');
      });
  };

  downloadVideo = (options,fileData) => {
    const { data } = this.props;
    Service.logger.save({
      description: `下载【${data.deviceName || data.cameraName}】【${formatTimeStamp(data.captureTime)}】的历史视频`,
      module: 104100,
      function: 104107,
    });
    this.props.downloadVideo && this.props.downloadVideo({ fileData, ...options });
  };
  // 快进/后退 s
  videoSwitch = (times) => {
    const { nextTimes } = this.state
    this.setState({ nextTimes: nextTimes + times }, () => {
      this.queryHistoryAddress();
    })
  }

  //时间段
  timeRangeChange = (value) => {
    this.setState({ switchTime: value }, () => {
      this.queryHistoryAddress();
    })
  }
  render() {
    const { radioType, collectStatus, rects, switchTime,
      // fileData, fileData2,
      associationCids, fileDatas } = this.state;
    const { data = {}, type = 'face' } = this.props;
    // const { historyList, startTime, endTime, cid, deviceName } = fileData;
    const videoInfo = this.getVideoRadioTitle();
    const mutPlayerFlag = associationCids && associationCids.length >= 2
    
    return (
      <ContentBox.InfoBox className="lm-c-detail-picture-map" contentStyle={{ display: 'flex', flexDirection: 'column' }}>
        <div className="detail-header">
          <Radio.Group buttonStyle="solid" value={radioType} onChange={this.changeRadioType}>
            {radioArray.map((v) => (
              <Radio.Button value={v.value} key={v.value} disabled={v.value === 'video' ? videoInfo.disabeld : false}>
                <IconFont type={v.iconType} />
                <span>{v.value === 'video' ? videoInfo.label : v.label}</span>
              </Radio.Button>
            ))}
          </Radio.Group>
        </div>
        {radioType === 'image' && type !== 'accessControl' && (
          <Tooltip title={`${collectStatus ? '取消' : ''}收藏`}>
            <IconFont className={`collection-icon ${collectStatus ? 'active' : ''}`} type="icon-S_Photo_KeepYes" onClick={this.handleCollectiton} />
          </Tooltip>
        )}
        <div className={`detail-content ${mutPlayerFlag ? ' mut-player' : ''}`}>
          <div className={`detail-content-part  ${radioType === 'image' ? 'detail-show-part' : 'detail-hide-part'}`}>
            <PictureView imagePath={data && (data.sceneUrl || data.url || data.pictureUrl || data.scenePath || data.imageUrl)} rects={rects} data={data} type={type} frameSelectJumpPage={this.frameSelectJumpPage} minHeight={550} imgDownload={this.imgDownload} {...this.props} />

          </div>
          {radioType === 'video' && (
            <>
              <div className={`detail-content-part detail-content-part-video detail-show-part`}>
                {
                  fileDatas.map(item => {
                    const { cid, fileData } = item
                    const { historyList, startTime, endTime, deviceName } = fileData||{};

                    return <Player key={cid} historyList={historyList} isLive={false} title={deviceName} cid={cid} startTime={startTime} endTime={endTime} downloadVideo={(options) => this.downloadVideo(options,fileData)} history={this.props.history} />
                  })
                }
                {/* <Player historyList={historyList} isLive={false} title={deviceName} cid={cid} startTime={startTime} endTime={endTime} downloadVideo={(options) => this.downloadVideo(options)} history={this.props.history} />
                {
                  mutPlayerFlag && fileData2 ? <Player historyList={fileData2.historyList} isLive={false} title={fileData2.deviceName} cid={fileData2.cid} startTime={fileData2.startTime} endTime={fileData2.endTime} downloadVideo={(options) => this.downloadVideo(options)} history={this.props.history} /> : null
                } */}

              </div>
              <div className="fotter-btn">
                <Button type="primary" onClick={() => this.videoSwitch(-switchTime)}>
                  <IconFont type="icon-S_Arrow_LinePrev" />
                  上个片段
                  {/* 回退({switchTime}s) */}
                </Button>
                <Select style={{ margin: '0 8px' }} options={[5, 10, 15, 30].map(v => ({ label: `前后${v}秒`, value: v }))} value={switchTime} onChange={this.timeRangeChange}></Select>
                {/* <Radio.Group buttonStyle="solid" value={switchTime} onChange={this.timeRangeChange}>
                  {[5, 10, 15, 30].map((v) => (
                    <Radio.Button value={v} key={v} >
                      {`前后${v}秒`}
                    </Radio.Button>
                  ))}
                </Radio.Group> */}
                <Button type="primary" onClick={() => this.videoSwitch(switchTime)}>
                  {/* 快进({switchTime}s) */}
                  下个片段
                  <IconFont type="icon-S_Arrow_LineNext" />
                </Button>
              </div>
            </>
          )}
          {radioType === 'map' && (
            <div className={`detail-content-part detail-content-part-map detail-show-part`}>
              <LMap.SinglePointMap point={BaseStore.device.getDeviceById(data.deviceId) || BaseStore.device.getDeviceByCId(data.cid) || data} />
            </div>
          )}
        </div>
      </ContentBox.InfoBox>
    );
  }
}
export default DetailPictureMap;
