package com.mortals.xhx.module.device.web;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.OrderCol;
import com.mortals.xhx.base.system.message.MessageService;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.busiz.rsp.ApiResp;
import com.mortals.xhx.common.code.ActiveEnum;
import com.mortals.xhx.common.code.ApiRespCodeEnum;
import com.mortals.xhx.common.code.DeviceOnlineStatusEnum;
import com.mortals.xhx.common.code.DeviceTypeEnum;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.common.model.DefaultTbQueueMsgHeaders;
import com.mortals.xhx.common.model.MessageHeader;
import com.mortals.xhx.module.firm.model.FirmQuery;
import com.mortals.xhx.module.firm.service.FirmService;
import com.mortals.xhx.module.platform.model.PlatformEntity;
import com.mortals.xhx.module.platform.model.PlatformQuery;
import com.mortals.xhx.module.platform.service.PlatformService;
import com.mortals.xhx.module.product.model.ProductEntity;
import com.mortals.xhx.module.product.model.ProductQuery;
import com.mortals.xhx.module.product.service.ProductService;
import com.mortals.xhx.queue.TbQueueMsgHeaders;
import com.mortals.xhx.queue.TopicPartitionInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.mortals.framework.model.Context;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mortals.framework.web.BaseCRUDJsonMappingController;
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 org.apache.commons.lang3.ArrayUtils;
import com.mortals.framework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import static com.mortals.framework.ap.SysConstains.*;

/**
 * 设备
 *
 * @author zxfei
 * @date 2022-03-09
 */
@RestController
@RequestMapping("device")
public class DeviceController extends BaseCRUDJsonMappingController<DeviceService, DeviceForm, DeviceEntity, Long> {

    @Autowired
    private ParamService paramService;
    @Autowired
    private FirmService firmService;
    @Autowired
    private ProductService productService;
    @Autowired
    private PlatformService platformService;
    @Autowired
    private MessageService messageService;

    public DeviceController() {
        super.setFormClass(DeviceForm.class);
        super.setModuleDesc("设备");
    }

    @Override
    protected void doListBefore(HttpServletRequest request, HttpServletResponse response, DeviceForm form, Map<String, Object> model, Context context) throws AppException {
        form.getQuery().setOrderColList(new ArrayList<OrderCol>() {
            {
                add(new OrderCol("createTime", OrderCol.DESCENDING));
            }
        });
        super.doListBefore(request, response, form, model, context);
    }

