package com.gyee.alarm.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gyee.alarm.model.auto.ProEconAlarmPlan;
import com.gyee.alarm.model.auto.ProEconAlarmPlan;
import com.gyee.alarm.model.vo.AjaxResult;
import com.gyee.alarm.model.vo.AjaxStatus;
import com.gyee.alarm.model.vo.AlarmCustomType;
import com.gyee.alarm.service.auto.IProEconAlarmPlanService;
import com.gyee.alarm.util.ExcelUtils;
import com.gyee.alarm.util.StringUtils;
import com.gyee.common.util.DateUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
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.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author shilin
 * @since 2024-10-28
 */
@RestController
@RequestMapping("//alarmplan")
public class ProEconAlarmPlanController {

    @Resource
    private IProEconAlarmPlanService proEconAlarmPlanService;

    @GetMapping(value = "/alarmPlanlistById")
    @ApiOperation(value = "通过预警编号获得报警解决方案列表", notes = "通过预警编号获得报警解决方案列表")
    public AjaxResult alarmPlanlistById(String alarmId) {

        List<ProEconAlarmPlan> vos=new ArrayList<>();
        if(StringUtils.notEmp( alarmId) )
        {
            vos= proEconAlarmPlanService.alarmPlanlistById(alarmId);
        }

        if (StringUtils.notEmp(vos)) {

            return AjaxResult.successData(AjaxStatus.success.code, vos);
        } else {
            return AjaxResult.successData(AjaxStatus.loginexpire.code, "error");
        }
    }
    @GetMapping(value = "/alarmPlanTypelist")
    @ApiOperation(value = "预警解决方案分类列表", notes = "预警解决方案分类列表")
    public AjaxResult queryAlarmPlanlist() {

        List<String> namels=new ArrayList();
        List<ProEconAlarmPlan> alertrules = proEconAlarmPlanService.list();

        Map<String, List<ProEconAlarmPlan>> map = alertrules.stream()
                .collect(Collectors.groupingBy(ProEconAlarmPlan::getTypes));

        for (Map.Entry<String, List<ProEconAlarmPlan>> entry : map.entrySet()) {
            String key = entry.getKey();
            namels.add(key);
        }
        if (StringUtils.notEmp(namels)) {

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

    @GetMapping(value = "/alarmPlanTypeDeallist")
    @ApiOperation(value = "预警解决方案分类列表", notes = "预警解决方案分类列表")
    public AjaxResult alarmPlanTypeDeallist() {

        List<String> namels=new ArrayList();
        List<ProEconAlarmPlan> alertrules = proEconAlarmPlanService.list();

        Map<String, List<ProEconAlarmPlan>> map = alertrules.stream()
                .collect(Collectors.groupingBy(ProEconAlarmPlan::getTypedetails));

        for (Map.Entry<String, List<ProEconAlarmPlan>> entry : map.entrySet()) {
            String key = entry.getKey();
            namels.add(key);
        }
        if (StringUtils.notEmp(namels)) {

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

    @GetMapping(value = "/queryAlarmPlanMap")
    @ApiOperation(value = "预警解决方案分类列表", notes = "预警解决方案分类列表")
    public AjaxResult queryAlarmPlanMap() {

        List<String> namels=new ArrayList();
        List<ProEconAlarmPlan> alertrules = proEconAlarmPlanService.list();

        Map<String, List<ProEconAlarmPlan>> map = alertrules.stream()
                .collect(Collectors.groupingBy(ProEconAlarmPlan::getTypes));


        if (StringUtils.notEmp(map)) {

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


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


        if (StringUtils.notEmp(alarmRule)) {


            int result = proEconAlarmPlanService.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 =false;
        if(StringUtils.notEmp(id))
        {
            List<String> idls= Arrays.asList(id.split(","));   ;
            i = proEconAlarmPlanService.deleteAlertrule(idls);
        }





        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 = "types", 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 = "types", required = false) String types
    ) {
        Page<ProEconAlarmPlan> page = new Page(pageNum, pageSize);

        IPage<ProEconAlarmPlan> pageResult = proEconAlarmPlanService.pageQueryAll(page, name,types);


        if (StringUtils.notEmp(pageResult)) {

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


    //@UserLoginToken
    @PostMapping(value = "/save-batch")
    @ResponseBody
    @ApiOperation(value = "批量保存", notes = "批量保存")
    public AjaxResult saveAlertruleBatch(HttpServletRequest request, @RequestBody List<ProEconAlarmPlan> lst) throws Exception {


        boolean allCheck = true;

        for (ProEconAlarmPlan alertrule : lst) {
            String msg = "";
            boolean result = true;
            if (StringUtils.isBlank(alertrule.getName())) {
                msg = "名称不能为空";
                result = false;
            } else if (StringUtils.isBlank(alertrule.getSpareParts())) {
                msg = "备件不能为空";
                result = false;
            } else if (StringUtils.isBlank(alertrule.getTroubleMethod())) {
                msg = "排查步骤不能为空";
                result = false;
            } else if (StringUtils.empty(alertrule.getProcessMethod())) {
                msg = "检修方案不能为空";
                result = false;
            } else if (StringUtils.isBlank(alertrule.getTools())) {
                msg = "所需工具不能为空";
                result = false;
            }

            if (result != true) {
                allCheck = false;
                if (!result) {
                    return AjaxResult.successData(AjaxStatus.error.code, msg);
                }
            }
        }
        if (allCheck) {
            for (ProEconAlarmPlan alertRule : lst) {
                int result = proEconAlarmPlanService.saveAndUpdateAlertrule(alertRule);
                if (result <= 0) {
                    return AjaxResult.successData(AjaxStatus.error.code, alertRule.getName() + ":" + "操作数据库失败");

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


    }


    @GetMapping("/importtemplate")
    @ApiOperation(value = "获得导入模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo


        List<ProEconAlarmPlan> list = Arrays.asList(
                ProEconAlarmPlan.builder().id("1").types("类型1").troubleMethod("排查步骤1")
                        .processMethod("检修方案").tools("所需工具1").spareParts("备品备件1").name("名字1").typedetails("类别1")

                        .build(),
                ProEconAlarmPlan.builder().id("2").types("类型2").troubleMethod("排查步骤2")
                        .processMethod("检修方案2").tools("所需工具2").spareParts("备品备件2").name("名字2").typedetails("类别2")

                        .build()

        );

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

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

        if (com.gyee.common.model.StringUtils.notEmp(list) && !list.isEmpty()) {
            boolean allCheck = true;
            for (ProEconAlarmPlan alertrule : list) {
                String msg = "";
                boolean result = true;
                if (StringUtils.isBlank(alertrule.getTypes())) {
                    msg = "类型不能为空";
                    result = false;
                } else if (StringUtils.isBlank(alertrule.getTroubleMethod())) {
                    msg = "排查方法不能为空";
                    result = false;
                } else if (StringUtils.isBlank(alertrule.getProcessMethod())) {
                    msg = "处理方法不能为空";
                    result = false;
                } else if (StringUtils.empty(alertrule.getTools())) {
                    msg = "处理工具不能为空";
                    result = false;
                } else if (StringUtils.empty(alertrule.getName())) {
                    msg = "名称不能为空";
                    result = false;
                } else if (StringUtils.empty(alertrule.getTypedetails())) {
                    msg = "类别不能为空";
                    result = false;
                }
                if (result != true) {
                    allCheck = false;
                    if (!result) {
                        return AjaxResult.successData(AjaxStatus.error.code, msg);
                    }
                }

                if (allCheck) {


                    proEconAlarmPlanService.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");
        }


    }

}
