package com.zcxk.charge.web.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zcxk.charge.api.dto.query.AlarmSettingPageDto;
import com.zcxk.charge.api.enums.AlarmTypeEnum;
import com.zcxk.charge.api.enums.ChargeErrorEnum;
import com.zcxk.charge.api.vo.AlarmSettingVo;
import com.zcxk.charge.web.common.Pagination;
import com.zcxk.charge.api.dto.AlarmSettingDto;
import com.zcxk.charge.core.entity.AlarmSetting;
import com.zcxk.charge.core.entity.SceneEntity;
import com.zcxk.charge.web.service.AlarmSettingService;
import com.zcxk.charge.web.service.SceneService;
import com.zcxk.charge.web.util.OrgInfoUtil;
import com.zcxk.core.common.pojo.AjaxMessage;
import com.zcxk.core.oauth2.pojo.LoginUser;
import com.zcxk.core.oauth2.util.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 报警设置控制层
 * @author yjy
 * @since 2020-11-17
 */
@RestController
@RequestMapping("/alarmSetting")
@Api(tags = "报警管理")
public class AlarmSettingController {

    @Autowired
    private AlarmSettingService alarmSettingService;

    @Autowired
    private SceneService sceneService;

    @Autowired
    private OrgInfoUtil orgInfoUtil;

    @RequestMapping(value = "deleteByAlarmIds", method = RequestMethod.POST)
    @ApiOperation(value = "删除报警配置信息")
    public AjaxMessage<Boolean> deleteByAlarmIds(@ApiParam(value = "报警配置ids", required = true) @RequestBody Long[] ids) {
        // 修改实时报警数据
        alarmSettingService.updateRealtimeAlarm(ids,UserUtil.getCurrentUser().getUsername());
        return AjaxMessage.success(alarmSettingService.deleteByAlarmIds(ids));
    }

    @RequestMapping(value = "updateByAlarmId", method = RequestMethod.POST)
    @ApiOperation(value = "修改报警配置信息")
    public AjaxMessage updateByAlarmId(@ApiParam(value = "报警配置信息", required = true) @RequestBody AlarmSetting alarmSetting) {
        if (alarmSetting.getId() == null) {
            return AjaxMessage.fail(ChargeErrorEnum.PARAM_ERROR);
        }
        LoginUser currentUser = UserUtil.getCurrentUser();
        alarmSetting.setUpdateBy(currentUser.getUsername());
        // 修改实时报警数据
        alarmSettingService.updateRealtimeAlarm(new Long[]{alarmSetting.getId().longValue()}, currentUser.getUsername());
        return AjaxMessage.success(alarmSettingService.updateByAlarmId(alarmSetting));
    }

