package com.yeejoin.amos.boot.module.common.biz.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.dto.CommonVideoDto;
import com.yeejoin.amos.boot.biz.common.enums.CommonVideoEnum;
import com.yeejoin.amos.boot.module.common.api.dto.BaseEnterpriseVideoDto;
import com.yeejoin.amos.boot.module.common.api.entity.BaseEnterpriseVideo;
import com.yeejoin.amos.boot.module.common.api.mapper.BaseEnterpriseVideoMapper;
import com.yeejoin.amos.boot.module.common.api.service.IBaseEnterpriseVideoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.rdbms.service.BaseService;

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

import static com.yeejoin.amos.boot.biz.common.constants.VideoConstant.CODE_200;

/**
 * 单位下摄像头表服务实现类
 *
 * @author system_generator
 * @date 2024-10-09
 */
@Service
@Slf4j
public class BaseEnterpriseVideoServiceImpl extends BaseService<BaseEnterpriseVideoDto, BaseEnterpriseVideo, BaseEnterpriseVideoMapper> implements IBaseEnterpriseVideoService {

    @Value("${cylinder.video.default.image.url:/upload/tzs/cylinder/no-connect.png}")
    private String defaultVideoUrl;

    public List<CommonVideoDto> getUnitVideoUrl(String useUnitCode, String regionCode) {
        List<CommonVideoDto> result = new ArrayList<CommonVideoDto>();
        LambdaQueryWrapper<BaseEnterpriseVideo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BaseEnterpriseVideo::getUseUnitCode, useUnitCode);
        wrapper.like(StringUtils.isNotEmpty(regionCode), BaseEnterpriseVideo::getRegionCode, regionCode);
        List<BaseEnterpriseVideo> videos = this.getBaseMapper().selectList(wrapper);
        for (BaseEnterpriseVideo video : videos) {
            Map<String, Object> requestInfo = new HashMap<>();
            requestInfo.put("appKey", video.getAppKey());
            requestInfo.put("appSecret", video.getAppSecret());
            String channelNos = video.getChannelNo();
            List<CommonVideoDto> channelNoList = JSONObject.parseArray(channelNos, CommonVideoDto.class);
            try {
                String accessTokenData = HttpUtil.post(video.getTokenUrl(), requestInfo);
                JSONObject jsonObject = JSON.parseObject(accessTokenData);
                String msg = jsonObject.get("msg").toString();
                String code = jsonObject.get("code").toString();
                if (CODE_200.equals(code)) {
                    String data = jsonObject.get("data").toString();
                    JSONObject objTokenJson = JSON.parseObject(data);
                    String accessToken = objTokenJson.get("accessToken").toString();
                    System.out.println(accessToken);
                    for (CommonVideoDto channelNo : channelNoList) {
                        Map<String, Object> requestVideosInfo = new HashMap<>();
                        requestVideosInfo.put("accessToken", accessToken);
                        requestVideosInfo.put("deviceSerial", video.getDeviceSerial());
                        requestVideosInfo.put("channelNo", channelNo.getKey());
                        requestVideosInfo.put("protocol", video.getProtocol());
                        requestVideosInfo.put("quality", channelNo.getQuality());
                        requestVideosInfo.put("supportH265", channelNo.getSupportH265());
                        requestVideosInfo.put("expireTime", video.getExpireTime());
                        log.info("开始获取通道信息：{}", JSONObject.toJSONString(requestVideosInfo));
                        String videoData = HttpUtil.post(video.getUrl(), requestVideosInfo);
                        JSONObject videoJsonObject = JSON.parseObject(videoData);
                        String msgVideo = videoJsonObject.get("msg").toString();
                        String codeVideo = videoJsonObject.get("code").toString();
                        if (CODE_200.equals(codeVideo)) {
                            String dataS = videoJsonObject.get("data").toString();
                            JSONObject dd = JSON.parseObject(dataS);
                            String url = dd.get("url").toString();
                            CommonVideoDto commonVideoDto = new CommonVideoDto();
                            commonVideoDto.setUrl(url);
                            commonVideoDto.setKey(channelNo.getKey());
                            commonVideoDto.setType(CommonVideoEnum.getEnum(video.getProtocol()).getName());
                            commonVideoDto.setTitle(channelNo.getTitle());
                            commonVideoDto.setThumb(channelNo.getThumb());
                            result.add(commonVideoDto);
                        } else {
                            String errorMsg = "code:" + codeVideo + "msg:" + msgVideo + "appKey:" + video.getAppKey() + "appSecret:" + video.getAppSecret() + "accessToken:" + accessToken;
                            log.info("视频地址获取失败errorMsg:{}", errorMsg);
                            this.setDefaultChannelData(result, channelNo);
                        }
                    }
                } else {
                    String errorMsg = "code:" + code + "msg:" + msg + "appKey:" + video.getAppKey() + "appSecret:" + video.getAppSecret();
                    log.info("视频token获取失败errorMsg:{}", errorMsg);
                    this.setDefaultVideoIfConnectFailed(channelNoList, result);
                }
            } catch (Exception e) {
                log.error(e.getMessage());
                this.setDefaultVideoIfConnectFailed(channelNoList, result);
            }
        }
        return result;
    }

    /**
     * 通道连接不上时，返回通道的默认图片
     *
     * @param result    返回连接的总通道
     * @param channelNo 未连接的通道
     */
    private void setDefaultChannelData(List<CommonVideoDto> result, CommonVideoDto channelNo) {
        CommonVideoDto commonVideoDto = new CommonVideoDto();
        commonVideoDto.setUrl(channelNo.getThumb());
        commonVideoDto.setKey(channelNo.getKey());
        commonVideoDto.setType(CommonVideoEnum.IMG.getName());
        commonVideoDto.setTitle(channelNo.getTitle());
        commonVideoDto.setThumb(channelNo.getThumb());
        result.add(commonVideoDto);
    }

    /**
     * 连接不上时返回的气通道信息
     *
     * @param commonVideoDtos 当前气瓶单位的所有通道
     * @param result          返回的结果集合
     */
    private void setDefaultVideoIfConnectFailed(List<CommonVideoDto> commonVideoDtos, List<CommonVideoDto> result) {
        // 先情况防止数据重复
        result.clear();
        // 每个通道设备默认值
        commonVideoDtos.forEach(channelNo -> this.setDefaultChannelData(result, channelNo));
    }
}