package org.ccpit.business.registerManage;

import org.apache.commons.lang.StringUtils;
import org.ccpit.base.controller.BaseController;
import org.ccpit.base.controller.ValidateCodeController;
import org.ccpit.base.metadataManage.Metadata;
import org.ccpit.base.metadataManage.MetadataService;
import org.ccpit.base.user.UserService;
import org.ccpit.base.utils.EmailBody;
import org.ccpit.base.utils.MailSender;
import org.ccpit.base.utils.PasswordHash;
import org.ccpit.base.utils.mailUtil.Mail;
import org.ccpit.base.utils.mailUtil.MailUtil;
import org.ccpit.business.phase.Phase;
import org.ccpit.business.phase.PhaseService;
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 org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Date: 2015年11月12日 11:30
 *
 * @author 孙其鹏
 * @version 1.0
 */
@RestController
@RequestMapping("/training")
public class IndexController extends BaseController {
    @Autowired
    private RegisterService registerService;
    @Autowired
    private MetadataService metadataService;
    @Autowired
    private PhaseService phaseService;
    @Autowired
    private SubjectInfoService subjectInfoService;

    private Map<String, Object> check() {
        if (getActivePhase() == null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("info", "注册页面暂未开放");
            return map;
        }
        return null;
    }

    /**
     * 获取活动的期数
     *
     * @return
     */
    private Phase getActivePhase() {
        return phaseService.getActivePhase();
    }

    /**
     * 跳转去登录页
     *
     * @return
     */
    @RequestMapping(value = "/loginp", method = RequestMethod.GET)
    public ModelAndView loginPage() {
        if (check() != null) {
            ModelAndView mv = new ModelAndView("front/error");
            return mv;
        }
        return new ModelAndView("front/login");
    }
//    /**
//     * 跳转去登录页
//     * @return
//     */
//    @RequestMapping(value="/loginp2",method=RequestMethod.GET)
//    public ModelAndView loginPage2(){
//        if (check()!=null){
//            ModelAndView mv = new ModelAndView("front/error");
//            return mv;
//        }
//        return new ModelAndView("front/login2");
//    }

    /**
     * 跳转去注册页
     *
     * @return
     */
    @RequestMapping(value = "/regp", method = RequestMethod.GET)
    public ModelAndView regPage() {
        ModelAndView mv = new ModelAndView("front/reg");
        List<Metadata> cityType = metadataService.getMetadatasByType2("cityType");
        List<Metadata> encityType = metadataService.getMetadatasByType2("encityType");
        List<Metadata> status = metadataService.getMetadatasByType2("status");
        List<Metadata> invoiceType = metadataService.getMetadatasByType2("invoiceType");
        List<Metadata> subject = metadataService.getMetadatasByType2("subject");
        List<Metadata> gender = metadataService.getMetadatasByType2("gender");
        List<Metadata> engender = metadataService.getMetadatasByType2("engender");
        mv.addObject("cityType", cityType);
        mv.addObject("encityType", encityType);
        mv.addObject("status", status);
        mv.addObject("invoiceType", invoiceType);
        mv.addObject("subject", subject);
        mv.addObject("gender", gender);
        mv.addObject("engender", engender);
        return mv;
    }
    /**
     * 跳转去注册页
     * @return
     */
//    @RequestMapping(value="/regp2",method=RequestMethod.GET)
//    public ModelAndView regPage2(){
//        if (check()!=null){
//            ModelAndView mv = new ModelAndView("front/error");
//            return mv;
//        }
//        ModelAndView mv = new ModelAndView("front/reg2");
//        List<Metadata> encityType = metadataService.getMetadatasByType2("encityType");
//        List<Metadata> subject = metadataService.getMetadatasByType2("subject2");
//        List<Metadata> engender = metadataService.getMetadatasByType2("engender");
//        List<Metadata> invoiceType = metadataService.getMetadatasByType2("invoiceType");
//        mv.addObject("encityType",encityType);
//        mv.addObject("invoiceType",invoiceType);
//        mv.addObject("subject",subject);
//        mv.addObject("engender",engender);
//        return mv;
//    }

