package com.pqs9900.controller.user;

import com.njcn.enums.LogTypeEnum;
import com.njcn.mapper.configuration.GDInforMapper;
import com.njcn.mapper.configuration.LineMapper;
import com.njcn.mapper.user.DeptsMapper;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.commons.RedisDB;
import com.njcn.pojo.configuration.GDInformation;
import com.njcn.pojo.configuration.Line;
import com.njcn.pojo.user.*;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.service.user.DeptsLineService;
import com.njcn.service.user.DeptsLineTreeService;
import com.njcn.service.user.DeptsService;
import com.njcn.service.user.UserService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.PubUtils;
import com.njcn.utils.SerializeUtil;
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.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
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 = "/depts")
public class DeptsController {

    @Resource
    DeptsService ds;
    @Resource
    DeptsMapper dm;

    // 日志记录
    private static final Logger logger = LoggerFactory.getLogger(DeptsController.class);
    @Resource
    private UserService us;

    @Resource
    private UserLogDetailService userLog;

    @Autowired
    private DeptsLineService deptsLineService;

    @Autowired
    private LineMapper lineMapper;

    @Autowired
    private GDInforMapper gdInforMapper;

    @Autowired
    private DeptsLineTreeService deptsLineTreeService;

    @Autowired
    JedisManager jedisManager;

