package com.gyee.wisdom.alarm.sharding.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gyee.wisdom.alarm.sharding.config.AjaxResult;
import com.gyee.wisdom.alarm.sharding.entity.Alertrule2;
import com.gyee.wisdom.alarm.sharding.entity.DeviceMetrics;
import com.gyee.wisdom.alarm.sharding.model.TreeNode;
import com.gyee.wisdom.alarm.sharding.service.Alertrule2Service;
import com.gyee.wisdom.alarm.sharding.util.ExcelUtil;
import com.gyee.wisdom.alarm.sharding.util.TokenUtil;
import com.gyee.wisdom.alarm.sharding.util.UserLoginToken;
import com.gyee.wisdom.alarm.sharding.util.ResponseWrapper;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/alertrule2")
@CrossOrigin
@Api(tags = {"自定义规则接口"})
public class Alertrule2Controller {

    @Autowired
    private Alertrule2Service alertrule2Service;

    @GetMapping(value = "/list")
    public List<Alertrule2> queryTree() {
        List<Alertrule2> alertrules = alertrule2Service.queryTree();
        return alertrules;
    }

    @GetMapping(value = "/map")
    public List<Map<String, Alertrule2>> queryMap() {
        List<Map<String, Alertrule2>> alertrules = alertrule2Service.queryMap();
        return alertrules;
    }


    //@UserLoginToken
    @PostMapping(value = "/save")
    @ResponseBody
    @UserLoginToken
    public ResponseWrapper<Alertrule2> saveAlertrule2(HttpServletRequest request, @RequestBody Alertrule2 alertrule2) {

        String token=request.getHeader("token");
        Claims claims = TokenUtil.parseJWT(token);
        String userName=claims.get("jti").toString();
        ResponseWrapper<Alertrule2> wrapper = dataCheck(alertrule2);
        if (wrapper.getSuccess()) {
            int result = alertrule2Service.saveAndUpdateAlertrule2(alertrule2,userName);
            if (result <= 0) {
                if(result==-999)
                {
                    wrapper.setMsg("报警规则id生成错误,请联系管理员");
                }
                else {
                    wrapper.setMsg("操作数据库失败");
                }

                wrapper.setSuccess(false);
            }else{
                wrapper.success("操作成功");
            }
        }
        return wrapper;

    }

    @DeleteMapping(value = "/delete")
    public int deleteAlertrule2(Alertrule2 alertrule2) {
        return alertrule2Service.deleteAlertrule2(alertrule2);
    }

