package com.pqs9900.controller.configuration;


import com.njcn.enums.DicDataTypeEnum;
import com.njcn.enums.LogTypeEnum;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.commons.RedisDB;
import com.njcn.pojo.configuration.DicType;
import com.njcn.pojo.configuration.DicTypeTree;
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 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 javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/type")
public class DicTypeController {
    @Resource
    DicDataTypeService ddts;
    @Autowired
    UserUtil uu;
    @Resource
    UserLogDetailService userLog;
    @Autowired
    JedisManager jedisManager;
    // 日志记录
    private static final Logger logger = LoggerFactory.getLogger(DicTypeController.class);

    //根据Id查询所有
    @RequestMapping(value = "selType", method = RequestMethod.POST)
    @ResponseBody
    public List<DicType> selType(@Param(value = "dicTypeIndex") String dicTypeIndex) {
        List<DicType> dt = new ArrayList<>();
        try {
            dt = ddts.selTypeId(dicTypeIndex);
        } catch (Exception e) {
            logger.error("查询所有数据字典异常，异常是" + e.toString());
        }
        return dt;
    }

    /**
     * 资源列表树
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "getTree", method = RequestMethod.POST)
    @ResponseBody
    public List<DicTypeTree> getTree(HttpServletRequest request, HttpSession session) {
        List<DicTypeTree> result = new ArrayList();
        try {
            result = ddts.getTreeType();
        } catch (Exception e) {
            logger.error("查询所有数据字典异常，异常是" + e.toString());
        }

        return result;
    }

    @ResponseBody
    @RequestMapping(value = "getLog", method = RequestMethod.POST)
    public List<DicType> getLog() {
        List<DicType> dicTypes = new ArrayList<>();
        List<String> list = new ArrayList<>();
        try {
            list.add(DicDataTypeEnum.serviceEnum.getName());
            list.add(DicDataTypeEnum.systemEnum.getName());
            dicTypes = ddts.getLog(list);
        } catch (Exception e) {
            logger.error("查询日志异常，异常是" + e.toString());
        }
        return dicTypes;
    }

    /**
     * 新增通用字典
     */
    @RequestMapping(value = "saveType", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult saveType(HttpServletRequest request, String dicTypeName, String dicTypeDescription) {
        HttpResult result = new HttpResult();
        //后台Xss攻击处理、包括html/js/sql
        dicTypeName = XssFilterUtil.dealString(dicTypeName);
        dicTypeDescription = XssFilterUtil.dealString(dicTypeDescription);
        try {
            if(!StringUtils.isBlank(dicTypeName)) {
                if(PubUtils.patternTyPe(dicTypeName)) {
                    if(PubUtils.patternDes500(dicTypeDescription)) {
                        String message = ddts.saveType(dicTypeName, dicTypeDescription);
                        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 = PubUtils.assignmentResult(null, 501, message);
                            userLog.getLog("新增字典类型", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                            logger.error("新增字典类型失败");
                        } else if (message.equalsIgnoreCase("字典类型由中文组成")) {
                            userLog.getLog("新增字典类型", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                            result = PubUtils.assignmentResult(null, 502, message);
                            logger.error("新增字典类型失败");
                        } else {
                            result.setCode(500);
                            result.setMessage(message);
                            userLog.getLog("新增字典类型", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                            logger.error("新增字典类型失败");
                        }
                    }else {
                        result.setCode(500);
                        result.setMessage("描述长度为500内");
                        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("新增字典类型失败");
                }
            }else {
                result.setCode(500);
                result.setMessage("字典类型为空");
                userLog.getLog("新增字典类型", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                logger.error("新增字典类型失败");
            }
        } catch (Exception e) {
            logger.error("新增数据字典类型异常，异常是" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "新增字典类型失败");
        }
        return result;
    }

    //删除
    @ResponseBody
    @RequestMapping("/delete")
    public int delete(HttpServletRequest request,@Param(value = "dicTypeIndex") String dicTypeIndex) throws AccountException {
        DicType dt = new DicType();
        int flag = 0;
        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")){
                dt.setDicTypeIndex(dicTypeIndex);
                flag = ddts.deleteType(dt);
                userLog.getLog("删除字典类型", "成功",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
                logger.info("删除字典类型成功");
            }else{
                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("删除字典失败");
        }

        return flag;

    }

    // 修改字典
    @ResponseBody
    @RequestMapping(value = "/updateType", method = RequestMethod.POST)
    public int updateType(HttpServletRequest request,@Param(value = "dicTypeName") String dicTypeName, @Param(value = "updateTime") Date updateTime, @Param(value = "dicTypeIndex") String dicTypeIndex, @Param(value = "dicTypeDiscribe") String dicTypeDiscribe) throws AccountException {
        //后台Xss攻击处理、包括html/js/sql
        dicTypeName = XssFilterUtil.dealString(dicTypeName);
        dicTypeDiscribe = XssFilterUtil.dealString(dicTypeDiscribe);
        DicType dt = new DicType();
        int flag = 1;
        if(!StringUtils.isBlank(dicTypeName)) {
            if(PubUtils.patternTyPe(dicTypeName)) {
                try {
                    List<DicType> list = ddts.selectName(dicTypeIndex);
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).getDicTypeName().equals(dicTypeName)) {
                            flag = 0;
                            logger.error("修改字典类型失败，原因是该字典名称已存在");
                            userLog.getLog("修改字典类型", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
                        }
                    }
                    if (flag != 0) {
                        dt.setDicTypeIndex(dicTypeIndex);
                        dt.setDicTypeName(dicTypeName);
                        updateTime = new Date();
                        dt.setUpdateTime(updateTime);
                        dt.setDicTypeDiscribe(dicTypeDiscribe);
                        ddts.updateType(dt);
                        userLog.getLog("修改字典类型", "成功",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
                        logger.info("修改字典类型成功");
                    }
                } catch (Exception e) {
                    logger.error("修改字典类型异常，异常是"+e.getMessage());
                    flag = 0;
                }
            }else {
                flag = 3;
                userLog.getLog("修改字典类型", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
                logger.error("修改字典类型失败，原因是字典名称非法");
            }
        }else{
            flag = 2;
            userLog.getLog("修改字典类型", "失败",PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
            logger.error("修改字典类型失败，原因是字典名称为空");
        }

        return flag;
    }
}

