package com.community.huiju.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.community.commom.hk.Digests;
import com.community.commom.hk.HttpClientSSLUtils;
import com.community.commom.mode.ResponseBean;
import com.community.commom.hk.HKConstant;
import com.community.commom.hk.HKOpenApi;
import com.community.commom.session.UserElement;
import com.community.huiju.common.perproties.YinShiProperties;
import com.community.huiju.common.welcome.OkHttpRequestUtils;
import com.community.huiju.dao.*;
import com.community.huiju.exception.WisdomException;
import com.community.huiju.model.*;
import com.community.huiju.service.IMonitoringService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 监控 业务实现
 * @author weixmei
 */
@Service("iMonitoringService")
@Slf4j
public class MonitoringServiceImpl implements IMonitoringService {

    @Autowired
    private TpEquipmentMapper tpEquipmentMapper;

    @Autowired
    private TpEquipmentTreeMapper tpEquipmentTreeMapper;

    @Autowired
    private TpConfigurationMapper tpConfigurationMapper;

    @Autowired
    private TaUserVerifyMapper taUserVerifyMapper;

    @Autowired
    private TpPhaseMapper tpPhaseMapper;

    @Autowired
    private TpBuildingMapper tpBuildingMapper;

    @Autowired
    private TpUnitMapper tpUnitMapper;

    @Autowired
    private TpLevelMapper tpLevelMapper;

    @Autowired
    private YinShiProperties yinShiProperties;

    @Autowired
    private ToCommunitiesMapper toCommunitiesMapper;

    @Override
    public ResponseBean getByCommunityId(Integer communityId,Integer pageNo, Integer pageSize) {

        // TODO 数据是假数据, 后期在更改. 需要根据小区查询 组织中心编号

//        ResponseBean response = new ResponseBean();
//        Map<String,Object> parMap = Maps.newHashMap();
//        parMap.put("pageNo",pageNo);
//        parMap.put("pageSize",pageSize);
//        parMap.put("opUserUuid",HKConstant.OP_USER_UUID);
//        // 组织中心编号
//        parMap.put("unitUuids","1048576");
//
//        String result = HKOpenApi.getMonitoryPoint(parMap);
//        // String url = "rtsp://vipgz1.idcfengye.com:10004/realplay://#cameraUuid#:SUB:";
//        String url = "rtsp://222.190.241.190:556/realplay://#cameraUuid#:SUB:";
//        JSONArray cameraList = JSONObject.parseObject(result).getJSONObject("data").getJSONArray("list");
//        List<String> urlList = new ArrayList<String>();
//        for (Object cameraMap : cameraList){
//            JSONObject camera = (JSONObject) cameraMap;
//            urlList.add(url.replace("#cameraUuid#",camera.getString("cameraUuid")));
//        }
//
//        response.addSuccess(urlList);
        ResponseBean response = new ResponseBean();
        Page<TpEquipment> page = PageHelper.startPage(pageNo, pageSize);
        List<TpEquipment> tpEquipments = tpEquipmentMapper.selectByCommunityId(communityId);

        Map<String, Object> map = Maps.newHashMap();
        map.put("pageNo", page.getPageNum());
        map.put("pageSize", page.getPageSize());
        map.put("total", page.getTotal());
        map.put("list", tpEquipments);
        response.addSuccess(map);

        return response;
    }

    @Override
    public ResponseBean getMonitoringToken(Integer communityId, Integer pageNo, Integer pageSize) {

        String appkey = "";
        String op_user_uuid = "";
        String secret = "";
        String openapi_ip_port_http = "";
        String unitUuids = "";

        /**
         * 先检测设备 的appkey，op_user_uuid， secret 是否有值
         * 如果有值，则使用 设备里面的参数
         */

        Page<TpEquipment> page = PageHelper.startPage(pageNo, pageSize);
        List<TpEquipment> tpEquipments = tpEquipmentMapper.selectByCommunityId(communityId);
        if (!tpEquipments.isEmpty()) {
            TpEquipment equipment = tpEquipments.get(0);
            if (StringUtils.isNotBlank(equipment.getAppkey()) && StringUtils.isNotBlank(equipment.getOpUserUuid()) && StringUtils.isNotBlank(equipment.getSecret())) {
                appkey = equipment.getAppkey();
                op_user_uuid = equipment.getOpUserUuid();
                secret = equipment.getSecret();
                openapi_ip_port_http = equipment.getHttpServer();
                unitUuids = equipment.getUnitUuids();
            }
        }

        TpEquipmentTree tpEquipmentTree = tpEquipmentTreeMapper.selectByCommunityId(communityId);
        // 如果设备里面没有值
        if (StringUtils.isBlank(appkey) && StringUtils.isBlank(op_user_uuid) && StringUtils.isBlank(secret)) {
            appkey = tpEquipmentTree.getAppkey();
            op_user_uuid = tpEquipmentTree.getOpUserUuid();
            secret = tpEquipmentTree.getSecret();
            openapi_ip_port_http = tpEquipmentTree.getHttpServer();
            unitUuids = tpEquipmentTree.getUnitUuids();
        }


        ResponseBean response = new ResponseBean();
        Map<String,Object> parMap = Maps.newHashMap();
        String url = openapi_ip_port_http + HKConstant.ITF_MONITORY_POINT;
        //设置APPKEY
        parMap.put("appkey", appkey);
        //设置时间参数
        parMap.put("time", System.currentTimeMillis());
        parMap.put("pageNo",pageNo);
        parMap.put("pageSize",pageSize);
        // 这里可以设置其他操作用户 parMap.put("opUserUuid",map.get("opUserUuid") == null?HKConstant.OP_USER_UUID:map.get("opUserUuid"));
        parMap.put("opUserUuid",op_user_uuid);
        // 组织中心编号
        // parMap.put("unitUuids","1048576");
        parMap.put("unitUuids",unitUuids);
        String params =  JSON.toJSONString(parMap);
        String token = Digests.buildToken(url + "?" + params, params, secret);

        Map<String, Object> map = Maps.newHashMap();
        map.put("token",token);
        response.addSuccess(map);

        return response;
    }