    /**
     * 跳转去个人信息页
     *
     * @return
     */
    @RequestMapping("/infop")
    public ModelAndView infoPage(HttpServletRequest request) {
        if (check() != null) {
            ModelAndView mv = new ModelAndView("front/error");
            return mv;
        }
        ModelAndView mv = new ModelAndView("front/info");

        RegisterInfo registerInfo = (RegisterInfo) request.getSession().getAttribute("registerInfo");
        if (registerInfo == null) {
            return new ModelAndView("front/login");
        } else {
            RegisterInfo reg = registerService.queryRegisterById(registerInfo.getId());
            mv.addObject("registerInfo", reg);
        }
        List<SubjectInfo> subjectInfos = subjectInfoService.queryList("from SubjectInfo where registerInfo_id = " + registerInfo.getId());
        SubjectInfo sub_info = new SubjectInfo();
        sub_info.setId(registerInfo.getId());
        sub_info.setSubject(registerInfo.getSubject());
        sub_info.setRegisterStatus(registerInfo.getRegisterStatus());
        sub_info.setInvoiceTitle(registerInfo.getInvoiceTitle());
        sub_info.setInvoiceInfo(registerInfo.getInvoiceInfo());
        sub_info.setTaxpayerNum(registerInfo.getTaxpayerNum());
        sub_info.setAddressName(registerInfo.getAddressName());
        sub_info.setTelephone(registerInfo.getTelephone());
        sub_info.setBankAccount(registerInfo.getBankAccount());
        sub_info.setBankAddress(registerInfo.getBankAddress());
        sub_info.setTaxIssue(registerInfo.getTaxIssue());
        sub_info.setAppreciationTaxType(registerInfo.getAppreciationTaxType());
        subjectInfos.add(sub_info);
        List<Metadata> status = metadataService.getMetadatasByType2("status");
        List<Metadata> status2 = metadataService.getMetadatasByType2("status2");
        List<Metadata> invoiceType = metadataService.getMetadatasByType2("invoiceType");
        List<Metadata> subject = metadataService.getMetadatasByType2("subject");
        List<Metadata> subject2 = metadataService.getMetadatasByType2("subject2");
        List<Metadata> registerType = metadataService.getMetadatasByType2("registerType");
        mv.addObject("status", status);
        mv.addObject("status2", status2);
        mv.addObject("invoiceType", invoiceType);
        mv.addObject("subject", subject);
        mv.addObject("subject2", subject2);
        mv.addObject("registerType", registerType);
        mv.addObject("subjectInfos", subjectInfos);
        return mv;
    }

    /**
     * 保存证件照
     *
     * @return
     */
    @RequestMapping("/saveCertificateId")
    public Object saveCertificateId(HttpServletRequest request) {
        String img1 = request.getParameter("img1");
//    	String img2 = request.getParameter("img2");
//    	String img3 = request.getParameter("img3");
        String obj_id = request.getParameter("obj_id");
        RegisterInfo registerInfo = registerService.queryRegisterById(Long.valueOf(obj_id));
        Map<String, Object> map = new HashMap<String, Object>();
        if (null != registerInfo) {
            registerInfo.setImg1(img1);
//            registerInfo.setImg2(img2);
//            registerInfo.setImg3(img3);
            boolean result = registerService.updateRegisterInfo(registerInfo);
            map.put("result", result);
        }
//    	SubjectInfo subjectInfo = subjectInfoService.querySubjectInfoById(Long.valueOf(obj_id));
//    	if(null != subjectInfo){
//            subjectInfo.setImg1(img1);
//            subjectInfo.setImg2(img2);
//            subjectInfo.setImg3(img3);
//            boolean result = subjectInfoService.updateSubjectInfo(subjectInfo);
//            map.put("result", result);
//        }
        return map;
    }

