package com.mortals.xhx.busiz.web;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.xhx.common.code.ApiRespCodeEnum;
import com.mortals.xhx.common.code.DeviceMethodEnum;
import com.mortals.xhx.common.code.DeviceStatusEnum;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.pdu.device.DeviceReq;
import com.mortals.xhx.module.device.model.DeviceEntity;
import com.mortals.xhx.module.device.model.DeviceQuery;
import com.mortals.xhx.module.device.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.util.ServerInfo;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.util.Date;

import static com.mortals.xhx.common.key.Constant.PARAM_SERVER_HTTP_URL;
import static com.mortals.xhx.common.key.ErrorCode.*;
import static com.mortals.xhx.common.key.ErrorCode.DEVICE_CONFIG_IS_EMPTY_CONTENT;

@RestController
@Slf4j
@RequestMapping("/api/device")
public class DeviceCallbackController {

    @Autowired
    private DeviceService deviceService;

    @PostMapping("callback")
    @UnAuth
    public Rest<String> callback(@RequestBody DeviceReq req) {

        log.info("【设备接收】【请求体】-->  " + JSONObject.toJSONString(req));

        StringBuilder message = new StringBuilder();
        message.append(String.format("【外部请求】类型【%s】 内容:%s", DeviceMethodEnum.getByValue(req.getReceiveMethod()).getDesc(), JSONObject.toJSONString(req)));
        try {
            switch (DeviceMethodEnum.getByValue(req.getReceiveMethod())) {
                case ADD:
                    deviceAdd(req);
                    break;
                case UPDATE:
                    deviceUpdate(req);
                    break;
                case DEL:
                    deviceDel(req);
                    break;
                case ACTIVE:
                    deviceActive(req);
                    break;
                case ENABLED:
                    deviceEnabled(req);
                    break;
                case STOP:
                    deviceStop(req);
                    break;
            }
        } catch (Exception e) {
            log.error("接收数据失败", e);
            Rest.fail(e.getMessage());
        }

        return Rest.ok();
    }


    private void deviceAdd(DeviceReq req) throws AppException {
        log.info("【设备新增】【请求体】-->  " + JSONObject.toJSONString(req));
        //根据设备编码查询设备
        DeviceEntity deviceEntity = deviceService.selectOne(new DeviceQuery().deviceCode(req.getDeviceCode()));
        if (!ObjectUtils.isEmpty(deviceEntity)) {
            throw new AppException(DEVICE_CODE_IS_EXIST, DEVICE_CODE_IS_EXIST_CONTENT);
        }


        deviceEntity = new DeviceEntity();
        deviceEntity.initAttrValue();
        deviceEntity.setDeviceName(req.getDeviceName());
        deviceEntity.setDeviceCode(req.getDeviceCode());
        deviceEntity.setDeviceMac(req.getDeviceCode());
        deviceEntity.setSiteId(req.getSiteId());
        deviceEntity.setSiteCode(req.getSiteCode());
        deviceEntity.setSiteName(req.getSiteName());
        deviceEntity.setProductCode(req.getProductCode());

        deviceEntity.setIp(req.getIp());
        deviceEntity.setCenternum(req.getCenternum());
        deviceEntity.setPort(req.getPort());
        deviceEntity.setLeadingOfficial(req.getLeadingOfficial());
        deviceEntity.setLeadingOfficialTelephone(req.getLeadingOfficialTelephone());
        deviceEntity.setDeviceRemark(req.getDeviceRemark());
        deviceEntity.setCreateUserId(1L);
        deviceEntity.setCreateTime(new Date());
        deviceService.save(deviceEntity);

    }