    //@UserLoginToken
    @GetMapping(value = "/page")
    public IPage<Alertrule2> queryByPage(
            @RequestParam(value = "pagenum") Integer pageNum,
            @RequestParam(value = "pagesize") Integer pageSize,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "station", required = false) String station,
            @RequestParam(value = "modelId", required = false) String modelId,
            @RequestParam(value = "rank", required = false) String rank,
            @RequestParam(value = "category", required = false) String category
    ) {
        Page<Alertrule2> page = new Page(pageNum, pageSize);
        IPage<Alertrule2> pageResult = alertrule2Service.pageQueryAll(page, name,station,modelId,rank,category);

        return pageResult;
    }

    private ResponseWrapper<Alertrule2> dataCheck(Alertrule2 alertrule) {
        ResponseWrapper<Alertrule2> wrapper = null;
        String msg = "";
        boolean result = true;
        if (StringUtils.isBlank(alertrule.getName())) {
            msg = "报警名称不能为空";
            result = false;
        } else if (StringUtils.isBlank(alertrule.getDescription())) {
            msg = "规则描述不能为空";
            result = false;
        } else if (StringUtils.isBlank(alertrule.getExpression())) {
            msg = "报警规则不能为空";
            result = false;
        } else if (StringUtils.isBlank(alertrule.getRank())) {
            msg = "报警级别不能为空";
            result = false;
        } else if (StringUtils.isBlank(alertrule.getEnabled()+"")) {
            msg = "是否可用不能为空";
            result = false;
        } else if (StringUtils.isBlank(alertrule.getStation())) {
            msg = "风场不能为空";
            result = false;
        } else if (StringUtils.isBlank(alertrule.getCategory())) {
            msg = "报警类别不能为空";
            result = false;
        }
        if (alertrule.getCategory().equals("1")) {
            if (StringUtils.isBlank(alertrule.getModelId())) {
                msg = "风机型号不能为空";
                result = false;
            }
        }

        if (result) {
            wrapper = ResponseWrapper.success(msg, alertrule);
        } else {
            wrapper = ResponseWrapper.error(msg, alertrule);
        }
        return wrapper;
    }

    //@UserLoginToken
    @PostMapping(value = "/save-batch")
    @ResponseBody
    @UserLoginToken
    public ResponseWrapper<Alertrule2> saveAlertrule2Batch(HttpServletRequest request,@RequestBody List<Alertrule2> lst) {

        String token=request.getHeader("token");
        Claims claims = TokenUtil.parseJWT(token);
        String userName=claims.get("jti").toString();

        boolean allCheck = true;
        ResponseWrapper<Alertrule2> wrapper = null;
        for (Alertrule2 alertRule : lst) {
            wrapper = dataCheck(alertRule);
            if (wrapper.getSuccess() != true) {
                allCheck = false;
                String msg = wrapper.getMsg();
                wrapper.setMsg(alertRule.getName() + "：" + msg);
                break;
            }
        }
        if (allCheck) {
            for (Alertrule2 alertRule : lst) {
                int result = alertrule2Service.saveAndUpdateAlertrule2(alertRule,userName);
                if (result <= 0) {
                    wrapper.setMsg(alertRule.getName() + ":" + "操作数据库失败");
                    wrapper.setSuccess(false);
                    break;
                }
            }
            return wrapper;
        } else {
            return wrapper;
        }


    }


    @ApiOperation("自定义规则批量导入")
    @PostMapping(value ="/import")
    @ResponseBody
    @UserLoginToken
    public ResponseWrapper<Alertrule2> importAlertrule(@ApiParam(value = "导入文件") @RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String token=request.getHeader("token");
        Claims claims = TokenUtil.parseJWT(token);
        String userName=claims.get("jti").toString();
        ResponseWrapper<Alertrule2> wrapper = null;
        boolean allCheck = true;
        if (!file.isEmpty()) {
            try {
                //获取原始的文件名
                String originalFilename = file.getOriginalFilename();
                //获取文件类型
                String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
                //默认从第一行开始读取
                Integer startRows = 1;
                //获取输入流
                InputStream is = file.getInputStream();
                List<Alertrule2> bindingList = new ArrayList<>();
                //Excel导入导出的单元类
                List<String[]> strings = ExcelUtil.readData(fileType, startRows, true, is);
                //遍历Excel表每一行的数据
                for (String[] str : strings) {
                    Alertrule2 alertrule2 = new Alertrule2();
                    alertrule2.setId(str[0]);
                    alertrule2.setName(str[1]);
                    alertrule2.setCategory(str[2]);
                    alertrule2.setRank(str[3]);
                    alertrule2.setEnabled(Integer.parseInt(str[4]));
                    alertrule2.setStation(str[5]);
                    alertrule2.setModelId(str[6]);
                    alertrule2.setRelatedParts(str[7]);
                    alertrule2.setExpression(str[8]);
                    alertrule2.setDescription(str[9]);
                    bindingList.add(alertrule2);
                }
                for (Alertrule2 alertRule : bindingList) {
                    wrapper = dataCheck(alertRule);
                    if (wrapper.getSuccess() != true) {
                        allCheck = false;
                        String msg = wrapper.getMsg();
                        wrapper.setMsg(alertRule.getName() + "：" + msg);
                        break;
                    }
                }
                if (allCheck) {
                    for (Alertrule2 alertRule : bindingList) {
                        int result = alertrule2Service.saveAndUpdateAlertrule2(alertRule, userName);
                        if (result <= 0) {
                            wrapper.setMsg(alertRule.getName() + ":" + "操作数据库失败");
                            wrapper.setSuccess(false);
                            break;
                        }else {
                            wrapper.setMsg("批量导入成功");
                            wrapper.setSuccess(true);
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return wrapper;
    }
}