    @RequestMapping("/getObj")
    public Object getObj(HttpServletRequest request) {
        String obj_id = request.getParameter("obj_id");
        Map<String, Object> map = new HashMap<String, Object>();
        RegisterInfo registerInfo = registerService.queryRegisterById(Long.valueOf(obj_id));
        if (null != registerInfo) {
            map.put("obj", registerInfo);
        }
        return map;
    }

    @RequestMapping("/checkEmail")
    public Object checkEmail(String email, Boolean regType) {
        Map<String, Object> map = new HashMap<String, Object>();
        Phase phase = getActivePhase();
        if (phase == null) {
            map.put("success", false);
            return map;
        }
        RegisterInfo reg = registerService.queryByEmail(email, phase.getId(), regType);
        map.put("success", reg != null);
        return map;
    }

    @RequestMapping("/reg")
    public Object reg(HttpServletRequest request, RegisterInfo registerInfo, String repassword) {
        Phase phase = getActivePhase();
        //检查是否开放注册
        if (phase == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();

        if (StringUtils.isEmpty(registerInfo.getEmail())) {
            map.put("success", false);
            map.put("info", "请填写邮箱");
            return map;
        }
        RegisterInfo reg = registerService.queryByEmail(registerInfo.getEmail(), phase.getId(), true);
        if (reg != null) {
            map.put("success", false);
            map.put("info", "邮箱已经被占用");
            return map;
        }
        if (StringUtils.isEmpty(registerInfo.getPassword())) {
            map.put("success", false);
            map.put("info", "请填写密码");
            return map;
        }
        if (!registerInfo.getPassword().equals(repassword)) {
            map.put("success", false);
            map.put("info", "两次密码填写不一致");
            return map;
        }
        if (StringUtils.isEmpty(registerInfo.getName())) {
            map.put("success", false);
            map.put("info", "请填写姓名");
            return map;
        }
        if (StringUtils.isEmpty(registerInfo.getCompany())) {
            map.put("success", false);
            map.put("info", "请填写工作单位");
            return map;
        }
        if (StringUtils.isEmpty(String.valueOf(registerInfo.getSubject()))) {
            map.put("success", false);
            map.put("info", "请填写报名科目");
            return map;
        }
        registerInfo.setCountry("CHINA");
        registerInfo.setRegisterStatus(0);
        registerInfo.setRegType(true);
        registerInfo.setPhase(phase);
        registerInfo.setInvoiceInfo("发票内容为相应考试的考试费");
        try {
            String pwd = PasswordHash.createHash(registerInfo.getPassword());
            registerInfo.setPassword(pwd);

        } catch (Exception e) {
            throw new RuntimeException("修改用户密码加密失败....", e);
        }

        boolean success = registerService.addRegisterInfo(registerInfo);
        if (success) {
            request.getSession().setAttribute("registerInfo", registerInfo);
        }

        map.put("success", success);
        return map;
    }

    @RequestMapping("/reg2")
    public Object reg2(HttpServletRequest request, RegisterInfo registerInfo, String repassword) {
        Phase phase = getActivePhase();
        if (phase == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();

        if (StringUtils.isEmpty(registerInfo.getEmail())) {
            map.put("success", false);
            map.put("info", "请填写邮箱");
            return map;
        }
        RegisterInfo reg = registerService.queryByEmail(registerInfo.getEmail(), phase.getId(), false);
        if (reg != null) {
            map.put("success", false);
            map.put("info", "邮箱已经被占用");
            return map;
        }
        if (StringUtils.isEmpty(registerInfo.getPassword())) {
            map.put("success", false);
            map.put("info", "请填写密码");
            return map;
        }
        if (!registerInfo.getPassword().equals(repassword)) {
            map.put("success", false);
            map.put("info", "两次密码填写不一致");
            return map;
        }
        if (StringUtils.isEmpty(registerInfo.getName())) {
            map.put("success", false);
            map.put("info", "请填写中文姓名");
            return map;
        }
        if (StringUtils.isEmpty(registerInfo.getName_en())) {
            map.put("success", false);
            map.put("info", "请填写NAME");
            return map;
        }
        if (registerInfo.getDateOfBirth() == null) {
            map.put("success", false);
            map.put("info", "请填写Date of Birth");
            return map;
        }
        if (StringUtils.isEmpty(String.valueOf(registerInfo.getSubject2()))) {
            map.put("success", false);
            map.put("info", "请填写报名科目");
            return map;
        }
        registerInfo.setCountry("CHINA");
        registerInfo.setRegType(false);
        registerInfo.setPhase(phase);
        registerInfo.setRegisterStatus2(0);
        try {
            String pwd = PasswordHash.createHash(registerInfo.getPassword());
            registerInfo.setPassword(pwd);

        } catch (Exception e) {
            throw new RuntimeException("修改用户密码加密失败....", e);
        }

        boolean success = registerService.addRegisterInfo(registerInfo);
        if (success) {
            request.getSession().setAttribute("registerInfo", registerInfo);
        }
        map.put("success", success);
        return map;
    }

    @RequestMapping("/reg3")
    public Object reg3(HttpServletRequest request, SubjectInfo subjectInfo, long registerInfo_id) {
        Phase phase = getActivePhase();
        if (phase == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();

        if (StringUtils.isEmpty(String.valueOf(subjectInfo.getSubject()))) {
            map.put("success", false);
            map.put("info", "请填写报名科目");
            return map;
        }
        subjectInfo.setRegisterInfo_id(registerInfo_id);
        subjectInfo.setRegisterStatus(0);
        subjectInfo.setPhaseId(phase.getId());
        subjectInfo.setPhaseName(phase.getName());
        subjectInfo.setInvoiceInfo("发票内容为相应考试的考试费");
        RegisterInfo registerInfo = registerService.queryRegisterById(registerInfo_id);
        subjectInfo.setRegisterName(registerInfo.getName());
        boolean success = subjectInfoService.addSubjectInfo(subjectInfo);
        if (success) {
            request.getSession().setAttribute("registerInfo", registerInfo);
            request.getSession().setAttribute("subjectInfo", subjectInfo);
        }
        map.put("success", success);
        return map;
    }

    @RequestMapping("/checkSubject")
    public Object checkSubject(Long registerInfo_id, Integer subject,String sn) {
        Map<String, Object> map = new HashMap<String, Object>();
        Phase phase = getActivePhase();
        RegisterInfo reg = registerService.queryRegisterById(registerInfo_id);
        if(subject == reg.getSubject()){
            map.put("success", false);
            map.put("info", "当前选择考试科目《"+ sn +"》已报名，请勿重复报名！");
            return map;
        }
        List<SubjectInfo> subjectInfos = subjectInfoService.queryList("from SubjectInfo where registerInfo_id = " + registerInfo_id);
        for(SubjectInfo sub : subjectInfos){
            if(subject == sub.getSubject()){
                map.put("success", false);
                map.put("info", "当前选择考试科目《"+ sn +"》已报名，请勿重复报名！");
                return map;
            }
        }
        map.put("success", true);
        return map;
    }

    private void sendEmail(String email, String name, String subject) {
        EmailBody body = new EmailBody();
        MailSender.send(email, "", "");
    }

    @RequestMapping("/login")
    public Object login(String name, String password, String code, HttpServletRequest request) {
        Phase phase = getActivePhase();
        if (phase == null) {
            return null;
        }
        HashMap<String, Object> map = new HashMap<String, Object>();
        boolean isValid = ValidateCodeController.validate(request, code);
        if (!isValid) {
            //验证码错误
            map.put("status", 0);
            return map;
        }
        RegisterInfo registerInfo = registerService.queryByEmail(name, phase.getId(), true);
        if (registerInfo == null) {
            //用户不存在
            map.put("status", 1);
            return map;
        }
        try {
            map.put("status", 3);
            boolean ok = PasswordHash.validatePassword(password, registerInfo.getPassword());
            //3密码不正确
            //4密码正确 登录成功
            if (ok) {
                map.put("status", 4);
                request.getSession().setAttribute("registerInfo", registerInfo);
            }
        } catch (Exception e) {
            //啥也不干
        }
        return map;
    }

    @RequestMapping("/login2")
    public Object login2(String name, String password, String code, HttpServletRequest request) {
        Phase phase = getActivePhase();
        if (phase == null) {
            return null;
        }
        HashMap<String, Object> map = new HashMap<String, Object>();
        boolean isValid = ValidateCodeController.validate(request, code);
        if (!isValid) {
            //验证码错误
            map.put("status", 0);
            return map;
        }
        RegisterInfo registerInfo = registerService.queryByEmail(name, phase.getId(), false);
        if (registerInfo == null) {
            //用户不存在
            map.put("status", 1);
            return map;
        }
        try {
            map.put("status", 3);
            boolean ok = PasswordHash.validatePassword(password, registerInfo.getPassword());
            //3密码不正确
            //4密码正确 登录成功
            if (ok) {
                map.put("status", 4);
                request.getSession().setAttribute("registerInfo", registerInfo);
                request.getSession().setAttribute("user_in_session", registerInfo);
            }
        } catch (Exception e) {
            //啥也不干
        }
        return map;
    }

    @RequestMapping("/resetPassword")
    public Object resetPassword() {
        ModelAndView mv = new ModelAndView("front/reset");
        return mv;
    }

    @RequestMapping("/resetPwd")
    @ResponseBody
    public Object resetPwd(HttpServletRequest request, String email, boolean regType, String validateCode) {
        boolean valid = ValidateCodeController.validate(request, validateCode);
        Map<String, Object> map = new HashMap<String, Object>();
        if (!valid) {
            map.put("success", false);
            map.put("info", "验证码错误");
            return map;
        }

        Phase phase = getActivePhase();
        RegisterInfo info = registerService.queryByEmail(email, phase.getId(), regType);
        if (info == null) {
            map.put("success", false);
            map.put("info", "账号不存在");
            return map;
        }
        String newPwd = "";
        try {
            double rand = Math.random() * 10000000 + 1000000;
            newPwd = String.valueOf((long) rand);
            info.setPassword(PasswordHash.createHash(newPwd));
            registerService.updateRegisterInfo(info);

        } catch (Exception e) {
            throw new RuntimeException("修改用户密码加密失败....", e);
        }

        Mail new_mail = new Mail();
        new_mail.setHost(MailSender.SMTP);
        new_mail.setSender(MailSender.USERNAME);
        new_mail.setEmailCount(MailSender.USERNAME);
        new_mail.setEmailPassword(MailSender.PASSWORD);
        new_mail.setProtocol("smtp");
        new_mail.setName(info.getName());
        new_mail.setReceiver(info.getEmail());
        new_mail.setMailTitle("密码重置成功");
        String html = info.getName() + "，您好，<br><br>&emsp;&emsp;您已成功重置了密码，您的密码已修改为<span style='color:red;'>" + newPwd + "</span>,请用新密码登录本系统。<br>" +
                "<br><br><div style='font-size:12px;'>本邮件为系统发送，请勿直接回复。</div>";
        new_mail.setMailMessage(html);
        new Thread() {
            @Override
            public void run() {
                super.run();
                for (int i = 0; i < 5; i++) {
                    boolean success = MailUtil.sendMail(new_mail);
                    if (success) {
                        break;
                    }
                }
            }
        }.start();

        map.put("success", true);
        map.put("info", "发送成功");
        return map;
    }
}
