package com.ozs.controller.upload;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ozs.common.core.domain.Result;
import com.ozs.common.utils.ApiTokenUtils;
import com.ozs.common.utils.AppTokenUtils;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.stateSecrets.SM4Utils;
import com.ozs.service.entity.BaseDeviceDynamicManagement;
import com.ozs.service.entity.MsgAlarm;
import com.ozs.service.entity.MsgAlarmVice;
import com.ozs.service.entity.SvcAddress;
import com.ozs.service.service.BaseDeviceDynamicManagementService;
import com.ozs.service.service.MsgAlarmService;
import com.ozs.service.service.MsgAlarmViceService;
import com.ozs.service.service.SvcAddressService;
import com.ozs.vo.ReqDeviceVo;
import com.ozs.vo.ReqMsgAlarmVo;
import com.ozs.vo.RespGeoHazardMonitorVo;
import com.ozs.vo.RespMsgAlarmVo;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 1. 获取身份认证控制层
 *
 * @author Administrator
 */
@RestController
public class GeoHazardMonitorTokenController {

    @Resource
    private ApiTokenUtils apiTokenUtils;
    @Resource
    private AppTokenUtils appTokenUtils;
    @Resource
    BaseDeviceDynamicManagementService baseDeviceDynamicManagementService;
    @Autowired
    MsgAlarmService msgAlarmService;
    @Autowired
    MsgAlarmViceService msgAlarmViceService;
    @Autowired
    SvcAddressService svcAddressService;


    /**
     * 获取web访问令牌
     *
     * @param grantType    授权类型，客户端模式（client_credentials）
     * @param clientId     客户端编号
     * @param clientSecret 客户端密钥
     * @return
     */
    @PostMapping("/IPAddress/token")
    public String getWebToken(@RequestParam(value = "grantType", required = false) String grantType,
                              @RequestParam(value = "clientId", required = false) String clientId,
                              @RequestParam(value = "clientSecret", required = false) String clientSecret) {
        // 生成令牌
        JSONObject jsonObject=new JSONObject();
        LambdaQueryWrapper<SvcAddress> lw = new LambdaQueryWrapper<SvcAddress>();
        if (!ObjectUtils.isEmpty(grantType)) {
            lw.eq(SvcAddress::getGrantType, grantType);
        }
        if (!ObjectUtils.isEmpty(clientId)) {
            lw.eq(SvcAddress::getClientId, clientId);
        }
        if (!ObjectUtils.isEmpty(clientSecret)) {
            lw.eq(SvcAddress::getClientSecret, clientSecret);
        }
        List<SvcAddress> list = svcAddressService.list(lw);
        if (list.size() > 0) {
            ArrayList<String> objects = apiTokenUtils.createGeoHazardMonitorToken(grantType, clientId, clientSecret);
            if (objects.size() > 0) {
                RespGeoHazardMonitorVo respGeoHazardMonitorVo = new RespGeoHazardMonitorVo();
                respGeoHazardMonitorVo.setAccessToken(objects.get(1));
                respGeoHazardMonitorVo.setExpiresIn(Long.valueOf(objects.get(0)));
                respGeoHazardMonitorVo.setTokenType("令牌类型");
                jsonObject.put("resultCode",1);
                jsonObject.put("message","成功");
                jsonObject.put("data",respGeoHazardMonitorVo);
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e50000000000000000");
            } else {
                jsonObject.put("resultCode",2);
                jsonObject.put("message","失败");
                jsonObject.put("data","生成token失败");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e50000000000000000");
            }
        } else {
            jsonObject.put("resultCode",2);
            jsonObject.put("message","失败");
            jsonObject.put("data","参数验证失败");
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e50000000000000000");
        }
    }

    /**
     * 获取app访问令牌
     *
     * @return
     */
    @PostMapping("/App/token")
    public Result getAppToken(@RequestParam("parameter") String parameter) {
        // 生成令牌
        ArrayList<String> objects = appTokenUtils.createGeoHazardMonitorToken();
        if (objects.size() > 0) {
            RespGeoHazardMonitorVo respGeoHazardMonitorVo = new RespGeoHazardMonitorVo();
            respGeoHazardMonitorVo.setAccessToken(objects.get(1));
            respGeoHazardMonitorVo.setExpiresIn(Long.valueOf(objects.get(0)));
            respGeoHazardMonitorVo.setTokenType("令牌类型");
            return new Result(1, "成功", respGeoHazardMonitorVo);
        } else {
            return new Result(2, "失败", "生成token失败！！");
        }
    }

