package com.yeejoin.equipmanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yeejoin.equipmanage.common.entity.SupervisionVideo;
import com.yeejoin.equipmanage.common.entity.vo.AlamVideoVO;
import com.yeejoin.equipmanage.mapper.SupervisionVideoMapper;
import com.yeejoin.equipmanage.service.ISupervisionVideoService;
import com.yeejoin.equipmanage.service.IVideoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@Slf4j
@Service
//@EnableAsync
public class SupervisionVideoServiceImpl extends ServiceImpl<SupervisionVideoMapper, SupervisionVideo> implements ISupervisionVideoService {

    @Autowired
    SupervisionVideoMapper supervisionVideoMapper;
    @Value("${window.vedioFormat}")
    String vedioFormat;
    @Autowired
    private IVideoService videoService;

    @Override
    public List<List<AlamVideoVO>> queryVideoList(String bizOrgCode) {
        List<List<AlamVideoVO>> resList = new ArrayList<>();
        List<AlamVideoVO> list = supervisionVideoMapper.getVideoByCompany(bizOrgCode);
        list.forEach(action -> {
            action.setVedioFormat(vedioFormat);
            action.setUrl(videoService.getVideoUrl(action.getName(), action.getPresetPosition(), action.getUrl(), action.getCode()));
        });
        List<AlamVideoVO> mapList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (list.size() > 1 && ((i+1) % 2) - 1 != 0 && i != 0) {
                mapList.add(list.get(i));
                resList.add(mapList);
                mapList = new ArrayList<>();
            } else {
                mapList.add(list.get(i));
                if (i == list.size() - 1) {
                    resList.add(mapList);
                }
            }
        }
        return resList;
    }


    @Override
    public boolean replaceVideo(Map<String,String> map, String bizOrgCode) {
        supervisionVideoMapper.delete(new QueryWrapper<SupervisionVideo>().eq("biz_org_code",bizOrgCode));
        List<SupervisionVideo> list = new ArrayList<>();
        String ids = map.get("ids");
        for (String s : ids.split(",")) {
            SupervisionVideo supervisionVideo = new SupervisionVideo();
            supervisionVideo.setCameraId(s);
            supervisionVideo.setBizOrgCode(bizOrgCode);
            supervisionVideo.setId(Long.valueOf(String.valueOf(UUID.randomUUID().getLeastSignificantBits()).replace("-", "")));
            list.add(supervisionVideo);
        }
        return saveBatch(list);
    }

    @Override
    public List<String> queryVideoAllId(String bizOrgCode) {
        return supervisionVideoMapper.queryVideoAllId(bizOrgCode);
    }
}
