package com.gyee.alarm.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gyee.alarm.init.CacheContext;
import com.gyee.alarm.model.auto.*;
import com.gyee.alarm.model.vo.*;
import com.gyee.alarm.service.AlarmConfigurationService;
import com.gyee.alarm.service.AlarmRuleService;
import com.gyee.alarm.service.auto.IProEconAlarmTypeService;
import com.gyee.alarm.util.ExcelUtils;
import com.gyee.alarm.util.SnowflakeGenerator;
import com.gyee.alarm.util.StringUtils;
import com.gyee.common.util.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


@Slf4j
@RestController
@RequestMapping("/alarmconfiguration")
@CrossOrigin
@Api(value = "报警规则", tags = "报警规则")
public class AlarmConfigurationController {


    @Autowired
    private AlarmConfigurationService alarmConfigurationService;

    @GetMapping(value = "/querywtalarmdesclist")
    @ApiOperation(value = "通过场站、型号和部件查询报警描述信息", notes = "通过场站、型号和部件查询报警描述信息")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "wpId", value = "风场编号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "modelId", value = "型号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "components", value = "部件", required = true, dataType = "string", paramType = "query")})
    public AjaxResult queryWtAlarmDescList(String wpId, String modelId,String components) {

        List<AlarmConfigurationVo> vos=new ArrayList<>();

        if (StringUtils.notEmp(wpId) && StringUtils.notEmp(modelId) && StringUtils.notEmp(components)) {

            vos= alarmConfigurationService.queryWtAlarmDescList(wpId, modelId,components);

        }

        if (StringUtils.notEmp(vos)) {

            return AjaxResult.successData(AjaxStatus.success.code, vos);
        } else {
            return AjaxResult.successData(AjaxStatus.loginexpire.code, "error");
        }
    }

    //@UserLoginToken
    @PostMapping(value = "/save")
    @ResponseBody
    @ApiOperation(value = "进行修改和保存", notes = "进行修改和保存")
    public AjaxResult saveAndUpdateAlertrule(HttpServletRequest request, @RequestBody ProEconAlarmConfiguration alarmRule) throws Exception {


        if (StringUtils.notEmp(alarmRule)) {

            boolean result = alarmConfigurationService.saveAndUpdateAlertrule(alarmRule);

            return AjaxResult.successData(AjaxStatus.success.code, result);
        } else {
            return AjaxResult.successData(AjaxStatus.loginexpire.code, "error");
        }


    }

    @DeleteMapping(value = "/delete")
    @ApiOperation(value = "删除", notes = "删除")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "id", value = "报警主键", required = true, dataType = "string", paramType = "query")})
    public AjaxResult deleteAlertrule(String id) {

        boolean i = alarmConfigurationService.deleteAlertrule(id);

        if (StringUtils.notEmp(i)) {
            return AjaxResult.successData(AjaxStatus.success.code, i);
        } else {
            return AjaxResult.successData(AjaxStatus.error.code, "error");
        }
    }

    //@UserLoginToken
    @GetMapping(value = "/page")
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "pageNum", value = "页号", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示多少行", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "名称", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "wpId", value = "风场编号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "modelId", value = "型号编号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "alarmType", value = "报警类型", required = false, dataType = "string", paramType = "query")})

    public AjaxResult queryByPage(HttpServletRequest request,
                                  @RequestParam(value = "pageNum") Integer pageNum,
                                  @RequestParam(value = "pageSize") Integer pageSize,
                                  @RequestParam(value = "name", required = false) String name,
                                  @RequestParam(value = "wpId", required = false) String wpId,
                                  @RequestParam(value = "modelId", required = false) String modelId,
                                  @RequestParam(value = "alarmType", required = false) String alarmType
    ) {
        Page<ProEconAlarmConfiguration> page = new Page(pageNum, pageSize);

        IPage<ProEconAlarmConfiguration> pageResult = alarmConfigurationService.pageQueryAll(page, name, wpId, modelId,alarmType);
        IPage<ProEconAlarmConfigurationVo> result=new Page<>();
        result.setPages(pageResult.getPages());
        result.setCurrent(pageResult.getCurrent());
        result.setSize(pageResult.getSize());
        result.setTotal(pageResult.getTotal());

        List<ProEconAlarmConfigurationVo> vos=new ArrayList<>();

            if(!pageResult.getRecords().isEmpty())
            {
                for(ProEconAlarmConfiguration ac:pageResult.getRecords())
                {
                    ProEconAlarmConfigurationVo vo= new ProEconAlarmConfigurationVo();

                    BeanUtil.copyProperties( ac,vo);
                    if(CacheContext.wpmap.containsKey(ac.getStationId()))
                    {
                        vo.setStationName(CacheContext.wpmap.get(ac.getStationId()).getName());
                    }
                    if(CacheContext.subwpmap.containsKey(ac.getStationId()))
                    {
                        vo.setStationName(CacheContext.subwpmap.get(ac.getStationId()).getName());
                    }

                    if(CacheContext.alarmTypeMap.containsKey(ac.getComponents()))
                    {
                        vo.setComponentsName(CacheContext.alarmTypeMap.get(ac.getComponents()).getName());
                    }

                    if(CacheContext.wtmap.containsKey(ac.getDeviceId()))
                    {
                        vo.setDeviceName(CacheContext.wtmap.get(ac.getDeviceId()).getAname());
                    }
                    vos.add(vo);
                }
            }
        result.setRecords(vos);
        if (StringUtils.notEmp(result)) {

            return AjaxResult.successData(AjaxStatus.success.code, result);
        } else {
            return AjaxResult.successData(AjaxStatus.error.code, "error");
        }
    }





    @GetMapping("/get-import-template")
    @ApiOperation(value = "获得导入模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        Date current = DateUtils.getCurrentDate();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(current);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        Date previousDay = calendar.getTime();

        List<ProEconAlarmConfiguration> list = Arrays.asList(
                ProEconAlarmConfiguration.builder().id("").tagId("1").deviceId("SXJ_KGDL_HSM_F_WT_0001_EQ").suffix("")
                        .rank(3).uniformCode("AI242").stationId("SXJ_KGDL_HSM_FDC_STA").modelId("/HW3-S2500(121)")
                        .alarmType("windturbine").deviceType("windturbine").components("CLX").subcomponents("")
                        .description("温度等于850度或者温度小于零下40度")
                        .characteristic("正常停机").resetTable(false).enable(true).name("").nemCode("").faultCause("").resolvent("")
                        .build(),
                ProEconAlarmConfiguration.builder().id("").tagId("1").deviceId("SXJ_KGDL_HSM_F_WT_0002_EQ").suffix("")
                        .rank(3).uniformCode("AI242").stationId("SXJ_KGDL_HSM_FDC_STA").modelId("/HW3-S2500(121)")
                        .alarmType("windturbine").deviceType("windturbine").components("CLX").subcomponents("")
                        .description("温度等于850度或者温度小于零下40度")
                        .characteristic("正常停机").resetTable(false).enable(true).name("").nemCode("").faultCause("").resolvent("")
                        .build()



        );

        // 输出
        ExcelUtils.write(response, "导入模板.xls", "导入模板", ProEconAlarmConfiguration.class, list);
    }

    @PostMapping("/import")
    @ApiOperation(value = "导入", notes = "导入")
    public AjaxResult importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        List<ProEconAlarmConfiguration> list = ExcelUtils.read(file, ProEconAlarmConfiguration.class);

        if (com.gyee.common.model.StringUtils.notEmp(list) && !list.isEmpty()) {
            boolean allCheck = true;
            for (ProEconAlarmConfiguration alertrule : list) {
                String msg = "";
                boolean result = true;
                if (StringUtils.empty(alertrule.getDescription())) {
                    msg = "报警名称不能为空";
                    result = false;
                }else if (StringUtils.empty(alertrule.getTriggerType())) {
                    msg = "触发类型不能为空";
                    result = false;
                } else if (StringUtils.empty(alertrule.getResetTable())) {
                    msg = "是否可以复位不能为空";
                    result = false;
                } else if (StringUtils.empty(alertrule.getDeviceId())) {
                    msg = "设备不能为空";
                    result = false;
                } else if (alertrule.getEnable()) {
                    msg = "是否可用不能为空";
                    result = false;
                } else if (StringUtils.empty(alertrule.getRank())) {
                    msg = "报警级别不能为空";
                    result = false;
                } else if (StringUtils.empty(alertrule.getStationId())) {
                    msg = "风场不能为空";
                    result = false;
                } else if (StringUtils.empty(alertrule.getAlarmType())) {
                    msg = "报警类别不能为空";
                    result = false;
                } else if (StringUtils.empty(alertrule.getDeviceType())) {
                    msg = "报警设备类型不能为空";
                    result = false;
                }else if (StringUtils.empty(alertrule.getUniformCode())) {
                    msg = "统一编码不能为空";
                    result = false;
                }else if (StringUtils.empty(alertrule.getCharacteristic())) {
                    msg = "特性不能为空";
                    result = false;
                }
                if (StringUtils.notEmp(alertrule.getAlarmType()) && alertrule.getAlarmType().equals(AlarmTypeValue.WT.getCode())) {
                    if (StringUtils.empty(alertrule.getModelId())) {
                        msg = "风机型号不能为空";
                        result = false;
                    }
                    else if (StringUtils.empty(alertrule.getComponents())) {
                        msg = "关联部件不能为空";
                        result = false;
                    }
                }else  if (StringUtils.notEmp(alertrule.getAlarmType()) && alertrule.getAlarmType().equals(AlarmTypeValue.BT.getCode())) {
                    if (StringUtils.empty(alertrule.getTagId())) {
                        msg = "测点不能为空";
                        result = false;
                    }
                }
                if (result != true) {
                    allCheck = false;
                    if (!result) {
                        return AjaxResult.successData(AjaxStatus.error.code, msg);
                    }
                }

                if (allCheck) {

                    alarmConfigurationService.saveAndUpdateAlertrule(alertrule);
                }

            }
        }
        if (com.gyee.common.model.StringUtils.isNotNull(list)) {
            return AjaxResult.successData(AjaxStatus.success.code, list);
        } else {
            return AjaxResult.successData(AjaxStatus.error.code, "error");
        }


    }
}
