package com.ruoyi.basicData.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.basicData.domain.TWarehouseWebcam;
import com.ruoyi.basicData.mapper.TWarehouseWebcamMapper;
import com.ruoyi.basicData.service.ITWarehouseWebcamService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 仓库摄像头Service业务层处理
 *
 * @author ruoyi
 * @date 2021-12-21
 */
@Service
public class TWarehouseWebcamServiceImpl implements ITWarehouseWebcamService {
    @Autowired
    private TWarehouseWebcamMapper tWarehouseWebcamMapper;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    /**
     * 查询仓库摄像头
     *
     * @param fId 仓库摄像头ID
     * @return 仓库摄像头
     */
    @Override
    public TWarehouseWebcam selectTWarehouseWebcamById(Long fId) {
        return tWarehouseWebcamMapper.selectTWarehouseWebcamById(fId);
    }

    /**
     * 查询仓库摄像头列表
     *
     * @param tWarehouseWebcam 仓库摄像头
     * @return 仓库摄像头
     */
    @Override
    public List<TWarehouseWebcam> selectTWarehouseWebcamList(TWarehouseWebcam tWarehouseWebcam) {
        return tWarehouseWebcamMapper.selectTWarehouseWebcamList(tWarehouseWebcam);
    }

    /**
     * 查询仓库摄像头
     *
     * @param deviceSerial 设备序列号
     * @return 仓库摄像头
     */
    @Override
    public TWarehouseWebcam selectTWarehouseWebcamByDeviceSerial(String deviceSerial) {
        return tWarehouseWebcamMapper.selectTWarehouseWebcamByDeviceSerial(deviceSerial);
    }

    /**
     * APP查询仓库摄像头列表
     *
     * @param tWarehouseWebcam 仓库摄像头
     * @return 仓库摄像头
     */
    @Override
    public List<TWarehouseWebcam> selectAppTWarehouseWebcamList(TWarehouseWebcam tWarehouseWebcam) {
        if (StringUtils.isNotNull(tWarehouseWebcam.getfWarehouseId())) {
            return tWarehouseWebcamMapper.selectAppTWarehouseWebcamList(tWarehouseWebcam.getfWarehouseId(), null);
        }

        String external = null;
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if ("外部用户".equals(user.getDept().getDeptName())) {
            external = user.getUserName();
        }

        return tWarehouseWebcamMapper.selectAppTWarehouseWebcamList(null, external);
    }

    /**
     * 新增仓库摄像头
     *
     * @param tWarehouseWebcam 仓库摄像头
     * @return 结果
     */
    @Override
    public int insertTWarehouseWebcam(TWarehouseWebcam tWarehouseWebcam) {
        tWarehouseWebcam.setCreateBy(SecurityUtils.getUsername());
        tWarehouseWebcam.setCreateTime(DateUtils.getNowDate());
        return tWarehouseWebcamMapper.insertTWarehouseWebcam(tWarehouseWebcam);
    }

    /**
     * 修改仓库摄像头
     *
     * @param tWarehouseWebcam 仓库摄像头
     * @return 结果
     */
    @Override
    public int updateTWarehouseWebcam(TWarehouseWebcam tWarehouseWebcam) {
        tWarehouseWebcam.setUpdateTime(DateUtils.getNowDate());
        return tWarehouseWebcamMapper.updateTWarehouseWebcam(tWarehouseWebcam);
    }

    /**
     * 修改仓库摄像头
     *
     * @param webcamList 仓库摄像头列表
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult updateTWarehouseWebcamList(List<TWarehouseWebcam> webcamList) {
        for (TWarehouseWebcam tWarehouseWebcam : webcamList) {
            tWarehouseWebcam.setUpdateBy(SecurityUtils.getUsername());
            tWarehouseWebcam.setUpdateTime(DateUtils.getNowDate());
            tWarehouseWebcamMapper.updateTWarehouseWebcam(tWarehouseWebcam);
        }
        return AjaxResult.success();
    }

    /**
     * 批量删除仓库摄像头
     *
     * @param fIds 需要删除的仓库摄像头ID
     * @return 结果
     */
    @Override
    public int deleteTWarehouseWebcamByIds(Long[] fIds) {
        return tWarehouseWebcamMapper.deleteTWarehouseWebcamByIds(fIds);
    }

    /**
     * 删除仓库摄像头信息
     *
     * @param fId 仓库摄像头ID
     * @return 结果
     */
    @Override
    public int deleteTWarehouseWebcamById(Long fId) {
        return tWarehouseWebcamMapper.deleteTWarehouseWebcamById(fId);
    }

    /**
     * 获取摄像头流地址
     *
     * @param warehouseId 仓库ID
     * @return 摄像头流地址集合
     */
    @Override
    public List<Map<String, Object>> getWebcamUrlList(Long fWarehouseId) {
        String external = null;
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if ("外部用户".equals(user.getDept().getDeptName())) {
            external = user.getUserName();
        }

        List<Map<String, Object>> data = new ArrayList<>();
        Map<String, Object> temp;

        List<TWarehouseWebcam> tWarehouseWebcams = tWarehouseWebcamMapper.selectAppTWarehouseWebcamList(fWarehouseId, external);
        if (tWarehouseWebcams.size() > 0) {
            // 获取摄像头token
            String token = getToken();
            for (TWarehouseWebcam tWarehouseWebcam : tWarehouseWebcams) {
                String projectId = tWarehouseWebcam.getProjectId();
                String deviceSerial = tWarehouseWebcam.getDeviceSerial();
                String streamUrl = getWebcamUrl(token, projectId, deviceSerial);
                temp = new HashMap<>();
                temp.put("warehouseName", tWarehouseWebcam.getfWarehouseName());
                temp.put("deviceName", tWarehouseWebcam.getDeviceName());
                temp.put("streamUrl", streamUrl);
                data.add(temp);
            }
        }
        return data;
    }

    private String getConfigValue(String key) {
        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique(key);
        if (StringUtils.isNull(sysConfig)) {
            throw new BaseException("系统参数异常，未找到" + key + "参数");
        }
        return sysConfig.getConfigValue();
    }

    private String getToken() {
        // 从参数里获取请求地址、参数
        String tokenUrl = getConfigValue("warehouse.webcam.tokenUrl");

        JSONObject values = new JSONObject();
        values.put("accessKey", getConfigValue("warehouse.webcam.accessKey"));
        values.put("secretKey", getConfigValue("warehouse.webcam.secretKey"));
        values.put("productCode", getConfigValue("warehouse.webcam.productCode"));

        String response = HttpRequest.post(tokenUrl)
                .body(values.toString())
                .execute().body();
        JSONObject json = JSON.parseObject(response);
        if ("200".equals(json.getString("code"))) {
            throw new BaseException(json.getString("msg"));
        }
        JSONObject data = JSON.parseObject(json.getString("data"));
        return data.getString("access_token");
    }

    private String getWebcamUrl(String token, String projectId, String deviceSerial) {
        // 从参数里获取请求地址、参数
        String streamUrl = getConfigValue("warehouse.webcam.streamUrl");

        JSONObject values = new JSONObject();
        values.put("projectId", projectId);
        values.put("deviceSerial", deviceSerial);
        values.put("protocol", 3);
        values.put("supportH265", 1);

        String response = HttpRequest.post(streamUrl)
                .header("access_token", token)
                .body(values.toString())
                .execute().body();
        JSONObject json = JSON.parseObject(response);
        if ("200".equals(json.getString("code"))) {
            throw new BaseException(json.getString("msg"));
        }
        JSONObject data = JSON.parseObject(json.getString("data"));
        return data.getString("url");
    }

}
