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

import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.OrderCol;
import com.mortals.framework.model.Result;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.common.code.DeviceActionEnum;
import com.mortals.xhx.common.code.DeviceOnlineStatusEnum;
import com.mortals.xhx.common.code.DeviceTypeEnum;
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.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("设备");
    }

    @GetMapping("stat")
    @UnAuth
    public String stat() {
        Map<String, Object> model = new HashMap();
        JSONObject ret = new JSONObject();
        ret.put("code", VALUE_RESULT_SUCCESS);
        ret.put("msg", "统计成功！");
        try {
            List<DeviceEntity> deviceEntityList = this.service.find(new DeviceQuery());
            Map<Boolean, Long> collect = deviceEntityList.stream().collect(Collectors.partitioningBy(item -> (item.getDeviceOnlineStatus() == DeviceOnlineStatusEnum.在线.getValue()), Collectors.counting()));
            model.put("totalCount", deviceEntityList.size());
            model.put("onlineCount", collect.get(true));
            model.put("offlineCount", collect.get(false));
            model.put("warnCount", 0);
            ret.put(KEY_RESULT_DATA, model);
        } catch (Exception e) {
            ret.put("code", VALUE_RESULT_FAILURE);
            doException(request, "统计", model, e);
        }
        return ret.toJSONString();
    }


    /**
     * 设备执行功能
     */
    @PostMapping(value = "execmd")
    public Rest<Void> deviceExecCmd(@RequestParam(value = "id") Long id,
                                   @RequestParam(value = "type") Integer type) {

        String busiDesc = this.getModuleDesc() + "设备执行"+ DeviceActionEnum.getByValue(type).getDesc();
        Rest<Void> rest = Rest.ok(busiDesc + " 【成功】");
        try {
            this.service.action(id,type,getContext());
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error("设备执行命令异常", e);
            rest = Rest.fail(super.convertException(e));
        }
        return rest;
    }


    @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) {
        this.addDict(model, "deviceType", paramService.getParamBySecondOrganize("Device", "deviceType"));
        this.addDict(model, "deviceOnlineStatus", paramService.getParamBySecondOrganize("Device", "deviceOnlineStatus"));
        this.addDict(model, "status", paramService.getParamBySecondOrganize("Device", "status"));
        this.addDict(model, "deviceFirmId", firmService.find(new FirmQuery()).stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getFirmName())));
        this.addDict(model, "deviceSource", paramService.getParamBySecondOrganize("Device", "deviceSource"));
        List<DeviceEntity> deviceEntityList = this.service.find(new DeviceQuery());
        Map<Boolean, Long> collect = deviceEntityList.stream().collect(Collectors.partitioningBy(item -> (item.getDeviceOnlineStatus() == DeviceOnlineStatusEnum.在线.getValue()), Collectors.counting()));
        model.put("totalCount", deviceEntityList.size());
        model.put("onlineCount", collect.get(true));
        model.put("offlineCount", collect.get(false));
        model.put("warnCount", 0);
        super.init(request, response, form, model, context);
    }


}