package com.bcxin.ars.rest.manage;

import com.alibaba.fastjson.JSON;
import com.bcxin.ars.dao.SecurityCompanyPersonDao;
import com.bcxin.ars.dao.SecurityPersonDao;
import com.bcxin.ars.dto.AjaxResult;
import com.bcxin.ars.exception.ArsException;
import com.bcxin.ars.model.*;
import com.bcxin.ars.rest.util.ArsRestUtil;
import com.bcxin.ars.rest.util.manage.ManageResultUtil;
import com.bcxin.ars.service.LoginLogService;
import com.bcxin.ars.service.PoliceService;
import com.bcxin.ars.service.UserService;
import com.bcxin.ars.service.syncDepart.SyncDepartService;
import com.bcxin.ars.service.task.ComContractService;
import com.bcxin.ars.service.util.ConfigUtils;
import com.bcxin.ars.service.util.GXSingleLoginUtil;
import com.bcxin.ars.startup.Startup;
import com.bcxin.ars.timer.person.RepairErrorPhotoForUser;
import com.bcxin.ars.util.Constants;
import com.bcxin.ars.util.StringUtil;
import com.founderinternation.datacenter.datadownload.client.DataDownLoadFactory;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 后台管理
 * @author linqinglin
 * @date 2019/01/11 0011 14:56
 */
@Controller
@RequestMapping("manage")
public class ManageController {

    Logger logger = LoggerFactory.getLogger(ManageController.class);

    @Autowired
    private UserService userService;


    @Autowired
    private ComContractService comContractService;

    @Autowired
    private PoliceService policeService;

    @Autowired
    private ArsRestUtil arsUtil;

    @Autowired
    private ConfigUtils configUtils;

    @Autowired
    private SyncDepartService syncDepartService;

    @Autowired
    private LoginLogService loginLogService;

    @Autowired
    private Startup startup;

    @Autowired
    private RepairErrorPhotoForUser repairErrorPhotoForUser;

    @Autowired
    private GXSingleLoginUtil gxSingleLoginUtil;

    @Autowired
    private SecurityCompanyPersonDao securityCompanyPersonDao;

    @Autowired
    private SecurityPersonDao securityPersonDao;


    @Value("${login-timeout}")
    private int loginTimeout = 10;

    /**
     * 后台管理登录页面
     * @return
     */
    @RequestMapping("login")
    public ModelAndView initLogin() {
        ModelAndView view = new ModelAndView("/manage/login");
        return view;
    }

    /**
     * 后台管理首页
     * @return
     */
    @RequestMapping("index")
    public ModelAndView initIndex() {
        ModelAndView view = new ModelAndView("/manage/index");
        return view;
    }

    /**
     * 操作权限页面
     * @return
     */
    @RequestMapping("auth/init")
    public ModelAndView initauth() {
        ModelAndView view = new ModelAndView("/manage/auth/index");
        return view;
    }
    /**
     * 操作权限页面
     * @return
     */
    @RequestMapping("gxAuth/init")
    public ModelAndView initGXAuth() {
        ModelAndView view = new ModelAndView("/manage/auth/gxIndex");
        return view;
    }

