package com.pqs9900.controller.terminal;

import cn.hutool.core.collection.CollectionUtil;
import com.njcn.enums.LogTypeEnum;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.configuration.DevFunction;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.utils.PubUtils;
import com.njcn.utils.XssFilterUtil;
import com.pqs9900.pojo.DataInfo.TerminalPojo;
import com.pqs9900.pojo.terminal.DeviceIpRVO;
import com.pqs9900.pojo.terminal.EdData;
import com.pqs9900.pojo.terminal.UpParamPojo;
import com.pqs9900.service.terminal.VersionService;
import org.apache.ibatis.annotations.Param;
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.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @Description pqs9900 终端管理  版本管理
 * @Author cdf
 * @Date 2020/7/30 10:56
 **/
@RestController
@RequestMapping("version")
public class VersionController {
    @Resource
    private UserLogDetailService userLog;

    @Autowired
    private VersionService versionService;

    /**
     * @Author chendaofei
     * @Description 获取所有终端
     * @Date 10:58 2020/7/30
     **/
    @GetMapping("getTerminalList")
    public HttpResult getTerminalList(Integer status, String devType,String devSeries,Integer upIsNo) {
        List<TerminalPojo> list = versionService.getDeviceList(status, devType,devSeries,upIsNo);
        return PubUtils.assignmentResult(list, 200, "获取成功");
    }

    /**
     * @Author chendaofei
     * @Description 获取所有终端
     * @Date 10:58 2020/7/30
     **/
    @PostMapping("getTerminalListForUp")
    public HttpResult getTerminalListForUp(@RequestBody List<String> devarr) {
        List<TerminalPojo> list = versionService.getTerminalListForUp(devarr);
        return PubUtils.assignmentResult(list, 200, "获取成功");
    }