    /**
     * 查询数据用以新增用户如：部门、角色组
     */
    @ResponseBody
    @PostMapping(value = "selectAll")
    public HttpResult selectAll() {
        HttpResult result;
        DeptsAndRoleGP deptsAndRoleGP = new DeptsAndRoleGP();
        try {
            List<Depts> list = dm.selectDeptAll();
            List<Role> roleGroups = us.selectAll();
            if (CollectionUtils.isEmpty(list)) {
                deptsAndRoleGP.setDeptsList(new ArrayList<>());
            } else {
                deptsAndRoleGP.setDeptsList(list);
            }
            if (CollectionUtils.isEmpty(roleGroups)) {
                deptsAndRoleGP.setRoleGroups(new ArrayList<>());
            } else {
                deptsAndRoleGP.setRoleGroups(roleGroups);
            }
            deptsAndRoleGP.setReferralCode(PubUtils.referralCode().toUpperCase());
            result = PubUtils.assignmentResult(deptsAndRoleGP, 200, "获取数据成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 500, "获取数据失败");
        }
        return result;
    }

    /**
     * 查询数据
     */
    @ResponseBody
    @PostMapping(value = "selectAllDept")
    public HttpResult selectAllDept(HttpServletRequest request) throws AccountException {
        HttpResult result = new HttpResult();
        try {
            List<Depts> list = ds.selectAll();
            if (!list.isEmpty()) {
                userLog.getLog("查询部门", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
                result = PubUtils.assignmentResult(list, 200, "获取数据成功");
            }
        } catch (Exception e) {
            userLog.getLog("查询部门", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
            logger.error("获取异常，异常为" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "获取部门失败");
        }
        return result;
    }

    /**
     * 查询数据
     */
    @ResponseBody
    @PostMapping(value = "selectDept")
    public HttpResult selectDept(HttpServletRequest request) throws AccountException {
        HttpResult result = new HttpResult();
        try {
            List<Depts> list = ds.selectDeptAll();
            if (!list.isEmpty()) {
                userLog.getLog("查询部门", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
                result = PubUtils.assignmentResult(list, 200, "获取数据成功");
            }
        } 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 = "getDepts", method = RequestMethod.POST)
    public HttpResult getDepts(HttpServletRequest request) throws AccountException {
        HttpResult result = new HttpResult();
        try {
            List<List> deviceList = ds.getDepts();
            if (deviceList.isEmpty()) {
                result.setCode(500);
                result.setMessage("没有配置信息");
                userLog.getLog("查询部门", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
                logger.error("获取部门信息失败");
            } else {
                result.setCode(200);
                result.setMessage("获取配置信息成功");
                result.setBody(deviceList);
                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;
    }

    /**
     * 根据选择的部门查询
     */
    @RequestMapping(value = "getD", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getD(HttpServletRequest request, String node) throws AccountException {
        HttpResult result = new HttpResult();
        List<List> deviceList;
        if (node.equals("0")) {
            try {
                deviceList = ds.getDepts();
                if (deviceList.isEmpty()) {
                    result.setCode(500);
                    result.setMessage("没有配置信息");
                    userLog.getLog("查询部门", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
                    logger.error("获取部门信息失败");
                } else {
                    result.setCode(200);
                    userLog.getLog("查询部门", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
                    result.setMessage("获取配置信息成功");
                    result.setBody(deviceList);
                    logger.info("获取部门信息成功");
                }
            } catch (Exception e) {
                userLog.getLog("查询部门", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
                result = PubUtils.assignmentResult(null, 500, "获取数据失败");
            }
        } else {
            try {
                deviceList = ds.getD(node);
                if (deviceList.isEmpty()) {
                    result.setCode(500);
                    result.setMessage("没有配置信息");
                    userLog.getLog("查询部门", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
                    logger.error("获取部门信息失败");
                } else {
                    result.setCode(200);
                    result.setMessage("获取配置信息成功");
                    result.setBody(deviceList);
                    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;
    }

    /**
     * 新增部门
     */
    @RequestMapping(value = "saveDepts", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult saveDepts(HttpServletRequest request, String deptsName, String deptsDescription, String parentNode, String area, int customDept) throws AccountException {
        HttpResult result = new HttpResult();
        //后台Xss攻击处理、包括html/js/sql
        deptsName = XssFilterUtil.dealString(deptsName);
        deptsDescription = XssFilterUtil.dealString(deptsDescription);
        area = XssFilterUtil.dealString(area);
        if (!StringUtils.isBlank(deptsName)) {
            if (!StringUtils.isBlank(area)) {
                if (PubUtils.patternDepts(deptsName)) {
                    if (PubUtils.patternDes200(deptsDescription)) {
                        if (StringUtils.isBlank(deptsDescription)) {
                            deptsDescription = "暂无描述";
                        }
                        try {
                            String message = ds.saveDepts(deptsName, deptsDescription, parentNode, area, customDept);
                            if (message.equalsIgnoreCase("新增部门成功！")) {
                                result.setCode(200);
                                result.setMessage(message);
                                result.setBody("success");
                                logger.info("新增部门成功");
                                userLog.getLog("新增部门", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                            } else {
                                result.setCode(500);
                                result.setMessage(message);
                                logger.error("新增部门失败");
                                userLog.getLog("新增部门", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                            }
                        } catch (Exception e) {
                            logger.error("新增部门异常，异常为" + e.toString());
                            userLog.getLog("新增部门", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                            result = PubUtils.assignmentResult(null, 500, "新增部门失败");
                        }
                    } else {
                        result.setCode(500);
                        result.setMessage("描述长度在200内");
                        logger.error("新增部门失败");
                        userLog.getLog("新增部门", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                    }
                } else {
                    result.setCode(500);
                    result.setMessage("部门名称非法，只可输入1-20位中文");
                    logger.error("新增部门失败");
                    userLog.getLog("新增部门", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                }
            } else {
                result.setCode(500);
                result.setMessage("区域为空，请到数据字典处新增");
                logger.error("新增部门失败");
                userLog.getLog("新增部门", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        } else {
            result.setCode(500);
            result.setMessage("部门名称为空");
            logger.error("新增部门失败");
            userLog.getLog("新增部门", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
        }
        return result;
    }

    /**
     * 根据部门索引删除部门
     */
    @RequestMapping(value = "deleteDeptsByIndex", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult deleteDeptsByIndex(HttpServletRequest request, String index) {
        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 = ds.deleteDeptsByIndex(index);
                if (message.equalsIgnoreCase("删除部门成功！")) {
                    result.setCode(200);
                    result.setMessage(message);
                    result.setBody("success");
                    logger.info("删除部门成功");
                    userLog.getLog("删除部门", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } else if (message.equalsIgnoreCase("该部门为省级部门，不可删除")) {
                    result = null;
                } else {
                    result.setCode(500);
                    result.setMessage(message);
                    logger.error("删除部门失败");
                    userLog.getLog("删除部门", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                }
            } else {
                result.setCode(500);
                result.setMessage("删除部门失败,密码验证失败!");
                logger.error("删除部门失败,密码验证失败!");
                userLog.getLog("删除部门", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            }
        } catch (Exception e) {
            logger.error("删除部门异常，异常为" + e.toString());
            userLog.getLog("新增部门", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            result = PubUtils.assignmentResult(null, 500, "删除部门失败");
        }
        return result;
    }

    /**
     * 根据部门索引查询所有
     */
    @RequestMapping(value = "getAll", method = RequestMethod.POST)
    @ResponseBody
    public Depts getAll(String deptsIndex) {

        return ds.getAll(deptsIndex);
    }

    /**
     * 根据部门索引查询所有
     */
    @RequestMapping(value = "getAllArea", method = RequestMethod.POST)
    @ResponseBody
    public Depts getAllArea(String deptsIndex) {

        return ds.getAllArea(deptsIndex);
    }

    //父节点
    @RequestMapping(value = "selectName", method = RequestMethod.POST)
    @ResponseBody
    public Depts selectName(String parentNode) {
        Depts list = new Depts();
        try {
            list = ds.selectName(parentNode);
        } catch (Exception e) {
            logger.error("查询父节点异常，异常是" + e.toString());
        }
        return list;
    }

    //父节点
    @RequestMapping(value = "selName", method = RequestMethod.POST)
    @ResponseBody
    public List<Depts> selName(String deptsIndex) {
        List<Depts> list = new ArrayList<>();
        try {
            list = ds.selName(deptsIndex);
        } catch (Exception e) {
            logger.error("查询父节点异常，异常是" + e.toString());
        }
        return list;
    }

    //父节点
    @RequestMapping(value = "selparentnode", method = RequestMethod.POST)
    @ResponseBody
    public List<Depts> selparentnode(String deptsIndex) {
        List<Depts> list = new ArrayList<>();
        try {
            list = ds.selparentnode(deptsIndex);
        } catch (Exception e) {
            logger.error("查询父节点异常，异常是" + e.toString());
        }
        return list;
    }

    /**
     * 修改部门
     */
    @RequestMapping(value = "updateDepts", method = RequestMethod.POST)
    @ResponseBody
    public int updateDepts(HttpServletRequest request, String deptsIndex, String deptsName, String deptsDescription, Integer customDeptType, String parentNode, String area) throws AccountException {
        int flag = 1;
        //后台Xss攻击处理、包括html/js/sql
        deptsName = XssFilterUtil.dealString(deptsName);
        deptsDescription = XssFilterUtil.dealString(deptsDescription);
        area = XssFilterUtil.dealString(area);
        try {
            List<Depts> list = dm.selName(deptsIndex);
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getDeptsName().equals(deptsName)) {
                    flag = 0;
                }
            }
            if (flag != 0) {
                Depts depts = new Depts();
                depts.setDeptsIndex(deptsIndex);
                depts.setDeptsName(deptsName);
                depts.setParentNodeId(parentNode);
                depts.setCustomDept(Integer.valueOf(customDeptType));
                depts.setUpdateTime(new Date());
                depts.setArea(area);
                depts.setDeptsDescription(deptsDescription);
                ds.updateDepts(depts);
                flag = 1;
                logger.info("修改部门成功");
                userLog.getLog("修改部门", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            } else {
                logger.error("修改部门失败，原因是部门名称已存在");
                userLog.getLog("修改部门", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                flag = 0;
            }
        } catch (Exception e) {
            // TODO: handle exception
            userLog.getLog("修改部门", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
            logger.error("修改部门异常，异常为" + e.toString());
            flag = 0;
        }


        return flag;
    }

    /***
     * 查询当前已绑的供电公司和监测点
     */
    @RequestMapping(value = "getBind", method = RequestMethod.POST)
    @ResponseBody
    public List<DeptsLine> getBind(HttpServletRequest request, @Param("deptsIndex") String deptsIndex) {
        List<DeptsLine> deptsLines = new ArrayList<>();
        try {
            deptsLines = deptsLineService.getBind(deptsIndex);
            List<Line> lines = new ArrayList<>();
            List<GDInformation> gdInformations = new ArrayList<>();
            if (!deptsLines.isEmpty()) {
                for (int i = 0; i < deptsLines.size(); i++) {
                    Line line = new Line();
                    line.setLineIndex(deptsLines.get(i).getLineIndex());
                    lines = lineMapper.select(line);
                    line = lineMapper.selectOne(line);
                    //监测点
                    deptsLines.get(i).setLines(lines);
                    //供电公司
                    GDInformation gdInformation = new GDInformation();
                    gdInformation.setGdIndex(line.getGdIndex());
                    gdInformations = gdInforMapper.select(gdInformation);
                    deptsLines.get(i).setGdi(gdInformations);
                }
                return deptsLines;
            } else {
                deptsLines = null;
            }
        } catch (Exception e) {
            deptsLines = null;
            logger.error("查询绑定的供电公司及监测点异常，异常为" + e.toString());
            return deptsLines;
        }
        return deptsLines;
    }

    /**
     * 部门绑定监测点树
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "deptsLinetree", method = RequestMethod.POST)
    @ResponseBody
    public List<DeptslineTree> deptsLinetree(HttpServletRequest request, HttpSession session, String area, String deptsIndex, Integer customDept, Integer isother) {
        if (session.getAttribute("line_index") != null || session.getAttribute("line_index") != "") {
            session.removeAttribute("line_index");
        }
        List<DeptslineTree> result = new ArrayList();
        try {
            //判断是否为自定义部门
            if (customDept == 1 ||customDept == 2) {
                result = deptsLineTreeService.getDeptsLineTreeNo(deptsIndex, area);
            } else {
                //判断是未绑定的还是其他绑定的
                if (isother == 0) {
                    //非自定义未绑定的
                    result = deptsLineTreeService.getDeptsLineTreeNoF(deptsIndex, area);
                } else {
                    //非自定义其他绑定的
                    result = deptsLineTreeService.getDeptsLineTreeOther(deptsIndex, area);
                }
            }
        } catch (Exception e) {
            logger.error("获取监测点树异常，异常为" + e.toString());
        }
        return result;
    }

    /**
     * 部门绑定监测点树
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "getmyselfTree", method = RequestMethod.POST)
    @ResponseBody
    public List<DeptslineTree> getmyselfTree(HttpServletRequest request, HttpSession session, String area, String deptsIndex) {
        if (session.getAttribute("line_index") != null || session.getAttribute("line_index") != "") {
            session.removeAttribute("line_index");
        }
        List<DeptslineTree> result = new ArrayList();
        try {
            result = deptsLineTreeService.getDeptsLineTreeMyself(deptsIndex, area);
        } catch (Exception e) {
            logger.error("获取监测点树异常，异常为" + e.toString());
        }
        return result;
    }

    @RequestMapping(value = "selectAreaDept", method = RequestMethod.POST)
    @ResponseBody
    public Depts selectAreaDept(String deptsIndex) {
        Depts depts = null;
        try {
            depts = ds.selectAreaDept(deptsIndex);
        } catch (Exception e) {
            logger.error("获取监测点树异常，异常为" + e.toString());
            return depts;
        }
        return depts;
    }

}