    private void deviceUpdate(DeviceReq req) throws AppException {
        log.info("【设备更新】【请求体】-->  " + JSONObject.toJSONString(req));
        //根据设备编码查询设备
        DeviceEntity deviceEntity = deviceService.selectOne(new DeviceQuery().deviceCode(req.getDeviceCode()));

        if (ObjectUtils.isEmpty(deviceEntity)) {
            throw new AppException(DEVICE_CODE_IS_EMPTY, DEVICE_CODE_IS_EMPTY_CONTENT);
        }
        deviceEntity.setDeviceName(req.getDeviceName());
        deviceEntity.setDeviceCode(req.getDeviceCode());
        deviceEntity.setDeviceMac(req.getDeviceCode());
        deviceEntity.setSiteId(req.getSiteId());
        deviceEntity.setSiteCode(req.getSiteCode());
        deviceEntity.setSiteName(req.getSiteName());

        deviceEntity.setProductCode(req.getProductCode());
        deviceEntity.setIp(req.getIp());
        deviceEntity.setCenternum(req.getCenternum());
        deviceEntity.setPort(req.getPort());
        deviceEntity.setDeviceRemark(req.getDeviceRemark());
        deviceEntity.setUpdateUserId(1L);
        deviceEntity.setUpdateTime(new Date());
        deviceEntity.setLeadingOfficial(req.getLeadingOfficial());
        deviceEntity.setDeviceInFloor(req.getDeviceInFloor());
        deviceEntity.setDeviceInBuilding(req.getDeviceInBuilding());
        deviceService.update(deviceEntity);

    }

    private void deviceDel(DeviceReq req) throws AppException {
        log.info("【设备删除】【请求体】-->  " + JSONObject.toJSONString(req));
        //根据设备编码查询设备
        DeviceEntity deviceEntity = checkDeviceExist(req);
        deviceService.remove(new Long[]{deviceEntity.getId()}, null);

    }

    private void deviceActive(DeviceReq req) throws AppException {
        log.info("【设备激活】【请求体】-->  " + JSONObject.toJSONString(req));
        //根据设备编码查询设备
        DeviceEntity deviceEntity = checkDeviceExist(req);
        if (deviceEntity.getDeviceStatus() > DeviceStatusEnum.未激活.getValue()) {
            throw new AppException("当前设备已激活！");
        }
        deviceEntity.setDeviceStatus(DeviceStatusEnum.离线.getValue());
        deviceEntity.setUpdateTime(new Date());
        deviceEntity.setUpdateUserId(1L);
        deviceService.update(deviceEntity);

    }

    private void deviceEnabled(DeviceReq req) throws AppException {
        log.info("【设备启用】【请求体】-->  " + JSONObject.toJSONString(req));
        //根据设备编码查询设备
        DeviceEntity deviceEntity = checkDeviceExist(req);
        deviceEntity.setEnabled(YesNoEnum.YES.getValue());
        deviceEntity.setUpdateTime(new Date());
        deviceEntity.setUpdateUserId(1L);
        deviceEntity.setUpdateTime(new Date());
        deviceEntity.setUpdateUserId(1L);
        deviceService.update(deviceEntity);
    }

    private void deviceStop(DeviceReq req) throws AppException {
        log.info("【设备停用】【请求体】-->  " + JSONObject.toJSONString(req));
        DeviceEntity deviceEntity = checkDeviceExist(req);
        deviceEntity.setEnabled(YesNoEnum.NO.getValue());
        deviceEntity.setUpdateTime(new Date());
        deviceEntity.setUpdateUserId(1L);
        deviceEntity.setUpdateTime(new Date());
        deviceEntity.setUpdateUserId(1L);
        deviceService.update(deviceEntity);
    }

    private DeviceEntity checkDeviceExist(DeviceReq req) {
        if (ObjectUtils.isEmpty(req.getDeviceCode())) {
            throw new AppException(DEVICE_CODE_IS_EMPTY, DEVICE_CODE_IS_EMPTY_CONTENT);
        }
        DeviceEntity deviceEntity = deviceService.selectOne(new DeviceQuery().deviceCode(req.getDeviceCode()));
        if (ObjectUtils.isEmpty(deviceEntity)) {
            throw new AppException(DEVICE_NOT_EXIST, DEVICE_NOT_EXIST_CONTENT);

        }
        return deviceEntity;
    }

}