    /**
     * @Author chendaofei
     * @Description 添加版本
     * @Date 10:58 2020/7/30
     **/
    @PostMapping("addVersion")
    public HttpResult addVersion(HttpServletRequest request, @RequestParam("edName") String edName, @RequestParam("edProtocol") String edProtocol, @RequestParam("edDate") String edDate, @RequestParam("edDescribe") String edDescribe, @RequestParam("devType") String devType, @RequestParam(value = "type",required = false) String type, @RequestParam("file") MultipartFile file) {
        if (PubUtils.isBlank(edName)||PubUtils.isBlank(edProtocol)||PubUtils.isBlank(edDate)||PubUtils.isBlank(devType)) {
            return PubUtils.assignmentResult(null, 500, "参数不可为空");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            sdf.parse(edDate);
        } catch (ParseException e) {
            return PubUtils.assignmentResult(null, 500, "时间格式有误");
        }
        if (file.isEmpty()) {
            return PubUtils.assignmentResult(null, 500, "请上传升级文件");
        } else {
            String fileName = file.getOriginalFilename();
            if(fileName.lastIndexOf(".")!=-1){
                //文件后缀,判断上传文件格式
                String subffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
                if (!judgeFileType(subffix)) {
                    return PubUtils.assignmentResult(null, 500, "请上传后缀为bin的文件或无后缀文件");
                }
            }

        }
        edName = XssFilterUtil.dealString(edName);
        edProtocol = XssFilterUtil.dealString(edProtocol);
        edDescribe = XssFilterUtil.dealString(edDescribe);
        type = XssFilterUtil.dealString(type);
        String res = versionService.addVersion(edName, edDescribe,edProtocol,edDate,devType,type,file);
        if ("新增成功".equals(res)) {
            userLog.getLog("新增终端升级程序版本", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            return PubUtils.assignmentResult(null, 200, res);
        } else {
            userLog.getLog("新增终端升级程序版本", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            return PubUtils.assignmentResult(null, 500, res);
        }

    }

    /**
     * @Author chendaofei
     * @Description 更新版本
     * @Date 10:58 2020/7/30
     **/
    @PostMapping("updateVersion")
    public HttpResult updateVersion(HttpServletRequest request,@RequestParam("edIndex") String edIndex, @RequestParam("edName") String edName,@RequestParam("edProtocol") String edProtocol,@RequestParam("edDate") String edDate, @RequestParam("edDescribe") String edDescribe,@RequestParam("devType") String devType,@RequestParam(value = "type",required = false) String type, @RequestParam(value = "file",required = false) MultipartFile file) {
        if (PubUtils.isBlank(edName) || PubUtils.isBlank(edProtocol) || PubUtils.isBlank(edIndex) ||PubUtils.isBlank(edDate)) {
            return PubUtils.assignmentResult(null, 500, "参数不可为空");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            sdf.parse(edDate);
        } catch (ParseException e) {
            return PubUtils.assignmentResult(null, 500, "时间格式有误");
        }
        if (file!=null) {
            if(!file.isEmpty()){
                String fileName = file.getOriginalFilename();
                if(fileName.lastIndexOf(".")!=-1){
                    //文件后缀,判断上传文件格式
                    String subffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
                    if (!judgeFileType(subffix)) {
                        return PubUtils.assignmentResult(null, 500, "请上传后缀为bin的文件或无后缀文件");
                    }
                }
            }
        }
        edName = XssFilterUtil.dealString(edName);
        edProtocol = XssFilterUtil.dealString(edProtocol);
        edDescribe = XssFilterUtil.dealString(edDescribe);
        type = XssFilterUtil.dealString(type);
        String res = versionService.updateVersion(edIndex, edName, edDescribe,edProtocol,edDate,devType,type,file);
        if ("修改成功".equals(res)) {
            userLog.getLog("修改终端升级程序版本", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            return PubUtils.assignmentResult(null, 200, res);
        } else {
            userLog.getLog("修改终端升级程序版本", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            return PubUtils.assignmentResult(null, 500, res);
        }
    }

    /**
     * @Author chendaofei
     * @Description 删除版本
     * @Date 10:58 2020/7/30
     **/
    @GetMapping("delVersion")
    public HttpResult delVersion(HttpServletRequest request,String edIndex) {
        if(PubUtils.isBlank(edIndex)){
            return PubUtils.assignmentResult(null, 500, "参数不可为空");
        }
        Integer res = versionService.delVersion(edIndex);
        if (res == 1) {
            userLog.getLog("删除终端升级程序版本", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            return PubUtils.assignmentResult(null, 200, "删除成功");
        } else if(res == -1){
            userLog.getLog("删除终端升级程序版本", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            return PubUtils.assignmentResult(null, 500, "当前版本已经绑定装置,不可删除");
        } else {
            userLog.getLog("删除终端升级程序版本", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            return PubUtils.assignmentResult(null, 500, "删除失败");
        }

    }

    /**
     * @Author chendaofei
     * @Description 启用停用版本
     * @Date 10:58 2020/7/30
     **/
    @PostMapping("enableDisable")
    public HttpResult enableDisable(HttpServletRequest request,String edIndex,Integer status) {
        if(PubUtils.isBlank(edIndex) || status == null){
            return PubUtils.assignmentResult(null, 500, "参数不可为空");
        }
        Integer res = versionService.enableDisable(edIndex,status);
        if (res == 1) {
            userLog.getLog("启用停用终端升级程序版本", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            return PubUtils.assignmentResult(null, 200, "切换成功");
        } else {
            userLog.getLog("启用停用终端升级程序版本", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            return PubUtils.assignmentResult(null, 500, "操作失败");
        }

    }

    /**
     * @Author chendaofei
     * @Description 根据id获取版本
     * @Date 10:58 2020/7/30
     **/
    @GetMapping("getVersion")
    public HttpResult getVersion(String edIndex) {
        if(PubUtils.isBlank(edIndex)){
            return PubUtils.assignmentResult(null, 500, "参数不可为空");
        }
        EdData edData = versionService.getVersion(edIndex);
        return PubUtils.assignmentResult(edData, 200, "获取成功");
    }

    /**
     * @Author chendaofei
     * @Description 根据id获取版本存在bolb类型字段加载过慢
     * @Date 10:58 2020/7/30
     **/
    @GetMapping("getVersionTwo")
    public HttpResult getVersionTwo(String edIndex) {
        if(PubUtils.isBlank(edIndex)){
            return PubUtils.assignmentResult(null, 500, "参数不可为空");
        }
        EdData edData = versionService.getVersionTwo(edIndex);
        return PubUtils.assignmentResult(edData, 200, "获取成功");
    }

    /**
     * @Author chendaofei
     * @Description 获取所有版本列表
     * @Date 10:58 2020/7/30
     **/
    @GetMapping("getVersionList")
    public HttpResult getVersionList(String blob,String devType) {
        List<EdData> list = versionService.getVersionList(blob,devType);
        return PubUtils.assignmentResult(list, 200, "获取成功");
    }

    /**
     * @Author chendaofei
     * @Description 获取所有版本列表过滤掉已有版本
     * @Date 10:58 2020/7/30
     **/
    @PostMapping("getVersionListFilterDevIndex")
    public HttpResult getVersionListFilterEdIndex(@RequestBody UpParamPojo upParamPojo) {
        String devType = upParamPojo.getDevType();
        String blob = upParamPojo.getBlob();
        List<String> edList = upParamPojo.getEdList();
        if (PubUtils.isBlank(devType) || PubUtils.isBlank(blob) || CollectionUtil.isEmpty(edList)) {
            return PubUtils.assignmentResult(null, 500, "参数不可为空");
        }

        List<EdData> list = versionService.getVersionListFilterEdIndex(devType,blob,edList);
        return PubUtils.assignmentResult(list, 200, "获取成功");
    }

    /**
     * @Author chendaofei
     * @Description
     * @Date 14:45 2020/8/11
     **/
    @PostMapping("getTemplet")
    public HttpResult getTemplet(@RequestBody DeviceIpRVO deviceIpRVO) {


        List<String> list = deviceIpRVO.getIndexlist();
        if (CollectionUtil.isEmpty(list)) {
            return PubUtils.assignmentResult(null, 500, "请选择终端");
        }
        if (PubUtils.isBlank(deviceIpRVO.getNodeIndex())) {
            return PubUtils.assignmentResult(null, 500, "请选择版本号");
        }
        try {
            String edIndex = deviceIpRVO.getNodeIndex();
            String res = versionService.getTemplet(list, edIndex);
            if ("运行成功".equals(res)) {
                return PubUtils.assignmentResult(null, 200, "执行成功");
            } else {
                return PubUtils.assignmentResult(null, 500, res);
            }
        } catch (Exception e) {
            return PubUtils.assignmentResult(null, 500, "连接异常");
        }

    }

    private Boolean judgeFileType(String subffix) {
        boolean result = false;

        if ("bin".equals(subffix)) {
            result = true;
        }

        return result;
    }

    /**
     * @Author chendaofei
     * @Description 获取启用装置功能
     * @Date 14:45 2020/8/11
     **/
    @GetMapping("getDevfunction")
    public HttpResult getDevfunction(String devIndex) {
        if(PubUtils.isBlank(devIndex)){
            return PubUtils.assignmentResult(null, 500, "参数不可为空");
        }
        List<DevFunction> devfunction = versionService.getDevfunction(devIndex);
        return PubUtils.assignmentResult(devfunction,200,"获取成功");
    }

    /**
     * @Author chendaofei
     * @Description 获取升级日志
     * @Date 14:45 2020/8/11
     **/
    @GetMapping("getUpdetail")
    public HttpResult getUpdetail(String devIndex) {
        if(PubUtils.isBlank(devIndex)){
            return PubUtils.assignmentResult(null, 500, "参数不可为空");
        }
        List<TerminalPojo> devfunction = versionService.getUpdetail(devIndex);
        return PubUtils.assignmentResult(devfunction,200,"获取成功");
    }


    /**
     * 批量单点重启装置命令
     * @author cdf
     * @date 2021/7/30
     */
    @PostMapping("restartDev")
    public HttpResult restartDev(@RequestBody List<String> devList){
        if(CollectionUtil.isEmpty(devList)){
            return PubUtils.assignmentResult(null,500,"重启装置命令发送失败");
        }else {
            //根据装置id获取前置机的ip
           String res = versionService.restartDev(devList);
           if("命令发送成功".equals(res)){
               return PubUtils.assignmentResult(null,200,"重启装置命令发送成功");
           }else {
               return PubUtils.assignmentResult(null,500,res);
           }
        }
    }

    /**
     * 批量单点重启装置命令
     * @author dhj
     * @date 2021/7/30
     */
    @RequestMapping(value = "restartDevConValue", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult restartDevConValue(HttpServletRequest request,Integer devnumber){
        if(CollectionUtil.isEmpty(Collections.singleton(devnumber))){
            return PubUtils.assignmentResult(null,500,"重启装置命令发送失败");
        }else {
            //根据装置id获取前置机的ip
            String res = versionService.restartDevConValue(devnumber);
            if("命令发送成功".equals(res)){
                return PubUtils.assignmentResult(null,200,"重启装置命令发送成功");
            }else {
                return PubUtils.assignmentResult(null,500,res);
            }
        }
    }


    /**
     * 取消升级命令
     * @author cdf
     * @date 2021/8/2
     */
    @PostMapping("cancelUp")
    public HttpResult cancelUp(@RequestBody List<String> devList){
        if(CollectionUtil.isEmpty(devList)){
            return PubUtils.assignmentResult(null,500,"取消升级命令发送失败");
        }else {
            //根据装置id获取前置机的ip
            String res = versionService.cancelUp(devList);
            if("取消命令发送成功".equals(res)){
                return PubUtils.assignmentResult(null,200,"取消命令发送成功");
            }else {
                return PubUtils.assignmentResult(null,500,res);
            }
        }
    }

    /**
     * 判断是否升级成功
     * @author cdf
     * @date 2021/8/30
     */
    @PostMapping("upFlag")
    public HttpResult upFlag(@RequestBody List<Integer> devIndex){
        List<TerminalPojo> list = versionService.upFlag(devIndex);
        if(CollectionUtil.isNotEmpty(list)){
            return PubUtils.assignmentResult(list,200,"获取成功");
        }else {
            return PubUtils.assignmentResult(list,500,"获取失败");
        }
    }

    /**
     * 记录升级版本日志
     * @author cdf
     * @date 2021/8/30
     */
    @PostMapping("logsPush")
    public HttpResult logsPush(@RequestBody List<Map<String, String>> map){
        try {
            versionService.logsPush(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return PubUtils.assignmentResult(null,200,"日志录入成功");
    }

}