    /**
     * 报警信息数据传输
     *
     * @return // 生成令牌
     */
    @PostMapping("/IPAddress/alarm")
    public String alarm(@RequestParam("parameter") String parameter, HttpServletRequest request) {
        String token = apiTokenUtils.getGeoHazardMonitorToken(request);
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNotEmpty(token)) {
            String s = SM4Utils.decryptData_ECB(parameter, "4370780c9a8c43e50000000000000000");
            ReqMsgAlarmVo reqMsgAlarmVo = JSON.parseObject(s, ReqMsgAlarmVo.class);
            RespMsgAlarmVo respMsgAlarmVo = new RespMsgAlarmVo();
            LambdaQueryWrapper<MsgAlarm> lw = new LambdaQueryWrapper<MsgAlarm>();
            if (!ObjectUtils.isEmpty(reqMsgAlarmVo.getAlarmId())) {
                lw.eq(MsgAlarm::getAlarmId, reqMsgAlarmVo.getAlarmId());
            }
            MsgAlarm alarm = msgAlarmService.getOne(lw);
            if (ObjectUtils.isEmpty(alarm)) {
                MsgAlarm msgAlarm = new MsgAlarm();
                BeanUtils.copyProperties(reqMsgAlarmVo, msgAlarm);
//                msgAlarm.setCreateBy(getUsername());
                msgAlarmService.save(msgAlarm);
                respMsgAlarmVo.setAlarmId(reqMsgAlarmVo.getAlarmId());
                respMsgAlarmVo.setAlarmCamera(reqMsgAlarmVo.getAlarmCamera());
                respMsgAlarmVo.setIsCancel(2);
                respMsgAlarmVo.setCancelTime(null);
            } else {
                MsgAlarmVice msgAlarmVice = new MsgAlarmVice();
                BeanUtils.copyProperties(reqMsgAlarmVo, msgAlarmVice);
//                msgAlarmVice.setCreateBy(getUsername());
                msgAlarmViceService.save(msgAlarmVice);
                respMsgAlarmVo.setAlarmId(reqMsgAlarmVo.getAlarmId());
                respMsgAlarmVo.setAlarmCamera(reqMsgAlarmVo.getAlarmCamera());
                respMsgAlarmVo.setIsCancel(alarm.getIsLock());
                respMsgAlarmVo.setCancelTime(alarm.getReleasedTime());
            }
            jsonObject.put("resultCode",1);
            jsonObject.put("message","成功");
            jsonObject.put("data",respMsgAlarmVo);
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e50000000000000000");
        } else {
            jsonObject.put("resultCode",2);
            jsonObject.put("message","失败");
            jsonObject.put("data","token验证失败");
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e50000000000000000");
        }
    }


    /**
     * 设备状态数据传输
     *
     * @return
     */
    @PostMapping("/IPAddress/device/state")
    public String deviceState(@RequestParam("parameter") String parameter, HttpServletRequest request) throws ParseException {
        JSONObject jsonObject = new JSONObject();
        String token = apiTokenUtils.getGeoHazardMonitorToken(request);
        if (StringUtils.isNotEmpty(token)) {
            ReqDeviceVo reqDeviceVo = JSON.parseObject(SM4Utils.decryptData_ECB(parameter, "4370780c9a8c43e50000000000000000"), ReqDeviceVo.class);
            LambdaQueryWrapper<BaseDeviceDynamicManagement> lw = new LambdaQueryWrapper<BaseDeviceDynamicManagement>();
            if (!ObjectUtils.isEmpty(reqDeviceVo.getCameraCode())) {
                lw.eq(BaseDeviceDynamicManagement::getCameraCode, reqDeviceVo.getCameraCode());
            }
            BaseDeviceDynamicManagement baseDynamicManagement = baseDeviceDynamicManagementService.getOne(lw);
            baseDynamicManagement.setElectricity(reqDeviceVo.getElectricity());
            baseDynamicManagement.setUpdateTime(new Date(reqDeviceVo.getTime()));
            if (baseDeviceDynamicManagementService.updateById(baseDynamicManagement)) {
                jsonObject.put("resultCode",1);
                jsonObject.put("message","成功");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e50000000000000000");
            }
            jsonObject.put("resultCode",2);
            jsonObject.put("message","设备状态数据传输失败");
            return  SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e50000000000000000");
        } else {
            jsonObject.put("resultCode",2);
            jsonObject.put("message","token验证失败");
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e50000000000000000");
        }
    }
}
