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.Scadabj;
import com.gyee.wisdom.alarm.sharding.entity.Scadafault;
import com.gyee.wisdom.alarm.sharding.entity.Warning2;
import com.gyee.wisdom.alarm.sharding.service.ScadafaultService;
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.service.Warning2Service;
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.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("/warning2")
@CrossOrigin
@Api(tags = {"warning2接口"})
public class Warning2Controller {

    @Autowired
    private Warning2Service warning2Service;

    //@UserLoginToken
    @PostMapping(value = "/save")
    @ResponseBody
    @UserLoginToken
    public ResponseWrapper saveWarning(HttpServletRequest request,@RequestBody Warning2 warning2) {
        String token=request.getHeader("token");
        Claims claims = TokenUtil.parseJWT(token);
        String userName=claims.get("jti").toString();
        ResponseWrapper<Warning2> wrapper = dataCheck(warning2);
        if (wrapper.getSuccess()) {
            int result = warning2Service.saveAndUpdateWarning2(warning2,userName);
            if (result <= 0) {
                wrapper.setSuccess(false);
                wrapper.setMsg("操作数据库失败");
            }
        }
        return wrapper;
    }

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


    }

    @ApiOperation("Warning2批量导入")
    @PostMapping(value ="/import")
    @ResponseBody
    @UserLoginToken
    public ResponseWrapper<Warning2> importWarning(@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<Warning2> 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<Warning2> bindingList = new ArrayList<>();
                //Excel导入导出的单元类
                List<String[]> strings = ExcelUtil.readData(fileType, startRows, true, is);
                //遍历Excel表每一行的数据
                for (String[] str : strings) {
                    Warning2 warning2 = new Warning2();
                    warning2.setId(str[0]);
                    warning2.setLevelId(str[1]);
                    warning2.setManufacturerCode(str[2]);
                    warning2.setChineseText(str[3]);
                    warning2.setParentId(str[4]);
                    warning2.setIsleaf(Integer.parseInt(str[5]));
                    warning2.setSequenceNumber(Integer.parseInt(str[6]));
                    warning2.setCharacteristic(str[7]);
                    warning2.setModelId(str[8]);
                    warning2.setCodeName(str[9]);
                    warning2.setEdnaValue(Integer.parseInt(str[10]));
                    warning2.setDisplay(Integer.parseInt(str[11]));
                    warning2.setWarningClassIfyId(str[12]);
                    warning2.setStandardTime(Integer.parseInt(str[13]));
                    warning2.setIsreset(Integer.parseInt(str[14]));
                    warning2.setWarningTypeId(str[15]);
                    warning2.setFaultCode(str[16]);
                    warning2.setRelatedParts(str[17]);
                    bindingList.add(warning2);
                }
                for (Warning2 warning : bindingList) {
                    wrapper = dataCheck(warning);
                    if (wrapper.getSuccess() != true) {
                        allCheck = false;
                        String msg = wrapper.getMsg();
                        wrapper.setMsg(warning.getChineseText() + "：" + msg);
                        break;
                    }
                }
                if (allCheck) {
                    for (Warning2 warning : bindingList) {
                        int result = warning2Service.saveAndUpdateWarning2(warning,userName);
                        if (result <= 0) {
                            wrapper.setMsg(warning.getChineseText() + ":" + "操作数据库失败");
                            wrapper.setSuccess(false);
                            break;
                        }
                        else {
                            wrapper.setMsg("批量导入成功");
                            wrapper.setSuccess(true);
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return wrapper;
    }

    @DeleteMapping(value = "/delete")
    public int deleteScadafault(Warning2 warning2) {
        return warning2Service.deleteWarning2(warning2);
    }

    //@UserLoginToken
    @GetMapping(value = "/page")
    public IPage<Warning2> queryByPage(
            @RequestParam(value = "pagenum") Integer pageNum,
            @RequestParam(value = "pagesize") Integer pageSize,
            @RequestParam(value = "modelId", required = false) String modelId,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "isLeaf", required = false) String isLeaf
    ) {
        Page<Warning2> page = new Page(pageNum, pageSize);
        return warning2Service.pageQueryAll(page, modelId, name, isLeaf);
    }

    private ResponseWrapper<Warning2> dataCheck(Warning2 warning) {

        ResponseWrapper<Warning2> wrapper = null;
        String msg = "";
        boolean result = true;
        if (warning.getModelId() != null && warning.getModelId().equals("")) {
            msg = "风机型号不能为空";
            result = false;
        } else if (warning.getEdnaValue() == 0) {
            msg = "统一编码不能为空";
            result = false;
        } else if (warning.getChineseText() != null && warning.getChineseText().equals("")) {
            msg = "报警名称不能为空";
            result = false;
        } else if (StringUtils.isBlank(warning.getLevelId())) {
            msg = "报警级别不能为空";
            result = false;
        }
        if (result) {
            wrapper = ResponseWrapper.success(msg, warning);
        } else {
            wrapper = ResponseWrapper.error(msg, warning);
        }
        return wrapper;
    }
}
