package com.xhpc.charging.station.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhpc.charging.station.mapper.XhpcEquipmenMonitorMapper;
import com.xhpc.charging.station.utils.img.HttpClientUtil;
import com.xhpc.common.core.utils.SecurityUtils;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.domain.XhpcEquipmenMonitor;
import com.xhpc.common.redis.service.RedisService;
import com.xhpc.common.security.service.TokenService;
import com.xhpc.common.util.UserTypeUtil;
import com.xhpc.system.api.domain.SysUser;
import com.xhpc.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author yuyang
 * @date 2022/9/12 10:56
 */
@Service
public class XhpcEquipmenMonitorServiceImpl implements IXhpcEquipmenMonitorService{

    @Resource
    private TokenService tokenService;
    @Resource
    private XhpcEquipmenMonitorMapper xhpcEquipmenMonitorMapper;
    @Autowired
    private RedisService redisService;

    @Override
    public List<Map<String, Object>> list(HttpServletRequest request, String equipmenName, String equipmenNumber, Long chargingStationId) {

        LoginUser loginUser = tokenService.getLoginUser();
        String tenantId = loginUser.getTenantId();
        Long logUserId = SecurityUtils.getUserId();
        SysUser sysUser = loginUser.getSysUser();
        List<Map<String, Object>> map =new ArrayList<>();
        if(tenantId !=null && !"".equals(tenantId)){
            if(UserTypeUtil.SYS_USER_TYPE_FOUR.equals(sysUser.getUserType())){
                //运维管理人员
                map = xhpcEquipmenMonitorMapper.list(3,logUserId,tenantId,chargingStationId,equipmenName,equipmenNumber);
            }else{
                if(sysUser.getUserId() !=UserTypeUtil.USER_ID){
                    Long logOperatorId = sysUser.getOperatorId();
                    if ("01".equals(sysUser.getUserType())) {
                        //运营商看自己的场站
                        map = xhpcEquipmenMonitorMapper.list(1,logOperatorId,tenantId,chargingStationId,equipmenName,equipmenNumber);
                    }else{
                        //查询赋值的场站
                        map = xhpcEquipmenMonitorMapper.list(2,logUserId,tenantId,chargingStationId,equipmenName,equipmenNumber);
                    }
                }else{
                    //全部桩
                    map = xhpcEquipmenMonitorMapper.list(0,null,tenantId,chargingStationId,equipmenName,equipmenNumber);
                }
            }
        }
        return map;
    }

    @Override
    public AjaxResult getequipmenMonitorById(Long equipmenMonitorId) {

        return AjaxResult.success(xhpcEquipmenMonitorMapper.getequipmenMonitorById(equipmenMonitorId));
    }

    @Override
    public AjaxResult addEquipmenMonitor(XhpcEquipmenMonitor xhpcEquipmenMonitor) {

        LoginUser loginUser = tokenService.getLoginUser();
        String tenantId = loginUser.getTenantId();

        if(xhpcEquipmenMonitor.getEquipmenMonitorId() ==null){
            xhpcEquipmenMonitor.setTenantId(tenantId);
            xhpcEquipmenMonitorMapper.insertquipmenMonitor(xhpcEquipmenMonitor);
        }else{
            xhpcEquipmenMonitorMapper.updaEquipmenMonitor(xhpcEquipmenMonitor);
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult remove(Long equipmenMonitorId) {
        XhpcEquipmenMonitor xhpcEquipmenMonitor = new XhpcEquipmenMonitor();
        xhpcEquipmenMonitor.setEquipmenMonitorId(equipmenMonitorId);
        xhpcEquipmenMonitor.setDelFlag(2);
        int i = xhpcEquipmenMonitorMapper.updaEquipmenMonitor(xhpcEquipmenMonitor);
        if (i > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @Override
    public AjaxResult getChargingStationMonitor(Long chargingStationId) {

        //获取设备列表
        List<Map<String, Object>> listMap =new ArrayList<>();
        List<XhpcEquipmenMonitor> list = xhpcEquipmenMonitorMapper.getChargingStationId(chargingStationId);
        //获取token
        String equipmenToken = getEquipmenToken();
        for (int i = 0; i <list.size() ; i++) {
            XhpcEquipmenMonitor xhpcEquipmenMonitor = list.get(i);
            Map<String, Object> map = new HashMap<>();
            String equipmenNumber = xhpcEquipmenMonitor.getEquipmenNumber();
            String equipmenName = xhpcEquipmenMonitor.getEquipmenName();
            map.put("chargingStationId",xhpcEquipmenMonitor.getChargingStationId());
            map.put("equipmentNumber",equipmenNumber);
            map.put("equipmentName",equipmenName);
            String equipmenUrl = getEquipmenUrl(equipmenToken, equipmenNumber, "1");
            if(equipmenUrl !=null && !"".equals(equipmenUrl)){
                map.put("url",equipmenUrl);
                listMap.add(map);
            }
        }
        return AjaxResult.success(listMap);
    }

    @Override
    public AjaxResult getChargingStationEquipmenToken() {

        try{
            //获取token
            String equipmenToken = getEquipmenToken();
            return AjaxResult.success(equipmenToken);
        }catch (Exception e){

            return AjaxResult.error("获取监控token失败，请联系管理员");
        }
    }

    public String getEquipmenToken(){
        String equipmenToken = redisService.getCacheObject("equipmen:token");
        Map<String, Object> map = new HashMap<>();
        if(equipmenToken ==null || "".equals(equipmenToken)){
            String resp = HttpClientUtil.sendPost("https://open.ys7.com/api/lapp/token/get?appKey=e87d64ac7c424d7bb37830055a21b57a&appSecret=85d3ea44e86f940ac8274b43f6703803",  null);
            JSONObject jsonObject = JSON.parseObject(resp);
            JSONObject data = jsonObject.getJSONObject("data");
            String accessToken = data.getString("accessToken");
            map.put("accessToken",accessToken);
            redisService.setCacheObject("equipmen:token",accessToken,259200L, TimeUnit.SECONDS);
            return accessToken;
        }else{
            return equipmenToken;
        }
    }

    public static String getEquipmenUrl(String accessToken,String deviceSerial,String channelNo){
        String url = "https://open.ys7.com/api/lapp/v2/live/address/get?accessToken=" + accessToken + "&deviceSerial=" + deviceSerial + "&channelNo=" + channelNo;
        String resp = HttpClientUtil.sendPost(url,  null);
        JSONObject jsonObject = JSON.parseObject(resp);
        if("200".equals(jsonObject.getString("code"))){
            JSONObject data = jsonObject.getJSONObject("data");
            return data.getString("url");
        }else{
            return null;
        }
    }


    public static void main(String[] args) {
        String accessToken = "at.bxecfid28j8vu7baai2o82jydfj74jlw-1hrdvblpz2-1a7773w-vr8r9vdl6";
        String deviceSerial ="C41675932";
        String channelNo ="1";
        String equipmenUrl = getEquipmenUrl(accessToken, deviceSerial, channelNo);
        System.out.println("equipmenUrl:"+equipmenUrl);
    }


}
