package com.pqs9900.controller.configuration;

import com.njcn.enums.LogTypeEnum;
import com.njcn.mapper.configuration.DicDataMapper;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.commons.RedisDB;
import com.njcn.pojo.configuration.DicData;
import com.njcn.pojo.configuration.DicType;
import com.njcn.service.configuration.DicDataService;
import com.njcn.service.configuration.DicDataTypeService;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.PubUtils;
import com.njcn.utils.SerializeUtil;
import com.njcn.utils.UserUtil;
import com.njcn.utils.XssFilterUtil;
import com.njcn.utils.redis.JedisManager;

import net.sf.json.JSONArray;

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.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/dic")
public class DicDataTypeController {
    @Resource
    DicDataTypeService ddts;
    @Resource
    DicDataService dds;
    @Resource
    UserLogDetailService userLog;
    @Autowired
    JedisManager jedisManager;

    // 日志记录
    private static final Logger logger = LoggerFactory.getLogger(DicDataTypeController.class);

    /**
     * 新增数据字典
     */
    @RequestMapping(value = "saveData", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult saveData(HttpServletRequest request, String dicName, String dicType, int leave, int triphase) throws AccountException {
        HttpResult result = new HttpResult();
        //后台Xss攻击处理、包括html/js/sql
        dicName = XssFilterUtil.dealString(dicName);
        dicType = XssFilterUtil.dealString(dicType);
        try {
            String message = dds.saveData(dicName, dicType, leave, triphase);
            if (message.equalsIgnoreCase("新增字典成功！")) {
                result.setCode(200);
                result.setMessage(message);
                result.setBody("success");
                userLog.getLog("新增数据字典", "成功",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
                logger.info("新增数据字典成功");
            } else if(message.equalsIgnoreCase("字典名称不可为空")){
                result.setCode(501);
                result.setMessage(message);
                userLog.getLog("新增数据字典", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
                logger.error("新增数据字典失败");
            } else if(message.equalsIgnoreCase("字典名称包括中文、数字、字母、括号以及点号")){
                result.setCode(502);
                result.setMessage(message);
                userLog.getLog("新增数据字典", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
                logger.error("新增数据字典失败");
            } 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);
            result = PubUtils.assignmentResult(null, 500, "新增数据字典失败");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "setArea", method = RequestMethod.POST)
    public List<DicData> setArea() {
        List<DicData> list = new ArrayList<>();
        try {
            list = dds.setArea();
        } catch (Exception e) {
            logger.error("查询区域信息异常，异常是" + e.toString());
        }
        return list;
    }

    // 查询所有数据类型
    @ResponseBody
    @RequestMapping(value = "All", method = RequestMethod.POST)
    public List<DicType> selectAll(@Param(value = "typeId") String typeId) {
        List<DicType> list = new ArrayList<>();
        try {
            list = ddts.All(typeId);
        } catch (Exception e) {
            logger.error("查询数据类型信息异常，异常是" + e.toString());
        }
        return list;
    }

    // 查询所有数据类型
    @ResponseBody
    @RequestMapping(value = "selectAll", method = RequestMethod.POST)
    public List<DicType> selectAll() {
        List<DicType> list = new ArrayList<>();
        try {
            list = ddts.selectAll();
        } catch (Exception e) {
            logger.error("查询数据类型信息异常，异常是" + e.toString());
        }
        return list;
    }

    // 查询所有数据类型
    @ResponseBody
    @RequestMapping(value = "selectTypeName", method = RequestMethod.POST)
    public DicType selectTypeName(@Param(value = "typeId") String typeId) {
        DicType list = new DicType();
        try {
            list = ddts.selectTypeName(typeId);
        } catch (Exception e) {
            logger.error("查询数据类型异常，异常是" + e.toString());
        }
        return list;
    }

    // 查询所有
    @ResponseBody
    @RequestMapping(value = "seleAll", method = RequestMethod.POST)
    public HttpResult seleAll(HttpServletRequest request,String name) throws AccountException {
        HttpResult result = new HttpResult();
        try {
            List<List> deviceList = dds.seleAll(name);
            if (deviceList.isEmpty()) {
                result.setCode(500);
                userLog.getLog("查询数据字典", "成功",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),0);
                result.setMessage("没有配置信息");
            } else {
                result.setCode(200);
                result.setMessage("获取配置信息成功");
                userLog.getLog("查询数据字典", "成功",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),0);
                result.setBody(deviceList);
            }
        } catch (Exception e) {
            logger.error("查询所有数据字典异常，异常是" + e.toString());
            userLog.getLog("查询数据字典", "成功",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),0);
            result = PubUtils.assignmentResult(null, 500, "没有配置信息");
        }
        return result;
    }

    // 根据类型ID查询所有字典数据详情
    @ResponseBody
    @RequestMapping(value = "selAll", method = RequestMethod.POST)
    public HttpResult selAll(HttpServletRequest request,String typeId) throws AccountException {
        HttpResult result = new HttpResult();
        List<List> deviceList = new ArrayList<>();
        try {
            if (typeId.equals("0")) {
                deviceList = dds.seleAll("");
            } else {
                deviceList = dds.selAll(typeId);
            }
            if (deviceList.isEmpty()) {
                result.setCode(500);
                userLog.getLog("查询数据字典", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),0);
                result.setMessage("没有配置信息");
            } else {
                result.setCode(200);
                userLog.getLog("查询数据字典", "成功",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),0);
                result.setMessage("获取配置信息成功");
                result.setBody(deviceList);
            }
        } catch (Exception e) {
            userLog.getLog("查询数据字典", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),0);
            logger.error("查询所有数据字典异常，异常是" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "没有配置信息");
        }
        return result;
    }

    //根據ID查詢所有
    @RequestMapping(value = "/selAllId", method = RequestMethod.POST)
    @ResponseBody
    public List<DicData> selAllId(String typeId) {
        List<DicData> dicData = new ArrayList<>();
        try {
            dicData = dds.selAllId(typeId);
        } catch (Exception e) {
            logger.error("查询数据字典异常，异常是" + e.toString());
        }
        return dicData;
    }

    //根據ID查詢所有
    @RequestMapping(value = "/selAllType", method = RequestMethod.POST)
    @ResponseBody
    public List<DicData> selAllType(String typeId) {
        List<DicData> dicData = new ArrayList<>();
        JSONArray jsonArray = JSONArray.fromObject(typeId);
        String types = (String) jsonArray.getJSONObject(0).get("type");
        String[] pointid = types.split(",");
        try {
        	List<String> tmp = new ArrayList<>();
        	if(pointid.length>0){
        		for(String type : pointid){
            		tmp.add(type);
        		}
        	}
            dicData = dds.selAllType(tmp);
        } catch (Exception e) {
            logger.error("查询数据字典异常，异常是" + e.toString());
        }
        return dicData;
    }
    
    //根據ID查詢所有
    @RequestMapping(value = "/selectId", method = RequestMethod.POST)
    @ResponseBody
    public DicData selectId(String dicIndex) {
        DicData dicData = new DicData();
        try {
            dicData = dds.selectId(dicIndex);
        } catch (Exception e) {
            logger.error("查询所有数据字典异常，异常是" + e.toString());
        }
        return dds.selectId(dicIndex);
    }

    /**
     * 根据字典索引删除字典
     */
    @RequestMapping(value = "deleteDataByIndex", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult deleteDataByIndex(HttpServletRequest request, String index) throws AccountException {
        HttpResult result = new HttpResult();
        try {
            String ip = PubUtils.getIpAddr(request);
            String username = TokenManager.getToken().getLoginName();

            byte[] value = jedisManager.getValueByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip));
            String key = SerializeUtil.deserialize(value, String.class);
            if(key.equals("success")){
                String message = dds.deleteDataByIndex(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("删除字典失败");
                }
            }else{
                result.setCode(500);
                result.setMessage("删除字典失败,密码验证失败!");
                userLog.getLog("删除数据字典,密码验证失败!", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
                logger.error("删除字典失败");
            }
        } catch (Exception e) {
            logger.error("删除数据字典异常，异常是" + e.toString());
            userLog.getLog("删除数据字典", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
            result = PubUtils.assignmentResult(null, 500, "删除数据字典失败");
        }
        return result;
    }

    // 修改字典
    @ResponseBody
    @RequestMapping(value = "/updateData", method = RequestMethod.POST)
    public int update(HttpServletRequest request,@Param(value = "dicName") String dicName, @Param(value = "updateTime") Date updateTime, @Param(value = "dicIndex") String dicIndex, @Param(value = "dicType") String dicType, @Param(value = "dicLeave") Integer dicLeave) throws AccountException {
        int flag = 1;
        //后台Xss攻击处理、包括html/js/sql
        dicName = XssFilterUtil.dealString(dicName);
        dicType = XssFilterUtil.dealString(dicType);
        if(!StringUtils.isBlank(dicName)) {
            if(PubUtils.patternDic(dicName)) {
                try {
                    List<DicData> list = dds.selectName(dicIndex, dicType);
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).getDicName().equals(dicName)) {
                            flag = 0;
                        }
                    }
                    if (flag != 0) {
                        DicData dic = new DicData();
                        dic.setDicIndex(dicIndex);
                        dic.setDicName(dicName);
                        updateTime = new Date();
                        DicType dt = new DicType();
                        dt.setDicTypeIndex(dicType);
                        dic.setDicType(dt.getDicTypeIndex());
                        dic.setUpdateTime(updateTime);
                        dic.setDicLeave(dicLeave);
                        int state = 1;
                        dic.setState(state);
                        dds.updateData(dic);
                        flag = 1;
                        userLog.getLog("修改数据字典", "成功",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
                        logger.info("修改数据字典成功");
                    } else {
                        flag = 0;
                        userLog.getLog("修改数据字典", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
                        logger.error("修改数据字典失败，原因是该数据字典名称已存在");
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    e.getMessage();
                }
            }else {
                userLog.getLog("修改数据字典", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
                logger.error("修改数据字典失败，原因是数据字典名称不匹配");
                flag = 3;
            }
        }else {
            userLog.getLog("修改数据字典", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
            logger.error("修改数据字典失败，原因是数据字典名称为空");
            flag = 2;
        }

        return flag;
    }

    @ResponseBody
    @RequestMapping(value = "getMangType", method = RequestMethod.POST)
    public List<DicData> getMangType() {
        List<DicData> dicData = new ArrayList<>();
        try {
            dicData = dds.getMangType();
        } catch (Exception e) {
            logger.error("查询所有数据类型异常，异常是" + e.toString());
        }
        return dicData;
    }

    @ResponseBody
    @RequestMapping(value = "getDicName", method = RequestMethod.POST)
    public String getDicName(String devtype) {
        String dicName="";
        try {
            dicName = dds.getDicName(devtype);
        } catch (Exception e) {
            logger.error("查询所有数据类型异常，异常是" + e.toString());
        }
        return dicName;
    }

    @ResponseBody
    @RequestMapping(value = "getType", method = RequestMethod.POST)
    public List<DicData> getType() {
        List<DicData> dicData = new ArrayList<>();
        try {
            dicData = dds.getType();
        } catch (Exception e) {
            logger.error("查询所有数据类型异常，异常是" + e.toString());
        }
        return dicData;
    }

    @ResponseBody
    @RequestMapping(value = "getSystemType", method = RequestMethod.POST)
    public List<DicData> getSystemType() {
        List<DicData> dicData = new ArrayList<>();
        try {
            dicData = dds.getSystemType();
        } catch (Exception e) {
            logger.error("查询所有数据类型异常，异常是" + e.toString());
        }
        return dicData;
    }
}