    @Override
    protected void init(HttpServletRequest request, HttpServletResponse response, DeviceForm form, Map<String, Object> model, Context context) {

        Map<String, String> deviceTypeMap = paramService.getParamBySecondOrganize("Device", "deviceType");
        this.addDict(model, "deviceType", deviceTypeMap);
        this.addDict(model, "deviceOnlineStatus", paramService.getParamBySecondOrganize("Device", "deviceOnlineStatus"));
        this.addDict(model, "status", paramService.getParamBySecondOrganize("Device", "status"));
        this.addDict(model, "active", paramService.getParamBySecondOrganize("Device", "active"));
        this.addDict(model, "deviceFirmId", firmService.find(new FirmQuery()).stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getFirmName())));
        this.addDict(model, "platformId", platformService.find(new PlatformQuery()).stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getPlatformName())));
        this.addDict(model, "productId", productService.find(new ProductQuery()).stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getProductName())));

        Map<Boolean, Long> collect = this.service.find(new DeviceQuery().active(ActiveEnum.已激活.getValue())).stream().collect(Collectors.partitioningBy(item -> (item.getDeviceOnlineStatus() == DeviceOnlineStatusEnum.在线.getValue()), Collectors.counting()));
        model.put("onlineCount", collect.get(true));
        model.put("offlineCount", collect.get(false));

        String resp = messageService.siteTree();
        JSONObject jsonObject = JSON.parseObject(resp);
        JSONArray siteTreeArray = jsonObject.getJSONObject("data").getJSONArray("siteTree");
        model.put("siteTree", siteTreeArray);
        super.init(request, response, form, model, context);
    }


    /**
     * 下发信息
     */
    @PostMapping(value = "downMsg")
    public String downMsg(@RequestParam(value = "deviceId") Long deviceId, @RequestParam(value = "content") String content) {
        JSONObject jsonObject = new JSONObject();
        Map<String, Object> model = new HashMap<>();
        String busiDesc = this.getModuleDesc() + "下发设备消息";
        try {
            //根据设备编码查询设备
            DeviceEntity deviceEntity = this.service.get(deviceId, getContext());
            if (!ObjectUtils.isEmpty(deviceEntity)) {
                //将上报信息转发到mq中
                PlatformEntity platformEntity = platformService.get(deviceEntity.getPlatformId());
                if (ObjectUtils.isEmpty(platformEntity)) {
                    throw new AppException("当前设备未配置所属系统平台，请在后台配置后再激活！");
                }
                // authInfo.setHost(platformEntity.getPlatformSn());
                ProductEntity productEntity = productService.get(deviceEntity.getProductId());
                if (ObjectUtils.isEmpty(productEntity)) {
                    throw new AppException("当前设备未配置所属产品，请在后台配置后再激活！");
                }
                String exchangeName = platformEntity.getPlatformSn() + Constant.EXCHANGE_SPLIT + productEntity.getProductCode();
                TopicPartitionInfo info = TopicPartitionInfo.builder().exchangeName(exchangeName).topic(Constant.DOWN_TOPIC + deviceEntity.getDeviceCode()).build();
                TbQueueMsgHeaders header = new DefaultTbQueueMsgHeaders();
                header.put(MessageHeader.MESSAGETYPE, Constant.MESSAGETYPE_UPGREAD);
                JSONObject obj = new JSONObject();
                obj.put("content", content);

                ApiResp<String> sendDeviceMessageResp = this.service.sendDeviceMessage(deviceEntity, info, header, JSON.toJSONString(obj), null);
                log.info(String.format("sendMsgResp:%s", JSON.toJSONString(sendDeviceMessageResp)));
                if (ApiRespCodeEnum.SUCCESS.getValue() != sendDeviceMessageResp.getCode()) {
                    throw new AppException("下发消息失败！");
                }
                // Thread.sleep(50);

                //log.info(String.format("sendMsgResp:%s", JSON.toJSONString(sendDeviceMessageResp)));
            } else {
                throw new AppException("设备不存在！deviceId:" + deviceId);
            }

            this.init(request, response, null, model, getContext());
            recordSysLog(request, busiDesc + " 【成功】");
            jsonObject.put(KEY_RESULT_DATA, model);
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
        } catch (Exception e) {
            log.error("下发设备消息", e);
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            jsonObject.put(KEY_RESULT_MSG, super.convertException(e));
        }
        return jsonObject.toJSONString();
    }

    @Override
    protected void saveBefore(HttpServletRequest request, HttpServletResponse response, DeviceForm form, Map<String, Object> model, Context context) throws AppException {
        super.saveBefore(request, response, form, model, context);
    }

    /**
     * 设备激活
     */
    @PostMapping(value = "active")
    public String deviceActive(@RequestParam(value = "deviceCode") String deviceCode) {
        JSONObject jsonObject = new JSONObject();
        Map<String, Object> model = new HashMap<>();
        String busiDesc = this.getModuleDesc() + "设备激活";
        try {
            this.service.active(deviceCode, getContext());
            this.init(request, response, null, model, getContext());
            recordSysLog(request, busiDesc + " 【成功】");
            jsonObject.put(KEY_RESULT_DATA, model);
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
        } catch (Exception e) {
            log.error("设备激活消息", e);
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            jsonObject.put(KEY_RESULT_MSG, super.convertException(e));
        }
        return jsonObject.toJSONString();
    }

    /**
     * 设备启用停用
     */
    @PostMapping(value = "enable")
    public String deviceEnable(@RequestParam(value = "deviceCode") String deviceCode,@RequestParam(value = "status") Integer status) {
        JSONObject jsonObject = new JSONObject();
        Map<String, Object> model = new HashMap<>();
        String busiDesc = this.getModuleDesc() + "设备启用停用";
        try {
            this.service.active(deviceCode, getContext());
            this.init(request, response, null, model, getContext());
            recordSysLog(request, busiDesc + " 【成功】");
            jsonObject.put(KEY_RESULT_DATA, model);
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
        } catch (Exception e) {
            log.error("设备激活消息", e);
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            jsonObject.put(KEY_RESULT_MSG, super.convertException(e));
        }
        return jsonObject.toJSONString();
    }

    @Override
    public void doExportAfter(Context context, List<DeviceEntity> list) throws AppException {
        list.stream().forEach(item->{

        });

        super.doExportAfter(context, list);
    }
}