package com.pqs9900.controller.user;
import com.njcn.enums.LogTypeEnum;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.configuration.DicData;
import com.njcn.pojo.user.TransFormer;
import com.njcn.sso.pojo.user.User;
import com.njcn.service.configuration.DicDataService;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.service.user.TransFormerService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.PubUtils;
import com.njcn.utils.XssFilterUtil;
import com.njcn.utils.redis.RedisCacheUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.security.auth.login.AccountException;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("trans")
public class TransFormerController {
	// 日志记录
    private static final Logger logger = LoggerFactory.getLogger(TransFormerController.class);
	@Resource
	private TransFormerService tfs;

	@Autowired
    RedisCacheUtil redisCacheUtil;

	@Resource
	private DicDataService dds;
	
	@Resource
	private UserLogDetailService userLog;
	/**
     * 获取所有变压器台账
     */
    @RequestMapping(value = "selectAll", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult selectAll(HttpServletRequest request) throws AccountException {
        HttpResult result = new HttpResult();
        try {
            List<List> transfomer = tfs.selectAll();
            if (transfomer.isEmpty()) {
                result.setCode(500);
                result.setMessage("没有获取到所有变压器台账列表");
                userLog.getLog("查询变压器", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),0);
                logger.error("获取所有变压器台账失败");
            } else {
                result.setCode(200);
                result.setBody(transfomer);
                result.setMessage("获取所有变压器台账列表成功");
                userLog.getLog("查询变压器", "成功",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),0);
                logger.info("获取所有变压器台账成功");
            }
        }catch (Exception e){
            logger.error("获取变压器信息异常，异常为"+e.toString());
            userLog.getLog("查询变压器", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),0);
            result=PubUtils.assignmentResult(null,500,"获取变压器信息失败");
        }
        return result;
    }
    /**
     * 根据name获取所有变压器台账
     */
    @RequestMapping(value = "selectNameAll", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult selectNameAll(HttpServletRequest request,String tfName,int node) throws AccountException {
        HttpResult result = new HttpResult();
        try{
            List<List> transfomer = tfs.selectNameAll(tfName,node);
            if (transfomer.isEmpty()) {
                result.setCode(500);
                result.setMessage("没有获取到所有变压器台账列表");
                userLog.getLog("查询变压器", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),0);
                logger.error("获取所有变压器台账失败");
            } else {
                result.setCode(200);
                result.setBody(transfomer);
                result.setMessage("获取所有变压器台账列表成功");
                userLog.getLog("查询变压器", "成功",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),0);
                logger.info("获取所有变压器台账成功");
            }
        }catch (Exception e){
            userLog.getLog("查询变压器", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),0);
            logger.error("获取变压器台账信息异常，异常为"+e.toString());
            result=PubUtils.assignmentResult(null,500,"获取变压器台账信息失败");
        }

        return result;
    }
    //获取接线方式
    @ResponseBody
	@RequestMapping(value="selectWring",method=RequestMethod.POST)
	public List<DicData> selectWring(){
		List<DicData> list= redisCacheUtil.getWring();
		return list;
	}
    
    /**
	 * 新增变压器
	 * */
	@RequestMapping(value="saveTrans",method=RequestMethod.POST)
	@ResponseBody
	public int saveTrans(HttpServletRequest request,String tfName, int subIndex,String Wiring, String description) throws AccountException {
		//后台Xss攻击处理、包括html/js/sql
		tfName= XssFilterUtil.dealString(tfName);
		Wiring= XssFilterUtil.dealString(Wiring);
		description= XssFilterUtil.dealString(description);
        int message = 0;
		if(!StringUtils.isBlank(tfName)) {
            if (!StringUtils.isBlank(Wiring)) {
                if(PubUtils.patternTrans(tfName)) {
                    if(PubUtils.patternDes500(description)) {
                        try {
                            message = tfs.saveTrans(tfName, subIndex, Wiring, description);
                            if (message == 1) {
                                logger.info("新增变压器成功");
                                userLog.getLog("新增变压器", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                            } else {
                                logger.error("新增变压器失败");
                                userLog.getLog("新增变压器", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                            }
                        } catch (Exception e) {
                            logger.error("新增变压器异常，异常为" + e.toString());
                            message = 0;
                        }
                    }else {
                        message = 5;
                        userLog.getLog("新增变压器", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
                        logger.error("新增变压器失败");
                    }
                }else {
                    message =4;
                    userLog.getLog("新增变压器", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
                    logger.error("新增变压器失败");
                }
            } else {
             message = 3;
             userLog.getLog("新增变压器", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
             logger.error("新增变压器失败");
            }
        }else {
		    message = 2;
            userLog.getLog("新增变压器", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
		    logger.error("新增变压器失败");
        }

		return message;
	}
	// 根据ID查询所有
    @ResponseBody
    @RequestMapping(value = "selectId", method = RequestMethod.POST)
    public TransFormer selectId(@Param(value = "tfIndex") String tfIndex) {
        return tfs.selectId(tfIndex);
    }
    // 根据ID查询所有
    @ResponseBody
    @RequestMapping(value = "selectDataName", method = RequestMethod.POST)
    public List<DicData> selectDataName(@Param(value = "dicIndex") String dicIndex) {
        return dds.selectDataName(dicIndex);
    }
 
    @ResponseBody
    @RequestMapping(value = "selectWiring", method = RequestMethod.POST)
    public List<DicData> selectWiring(@Param(value = "typeId") String typeId) {
        return dds.selectWiring(typeId);
    }
    
    //修改
    @ResponseBody
    @RequestMapping(value = "updateTrans", method = RequestMethod.POST)
    public int updateTrans(HttpServletRequest request,@Param(value="tfIndex")String tfIndex,@Param(value="tfName")String tfName,@Param(value = "subIndex")int subIndex,
    		@Param(value="wiring")String wiring,@Param(value="description")String description) throws AccountException {
        //后台Xss攻击处理、包括html/js/sql
        tfName= XssFilterUtil.dealString(tfName);
        wiring= XssFilterUtil.dealString(wiring);
        description= XssFilterUtil.dealString(description);
        int flag = 2;
        if(!StringUtils.isBlank(tfName)) {
            if (PubUtils.patternTrans(tfName)) {
                if(PubUtils.patternDes500(description)) {
                    Date updateTime = new Date();
                    User user = TokenManager.getToken();
                    String userIndex = user.getUserIndex();
                    TransFormer former = new TransFormer();
                    List<TransFormer> list = tfs.selectName(tfIndex);
                    try {
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getTfName().equals(tfName)) {
                                flag = 0;
                                userLog.getLog("修改变压器", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                                logger.error("修改变压器失败，原因是该变压器名已存在");
                            }
                        }
                        if (flag != 0) {
                            tfs.updateTrans(tfIndex, tfName, subIndex, wiring, description, updateTime, userIndex);
                            userLog.getLog("修改变压器", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                            flag = 1;
                        } else {
                            flag = 0;
                            userLog.getLog("修改变压器", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                            logger.error("修改变压器失败，原因是该变压器名已存在");
                        }
                    } catch (Exception e) {
                        userLog.getLog("修改变压器", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                        logger.error("修改变压器异常，异常为" + e.toString());
                        flag = 0;
                    }
                }else {
                    flag = 5;
                    userLog.getLog("修改变压器", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
                    logger.error("修改变压器失败，原因是变压器名称长度在500内");
                }
            }else {
                flag =4;
                userLog.getLog("修改变压器", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
                logger.error("修改变压器失败，原因是变压器名非法");
            }
        }else {
            flag = 3;
            userLog.getLog("修改变压器", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
            logger.error("修改变压器失败，原因是变压器名为空");
        }
        return flag;
    }
    /**
     * 根据变压器索引删除变压器
     */
    @RequestMapping(value = "deleteTransByIndex", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult deleteTransByIndex(HttpServletRequest request, String index) throws AccountException {
        HttpResult result = new HttpResult();
        try {
            String message = tfs.deleteTransByIndex(index);
            if (message.equalsIgnoreCase("删除变压器成功！")) {
                result.setCode(200);
                result.setMessage(message);
                result.setBody("success");
                userLog.getLog("删除变压器", "成功",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
                logger.info("删除变压器成功");
            } else {
                result.setCode(500);
                result.setMessage(message);
                userLog.getLog("修改变压器", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
                logger.error("删除变压器失败");
            }
        }catch (Exception e){
            userLog.getLog("修改变压器", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
            logger.error("删除变压器异常，异常为"+e.toString());
            result=PubUtils.assignmentResult(null,500,"删除变压器失败");
        }
        return result;
    }
}