    @Override
    public ResponseBean getHlsByCommunityId(Integer communityId, Integer pageNo, Integer pageSize) {
        ResponseBean response = new ResponseBean();
        Page<TpEquipment> page = PageHelper.startPage(pageNo, pageSize);
        List<TpEquipment> tpEquipments = tpEquipmentMapper.selectHlsByCommunityId(communityId);

        Map<String, Object> map = Maps.newHashMap();
        map.put("pageNo", page.getPageNum());
        map.put("pageSize", page.getPageSize());
        map.put("total", page.getTotal());
        map.put("list", tpEquipments);
        response.addSuccess(map);
        return response;
    }

    @Override
    public ResponseBean getIntercomHLS(UserElement userElement) {
        ResponseBean responseBean = new ResponseBean();

        ToCommunities toCommunities = toCommunitiesMapper.selectByPrimaryKey(userElement.getCommunityId());
        TpUnit tpUnit = tpUnitMapper.selectByPrimaryKey(userElement.getUnitId());

        /**
         * tp_equipment 表
         *      op_user_uuid 是监控的Token,
         *      unit_uuids 是token的有效时间
         *      appkey 是视频流的appKey
         *      secret 是视频流的appSecret
         *
         * tp_configuration 表
         *      key 视频高清地址
         *      configuration_value 视频流畅地址
         *
         */

        List<TpEquipment> tpEquipments = tpEquipmentMapper.selectByCommunityIdAndUnitId(userElement.getCommunityId(), userElement.getUnitId(), 5);
        if (CollectionUtils.isEmpty(tpEquipments)) {
            String address = toCommunities.getCommunityName() + tpUnit.getPhaseName() + tpUnit.getBuildingName() + tpUnit.getName();
            responseBean.addError("系统未配置单元门口机设备!", address, null);
            return responseBean;
        }
        TpEquipment tpEquipment = tpEquipments.get(0);
        TpConfiguration tpConfiguration = tpConfigurationMapper.selectByPrimaryKey(tpEquipment.getUuidId());

        // 判断视频流地址，是否过期
        if (System.currentTimeMillis() >= Long.valueOf(tpEquipment.getUnitUuids())) {
            // 开始更新视频Token
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put("appKey", tpEquipment.getAppkey());
            queryMap.put("appSecret", tpEquipment.getSecret());
            try {
                String result = OkHttpRequestUtils.doGet(yinShiProperties.getVideoTokenUrl(), queryMap);
                JSONObject jsonObject = JSONObject.parseObject(result);
                tpEquipment.setOpUserUuid(jsonObject.getString("accessToken"));
                tpEquipment.setUnitUuids(String.valueOf(jsonObject.getLong("expireTime")));
                tpEquipmentMapper.updateByPrimaryKeySelective(tpEquipment);
            } catch (Exception e) {
                throw new WisdomException("获取视频Token失败！");
            }

        }


        Map<String,Object> map = new HashMap<>();
        // 流程视频流地址
        map.put("url", tpConfiguration.getConfigurationValue());
        // 高清视频流地址
        map.put("url_high", tpConfiguration.getKey());
        map.put("address", toCommunities.getCommunityName() + tpUnit.getPhaseName() + tpUnit.getBuildingName() + tpUnit.getName());
        map.put("token", tpEquipment.getOpUserUuid());
        responseBean.addSuccess(map);
        return responseBean;
    }
}
