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.entity.Alertrule2;
import com.gyee.wisdom.alarm.sharding.entity.Scadabj;
import com.gyee.wisdom.alarm.sharding.service.Alertrule2Service;
import com.gyee.wisdom.alarm.sharding.service.ScadabjService;
import com.gyee.wisdom.alarm.sharding.util.*;
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.springframework.beans.factory.annotation.Autowired;
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;

@Slf4j
@RestController
@RequestMapping("/scadabj")
@CrossOrigin
@Api(tags = {"scadabj接口"})
public class ScadabjController {

    @Autowired
    private ScadabjService scadabjService;

    //@UserLoginToken
    @PostMapping(value = "/save")
    @ResponseBody
    @UserLoginToken
    public ResponseWrapper<Scadabj> saveScadabj(HttpServletRequest request, @RequestBody Scadabj scadabj) {
        String token=request.getHeader("token");
        Claims claims = TokenUtil.parseJWT(token);
        String userName=claims.get("jti").toString();
        ResponseWrapper<Scadabj> wrapper = dataCheck(scadabj);
        if (wrapper.getSuccess()) {
            //mybatis 操作数据库成功会返回影响的条数,如果成功则为1,失败为0
            int result = scadabjService.saveAndUpdateScadabj(scadabj,userName);
            if (result <= 0) {
                wrapper.setSuccess(false);
                wrapper.setMsg("操作数据库失败");
            }
        }
        return wrapper;

    }

    @DeleteMapping(value = "/delete")
    public int deleteScadabj(Scadabj scadabj) {
        return scadabjService.deleteScadabj(scadabj);
    }


    //@UserLoginToken
    @GetMapping(value = "/page")
    public IPage<Scadabj> queryByPage(
            @RequestParam(value = "pagenum") Integer pageNum,
            @RequestParam(value = "pagesize") Integer pageSize,
            @RequestParam(value = "pointKey", required = false) String pointKey,
            @RequestParam(value = "stationId", required = false) String stationId,
            @RequestParam(value = "enable", required = false) String enable,
            @RequestParam(value = "description", required = false) String description

    ) {
        Page<Scadabj> page = new Page(pageNum, pageSize);
        IPage<Scadabj> pg = scadabjService.pageQueryAll(page, pointKey, stationId, enable, description);
        return pg;
    }

    //@UserLoginToken
    @PostMapping(value = "/save-batch")
    @ResponseBody
    @UserLoginToken
    public ResponseWrapper<Scadabj> saveScadabjBatch(HttpServletRequest request,@RequestBody List<Scadabj> lst) {
        String token=request.getHeader("token");
        Claims claims = TokenUtil.parseJWT(token);
        String userName=claims.get("jti").toString();
        boolean allCheck = true;
        ResponseWrapper<Scadabj> wrapper = null;
        for (Scadabj scadabj : lst) {
            wrapper = dataCheck(scadabj);
            if (wrapper.getSuccess() != true) {
                allCheck = false;
                String msg = wrapper.getMsg();
                wrapper.setMsg(scadabj.getDescription() + "：" + msg);
                break;
            }
        }
        if (allCheck) {
            for (Scadabj scadabj : lst) {
                int result = scadabjService.saveAndUpdateScadabj(scadabj,userName);
                if (result <= 0) {
                    wrapper.setMsg(scadabj.getDescription() + ":" + "操作数据库失败");
                    wrapper.setSuccess(false);
                    break;
                }
            }
            return wrapper;
        } else {
            return wrapper;
        }

    }

    @ApiOperation("Scadabj批量导入")
    @PostMapping(value = "/import")
    @ResponseBody
    @UserLoginToken
    public ResponseWrapper<Scadabj> saveScadabjImport(@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<Scadabj> 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<Scadabj> bindingList = new ArrayList<>();
                List<String[]> strings = ExcelUtil.readData(fileType, startRows, true, is);
                for (String[] str : strings) {
                    Scadabj scadabj = new Scadabj();
                    if (str[0] == null || str[0].equals("")){
                        scadabj.setId(SnowflakeGenerator.generateId());
                    }else {
                        scadabj.setId(Long.valueOf(str[0]));
                    }
                    scadabj.setStationId(str[1]);
                    scadabj.setPointKey(str[2]);
                    scadabj.setDescription(str[3]);
                    scadabj.setCategory1(str[4]);
                    scadabj.setCategory2(str[5]);
                    scadabj.setCategory3(str[6]);
                    scadabj.setCategory4(str[7]);
                    scadabj.setRank(str[8]);
                    scadabj.setAlarmType(Integer.parseInt(str[9]));
                    scadabj.setEnabled(Integer.parseInt(str[10]));
                    if(str.length==12){
                        scadabj.setDeviceId(str[11]);
                    }
                    bindingList.add(scadabj);
                }
                for (Scadabj scadabj : bindingList) {
                    wrapper = dataCheck(scadabj);
                    if (wrapper.getSuccess() != true) {
                        allCheck = false;
                        String msg = wrapper.getMsg();
                        wrapper.setMsg(scadabj.getDescription() + "：" + msg);
                        break;
                    }
                }
                if (allCheck) {
                    for (Scadabj scadabj : bindingList) {
                        int result = scadabjService.saveAndUpdateScadabj(scadabj, userName);
                        if (result <= 0) {
                            wrapper.setMsg(scadabj.getDescription() + ":" + "操作数据库失败");
                            wrapper.setSuccess(false);
                            break;
                        }else {
                            wrapper.setMsg("批量导入成功");
                            wrapper.setSuccess(true);
                        }
                    }
                }
            } catch (IOException e) {
                wrapper.setMsg("操作数据库失败");
                wrapper.setSuccess(false);
            }
        }
        return wrapper;
    }


    private ResponseWrapper<Scadabj> dataCheck(Scadabj scadabj) {

        ResponseWrapper<Scadabj> wrapper = null;
        String msg = "";
        boolean result = true;
        if (scadabj.getPointKey() != null && scadabj.getPointKey().equals("")) {
            msg = "测点不能为空";
            result = false;
        } else if (scadabj.getDescription() != null && scadabj.getDescription().equals("")) {
            msg = "描述不能为空";
            result = false;
        } else if (scadabj.getRank() != null && scadabj.getRank().equals("")) {
            msg = "报警级别不能为空";
            result = false;
        } else if (scadabj.getEnabled() == -1) {
            msg = "是否可用不能为空";
            result = false;
        } else if (scadabj.getAlarmType() == -1) {
            msg = "报警逻辑不能为空";
            result = false;
        }
        if (result) {
            wrapper = ResponseWrapper.success(msg, scadabj);
        } else {
            wrapper = ResponseWrapper.error(msg, scadabj);
        }
        return wrapper;
    }
}