    /**
     *  登录验证
     * @param user
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("user/login")
    public @ResponseBody
    AjaxResult userLogin(User user, HttpServletRequest request) throws Exception {
        AjaxResult result = new AjaxResult();
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
            Subject currentUser = SecurityUtils.getSubject();
            token.setRememberMe(false);
            try {
                currentUser.login(token);
            } catch (AuthenticationException e) {
                logger.error(e.getMessage(), e);
                result.setSuccessful(false);
                result.setMsg("用户名/密码错误");
                return result;
            }
            //判断是否登录成功！
            if(currentUser.isAuthenticated()){
                Session session=currentUser.getSession();
                User dbUser = userService.findByUsername(user.getUsername(),null);
                if(StringUtil.isNotEmpty(dbUser.getIsAdmin()) && dbUser.getIsAdmin().equals("1")){
                    Police police = policeService.findById(dbUser.getOrgid());
                    dbUser.setPolice(police);
                }else{
                    throw new ArsException("请使用超管登录");
                }
                logger.info("当前登录用户是："+dbUser.getUsername());
                dbUser.setSessionId(session.getId().toString());
                arsUtil.setCurrentUser(dbUser,1000*120*loginTimeout);
                request.getSession().setAttribute(Constants.LOGIN_USER, dbUser);
                request.getSession().setAttribute(Constants.SESSION_ID, dbUser.getSessionId());

                Config policeConfig = configUtils.getConfigByKey(Constants.POLICE);
                if (policeConfig != null) {
                    String police = "";
                    if (policeConfig != null && policeConfig.getValue() != null) {
                        police = policeConfig.getValue();
                    }
                    request.getSession().setAttribute("police", police);
                }

                //是否启动流程
                Config isNeedActivityConfig = configUtils.getConfigByKey(Constants.IS_NEED_ACTIVITY);
                String is_need_activitt = "";
                if(isNeedActivityConfig != null&&isNeedActivityConfig.getValue()!=null){
                    is_need_activitt = isNeedActivityConfig.getValue();
                    request.getSession().setAttribute("is_need_activitt", is_need_activitt);
                }

                loginLogService.logIn(request);

                result.setData(dbUser);
                result.setSuccessful(true);
            }else{
                result.setSuccessful(false);
                result.setMsg("用户名/密码错误");
            }
        } catch (UnknownAccountException e) {
            logger.error(e.getMessage(), e);
            result.setSuccessful(false);
            result.setMsg("用户名/密码错误");
        } catch (IncorrectCredentialsException e) {
            logger.error(e.getMessage(), e);
            result.setSuccessful(false);
            result.setMsg("用户名/密码错误");
        } catch (ExcessiveAttemptsException e) {
            logger.error(e.getMessage(), e);
            result.setSuccessful(false);
            result.setMsg("登录失败多次，账户锁定10分钟");
        } catch (AuthenticationException e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }

    /**
     * 登出
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "logout")
    public ModelAndView logOut( HttpServletRequest request) throws Exception {
        try {
            //更新一下下线状态
            loginLogService.logOut(request);
            Subject currentUser = SecurityUtils.getSubject();
            currentUser.logout();
            arsUtil.removeCurrentUser(request);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return initLogin();
    }

    /**
     * 操作权限授权
     * @return
     */
    @RequestMapping("auth")
    @ResponseBody
    public JSONObject auth() {
        try {
            Config config = configUtils.getConfigByKey("approvalflag");
            config.setValue("1");
            configUtils.updateForKey(config);
            return ManageResultUtil.returnSuccessJson("操作成功","authList","", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson("操作失败","authList", "closeCurrent", "");
        }
    }

    /**
     * 重新加载config配置
     * @return
     */
    @RequestMapping("config/reload")
    @ResponseBody
    public JSONObject configReload() {
        try {
            startup.afterPropertiesSet();
            return ManageResultUtil.returnSuccessJson("操作成功","authList","", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson("操作失败","authList", "closeCurrent", "");
        }
    }

    /***
     * 部级接口
     *
     * @return
     */
    @RequestMapping("bjRest")
    public @ResponseBody
    AjaxResult bjRest() {
        AjaxResult result = new AjaxResult();
        try {
            syncDepartService.bjRest();
            result.setSuccessful(true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }

    @RequestMapping("repairErrorPhoto")
    @ResponseBody
    public JSONObject repairErrorPhoto() {
        try {
            repairErrorPhotoForUser.repairErrorPhoto();
            return ManageResultUtil.returnSuccessJson("操作成功","authList","", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson("操作失败","authList", "closeCurrent", "");
        }
    }

    @RequestMapping("contractErrorAtt")
    @ResponseBody
    public JSONObject contractErrorAtt() {
        try {
            comContractService.converImg();
            return ManageResultUtil.returnSuccessJson("操作成功","authList","", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson("操作失败","authList", "closeCurrent", "");
        }
    }

    @RequestMapping("getUserInfo")
    @ResponseBody
    public JSONObject getUserInfo(String username) {
        try {
            return ManageResultUtil.returnSuccessJson(JSON.toJSONString(gxSingleLoginUtil.getUserInfo(username)),"authList","", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson(e.getMessage(),"authList", "closeCurrent", "");
        }
    }

    @RequestMapping("getPoliceOrg")
    @ResponseBody
    public JSONObject getPoliceOrg(String jgdm) {
        try {
            gxSingleLoginUtil.getPoliceOrg(jgdm);
            return ManageResultUtil.returnSuccessJson(gxSingleLoginUtil.getPoliceOrg(jgdm),"authList","", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson(e.getMessage(),"authList", "closeCurrent", "");
        }
    }

    @RequestMapping("getPoliceOrgsByParent")
    @ResponseBody
    public JSONObject getPoliceOrgsByParent(String sjjgbm) {
        try {
            ;
            return ManageResultUtil.returnSuccessJson(gxSingleLoginUtil.getPoliceOrgsByParent(sjjgbm),"authList","", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson(e.getMessage(),"authList", "closeCurrent", "");
        }
    }

    @RequestMapping("getMenuList")
    @ResponseBody
    public JSONObject getMenuList(String zxtqxgw) {
        try {
            ;
            return ManageResultUtil.returnSuccessJson(JSON.toJSONString(gxSingleLoginUtil.getMenuList(zxtqxgw)),"authList","", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson(e.getMessage(),"authList", "closeCurrent", "");
        }
    }

    @RequestMapping("isKeyPerson")
    @ResponseBody
    public JSONObject isKeyPerson() {
        try {
            String idNumber = "412827198709237522";
            SecurityPerson person = securityPersonDao.findByIdCard(idNumber);

            ProblemPerson problemPerson = new ProblemPerson();

            SecurityCompanyPerson securityCompanyPerson = securityCompanyPersonDao.findByPersonId(person.getId());
            problemPerson.setUpdateTime(new Date());
            problemPerson.setActive(true);
            problemPerson.setUpdateBy("systemAuto");
            problemPerson.setIdnumber(idNumber);
            //就职状态
            problemPerson.setIncumbencyStatus(person.getIncumbencyStatus());
            //获取公司信息
            if (securityCompanyPerson != null) {
                if (securityCompanyPerson.getCompany() != null) {

                    //公司名称
                    problemPerson.setCompanyid(securityCompanyPerson.getCompany().getId());
                    //公司主键
                    problemPerson.setCompanyname(securityCompanyPerson.getCompany().getName());
                    //公司信息
                    SecurityCompany company = securityCompanyPerson.getCompany();
                    if(company.getComId().equals("591221865301671937") || (StringUtil.isNotEmpty(company.getParentId()) && company.getParentId().equals("591221865301671937"))){
                        /***
                         * 保总特殊处理
                         */
                        Police police = policeService.findById(1000L);
                        if(police!=null) {
                            problemPerson.setOrgId(Long.valueOf(police.getId()));
                            //监控机构名称
                            problemPerson.setOrgName(police.getOrgname());
                            //所属区域
                            problemPerson.setAreaCode(police.getAreacode());
                        }
                    }else if(company.getId() == 610907743891451L || company.getId()== 610238522001631L){
                        /**
                         * 振远特殊处理
                         */
                        Police police = policeService.findById(2000L);
                        if(police!=null) {
                            problemPerson.setOrgId(Long.valueOf(police.getId()));
                            //监控机构名称
                            problemPerson.setOrgName(police.getOrgname());
                            //所属区域
                            problemPerson.setAreaCode(police.getAreacode());
                        }
                    }else {
                        //监控机构ID
                        if (StringUtil.isNotEmpty(securityCompanyPerson.getCompany().getOrgId())) {
                            problemPerson.setOrgId(Long.valueOf(securityCompanyPerson.getCompany().getOrgId()));
                            //监控机构名称
                            problemPerson.setOrgName(securityCompanyPerson.getCompany().getOrgName());
                            //所属区域
                            problemPerson.setAreaCode(securityCompanyPerson.getCompany().getAreaCode());
                        }
                    }
                }
            }


            try {
                DataDownLoadFactory dataDownLoadFactory = DataDownLoadFactory.getInstance();
                if(dataDownLoadFactory == null){
                    logger.error("DataDownLoadFactory异常");
                }
                //此方法新建一个实例 相当于new
                String ip = "10.236.17.18";
                String port = "8212";
                String methodName = "QueryJzZdry";
                String tableCode = "010112";
                String senderId = "94934D2A-9B28-4A1B-9C0A-A20E767BF3E1";
                String condition = " SFZH ='452625196312134693' and YXX = '1' ";
                String[] fileds = {"XM","ZDRYLBBJ"};
                //String[] fileds = {"*"};
                int totalCount = 1;// 0=< 默认返回所有符合条件的数据，>0 符合条件的totalCount条
                int waittime = 0;//大于等于0为等待wait ms ，等于 0 为不等待
                String result = dataDownLoadFactory.getFromRemote(ip, port, methodName, tableCode, senderId, condition, fileds, totalCount, waittime);
                logger.error("广西【警综-重点人员】返回结果：{}",result);
                long start = System.currentTimeMillis();
                int sum = 0;
                boolean isHadData = false;
                if ("success".equals(result)) {
                    if (dataDownLoadFactory.getResultQueue() != null || !dataDownLoadFactory.isClose()) {
                        //当返回队列不为空或者链接未关闭继续等待接收数据
                        int i=0;
                        while (!dataDownLoadFactory.getResultQueue().isEmpty() || !dataDownLoadFactory.isClose()) {
                            logger.error("循环次数：",i++);
                            Object[] resultstr = dataDownLoadFactory.getResultQueue().poll();
                            //获取返回数据为 Object[2]  rsultstr[0] 为一个map key:value  分别是字段名和字段类型编码（对应类型下面会有介绍）；
                            //map为linkedHashMap 获取keyset为字段set；
                            //resultstr[1] 为List<Object[]> 返回数据包，
                            //object[]对应一个row每个object对应一列，和上面keyset 字段对应
                            if (resultstr == null) {
                                //休息1秒
                                Thread.sleep(1);
                            } else {//获取到数据 TO DO数据处理
                                isHadData = true;
                                sum++;
                                System.out.println("sum:" + sum * 10000);
                                if (resultstr.length == 2 && resultstr[0] != null && resultstr[1] != null) {
                                    List<Object[]> resultList = (List<Object[]>) resultstr[1];
                                }
                            }
                        }
                        logger.error("数据结果队列：" + isHadData);
                        long end = System.currentTimeMillis();
                        logger.error("耗时：" + (double) (end - start) / 1000 + " 秒");
                        dataDownLoadFactory.closeSession();
                        logger.error("耗时：" + (double) (System.currentTimeMillis() - start) / 1000 + " 秒");
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                logger.error(e.getMessage(), e);
                throw new ArsException("广西【警综-重点人员】调用异常！！");
            }
            return ManageResultUtil.returnSuccessJson(null,"authList","", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ManageResultUtil.returnFailedJson(e.getMessage(),"authList", "closeCurrent", "");
        }
    }
}
