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

import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.OrderCol;
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.module.firm.model.FirmQuery;
import com.mortals.xhx.module.firm.service.FirmService;
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;

    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())));
        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));

        //离线设备 按类型分组
        if (collect.get(false) > 0) {
            Map<String, Long> collectTwo = this.service.find(new DeviceQuery().deviceOnlineStatus(DeviceOnlineStatusEnum.离线.getValue()).active(ActiveEnum.已激活.getValue())).stream().collect(Collectors.groupingBy(x -> deviceTypeMap.get(x.getDeviceType().toString()), Collectors.counting()));
            model.put("offlineDeviceType", collectTwo);
        }
        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 {
            ApiResp<String> apiResp = this.service.sendDeviceMessage(deviceId, Constant.DOWN_TOPIC, content, getContext());
            if(ApiRespCodeEnum.SUCCESS.getValue()!=apiResp.getCode()){
                throw new AppException("下发消息失败！");
            }
            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();
    }

}