    @RequestMapping(value = "insertBatch", method = RequestMethod.POST)
    @ApiOperation(value = "批量增加报警配置信息",notes = "alarmType 为参数报警或状态报警")
    public AjaxMessage insertBatch(@ApiParam(value = "报警配置列表", required = true) @RequestBody List<AlarmSetting> listAlarmSetting) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        if (CollectionUtils.isEmpty(listAlarmSetting) || listAlarmSetting.get(0).getSceneId() == null || listAlarmSetting.get(0).getSceneId() == 0){
            return AjaxMessage.fail(ChargeErrorEnum.PARAM_ERROR);
        }
        SceneEntity sceneEntity = sceneService.findParentSceneById(listAlarmSetting.get(0).getSceneId());
        if (sceneEntity == null) {
            return AjaxMessage.fail(ChargeErrorEnum.OBJECT_ERROR);
        }
        for (AlarmSetting alarm : listAlarmSetting) {
            if(!valid(alarm)){
                return AjaxMessage.fail(ChargeErrorEnum.PARAM_ERROR);
            }
            alarm.setSceneName(sceneEntity.getSceneName());
            alarm.setParentSceneId(sceneEntity.getParentSceneId());
            alarm.setParentSceneName(sceneEntity.getParentSceneName());
            alarm.setCreateBy(currentUser.getUsername());
            alarm.setTenantId(currentUser.getTenantId());
            alarm.setStatus(1);
        }
        boolean result = alarmSettingService.insertBatch(listAlarmSetting);
        return AjaxMessage.success(result);
    }

    @RequestMapping(value = "selectPage", method = RequestMethod.POST)
    @ApiOperation(value = "分页查询报警设置数据")
    public AjaxMessage selectPage(@RequestBody @Valid AlarmSettingPageDto dto) {
        AlarmSettingDto alarmSettingDto=new AlarmSettingDto();
        alarmSettingDto.setId(dto.getId());
        alarmSettingDto.setAttributeName(dto.getAttributeName());
        alarmSettingDto.setSceneId(dto.getSceneId());
        alarmSettingDto.setSceneIds(sceneService.findByParentIdsSceneTypeName(dto.getSceneId(), dto.getSceneTypeName()));

        LoginUser loginUser = UserUtil.getCurrentUser();
        alarmSettingDto.setTenantId(loginUser.getTenantId());
        alarmSettingDto.setProgramItems(loginUser.getProgramItemList());
        alarmSettingDto.setUserType(loginUser.getType());
        // 1是公司，2是公司及以下，3部门，4部门及以下，5自定义
        alarmSettingDto.setPermissonType(loginUser.getPermissonType());
        IPage<AlarmSettingDto> iPage = new Page<>(dto.getPageNum(), dto.getPageSize());
        Pagination<AlarmSettingVo> pages = new Pagination<>(alarmSettingService.selectPage(iPage, alarmSettingDto));
        for (AlarmSettingVo alarm : pages.getList()){
            alarm.setCompanyOrgName(orgInfoUtil.getOrgName(alarm.getCompanyOrgId()));
            alarm.setDeptOrgName(orgInfoUtil.getOrgName(alarm.getDeptOrgId()));
        }
        return AjaxMessage.success(pages);
    }

    @RequestMapping(value = "selectAttributes", method = RequestMethod.GET)
    @ApiOperation(value = "根据设备id查询属性信息")
    public AjaxMessage selectAttributes(
            @ApiParam(value = "场景id", required = true)@RequestParam Integer sceneId,
            @ApiParam(value = "设备id", required = true)@RequestParam Integer deviceId) {
        if ( deviceId == null || sceneId == null) {
            return AjaxMessage.fail(ChargeErrorEnum.PARAM_ERROR);
        }
        return AjaxMessage.success(alarmSettingService.selectAttributes(deviceId,sceneId));
    }

    /**
    * 检查参数
    * @author Andy
    * @date 16:19 2021/8/16
    * @param alarm:
    * @return boolean
    **/
    private boolean valid(AlarmSetting alarm){
        if(!(AlarmTypeEnum.PARAMETER_ALARM.getMessage().equals(alarm.getAlarmType()) || AlarmTypeEnum.STATUS_ALARM.getMessage().equals(alarm.getAlarmType()))){
            return false;
        }
        if (alarm.getDeviceId() == null || alarm.getSceneId() == null){
            return false;
        }
        if (AlarmTypeEnum.PARAMETER_ALARM.getMessage().equals(alarm.getAlarmType()) && (attributeConditionValueEmpty(alarm))){
            return false;
        }
        if (AlarmTypeEnum.PARAMETER_ALARM.getMessage().equals(alarm.getAlarmType()) && (conditionValueEmpty(alarm))){
            return false;
        }
        return true;
    }

    private boolean attributeConditionValueEmpty(AlarmSetting alarm){
        return alarm.getAttributeId() == null|| StringUtils.isEmpty(alarm.getAlarmCondition()) || alarm.getAlarmValue()==null ;
    }

    private boolean conditionValueEmpty(AlarmSetting alarm){
        return StringUtils.isEmpty(alarm.getAlarmCondition()) || alarm.getAlarmValue()==null ;
    }
}