package com.casic.missiles.modular.alarm.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.casic.missiles.core.application.context.AbstractPermissionContext;
import com.casic.missiles.core.base.controller.BaseController;
import com.casic.missiles.core.datascope.DataScope;
import com.casic.missiles.core.model.auth.AuthUser;
import com.casic.missiles.core.util.EhcacheConstant;
import com.casic.missiles.model.response.ResponseData;
import com.casic.missiles.modular.alarm.model.AlarmLevelParam;
import com.casic.missiles.modular.alarm.service.IAlarmLevelService;
import com.casic.missiles.modular.system.model.AlarmLevel;
import com.casic.missiles.modular.system.model.DeptPermission;
import com.casic.missiles.modular.system.service.IDeptPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 控制器
 *
 * @author dev
 * @Date 2019-10-15 17:00:34
 */
@Slf4j
@Controller
@RequestMapping("/alarm")
public class AlarmLevelController extends BaseController {

    @Autowired
    private IAlarmLevelService alarmLevelService;
    @Resource
    private AbstractPermissionContext permissionService;
    @Resource
    private IDeptPermissionService deptPermissionService;
    @Resource
    private AbstractPermissionContext iCommonPermissionService;

    /**
     * 获取告警等级列表
     */
    @RequestMapping("/level/list")
    @ResponseBody
    public Object levelList(Long tenantId) {
        List<Map<String, Object>> levelList = new ArrayList<>();
        AuthUser currUser = permissionService.getAuthService().getLoginUser();
        //当前用户所属组织机构关联的项目id
        if(ObjectUtil.isEmpty(tenantId)){
            tenantId = Long.valueOf(currUser.getTenantId());
        }
        DeptPermission deptPermission = deptPermissionService.selectDeptPermission(currUser.getDeptId());
        if (ObjectUtil.isEmpty(deptPermission)) {
            return levelList;
        }
        for (Object deviceType : JSON.parseObject(deptPermission.getDeviceType(), List.class)) {
            Long deviceTypeNum = Long.valueOf(deviceType.toString());
            if (ObjectUtils.isEmpty(deviceTypeNum)) {
                continue;
            }
            String deviceTypeName = EhcacheConstant.retBean().getDeviceTypeNameById(deviceTypeNum);
            List<Map<String, Object>> levels = alarmLevelService.getLevelList(tenantId, deviceTypeNum);
            levels.forEach(
                    levelMap -> {
                        levelMap.put("deviceType", deviceType);
                        levelMap.put("deviceTypeName", deviceTypeName);
                        levelList.add(levelMap);
                    }
            );
        }

        ArrayList<Map<String, Object>>  distinctList= levelList.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(
                        Comparator.comparing(e->String.valueOf(e.get("deviceType"))))), ArrayList::new));
        return ResponseData.success(distinctList);
    }

    /**
     * 获取监测内容的告警等级
     */
    @RequestMapping("/levelByType")
    @ResponseBody
    public Object levelByType(Long tenantId, String name) {
        AuthUser currUser = permissionService.getAuthService().getLoginUser();
        if (ObjectUtil.isEmpty(tenantId)) {
            if (StrUtil.isEmpty(currUser.getTenantId())) {
                return ResponseData.error("无关联的项目id");
            }
            //当前用户所属组织机构关联的项目id
            tenantId = Long.valueOf(currUser.getTenantId());
        }
        List<AlarmLevel> levelList = alarmLevelService.selectByNameAndTenList(tenantId, name);
        System.out.println(levelList.toString());
        return ResponseData.success(levelList);
    }

    @RequestMapping("/configLevel")
    @ResponseBody
    public Object configLevel(@RequestBody List<AlarmLevel> levelList) {
        AuthUser currUser = permissionService.getAuthService().getLoginUser();
        //当前用户所属组织机构关联的项目id
        String userTenantId = currUser.getTenantId();
        Date currDate = new Date();
        for (AlarmLevel alarmLevel : levelList) {
            if (ObjectUtil.isAllEmpty(alarmLevel.getTenantId(), userTenantId)) {
                return ResponseData.error("无关联的项目id");
            }
            Long tenantId = ObjectUtil.isEmpty(alarmLevel.getTenantId()) ? Long.valueOf(userTenantId) : alarmLevel.getTenantId();
            AlarmLevel oldAlarmLevel = alarmLevelService.selectByNameAndTenAndLevel(tenantId, alarmLevel.getName(), alarmLevel.getLevel());
            if (ObjectUtil.isEmpty(oldAlarmLevel)) {
                //insert
                alarmLevel.setTenantId(tenantId);
                alarmLevel.setTs(currDate);
                alarmLevelService.save(alarmLevel);
            } else {
                //update
                alarmLevel.setId(oldAlarmLevel.getId());
                alarmLevel.setTenantId(tenantId);
                alarmLevel.setTs(currDate);
                alarmLevelService.updateById(alarmLevel);
            }
        }
        return ResponseData.success();
    }


    @RequestMapping(value = "/level/add", method = RequestMethod.POST)
    @ResponseBody
    public Object add(@RequestBody AlarmLevelParam alarmLevelParam) {
        if (ObjectUtils.isEmpty(alarmLevelParam.getTenantId())) {
            AuthUser currUser = permissionService.getAuthService().getLoginUser();
            alarmLevelParam.setTenantId(Long.valueOf(currUser.getTenantId()));
        }
        return alarmLevelService.addAlarmLevel(alarmLevelParam);
    }

    @RequestMapping(value = "/level/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@RequestBody AlarmLevelParam alarmLevelParam) {
        return alarmLevelService.updateAlarmLevel(alarmLevelParam);
    }

    /**
     * 获取详情信息
     */
    @RequestMapping(value = "/level/detail/{id}")
    @ResponseBody
    public Object selectAlarmLevel(@PathVariable(name = "id") Long id) {
        AlarmLevel alarmLevel = alarmLevelService.selectByID(id);
        return ResponseData.success(alarmLevel);
    }

    @RequestMapping(value = "/level/delete")
    @ResponseBody
    public Object deleteAlarmLevel(String deviceType, String name, String tenantId) {
        return alarmLevelService.deleteByCondition(deviceType, name, tenantId);
    }
}
