package com.lightinit.hsdataportal.controller.open;

import com.google.gson.Gson;
import com.lightinit.hsdataportal.common.ConfigUtils;
import com.lightinit.hsdataportal.common.GuidGenerator;
import com.lightinit.hsdataportal.common.SysContants;
import com.lightinit.hsdataportal.common.UploadFileUtils;
import com.lightinit.hsdataportal.controller.BaseController;
import com.lightinit.hsdataportal.dictionary.DicCompanyAuthResult;
import com.lightinit.hsdataportal.dictionary.DicUserAuthState;
import com.lightinit.hsdataportal.entity.User;
import com.lightinit.hsdataportal.model.*;
import com.lightinit.hsdataportal.service.IUserVerifyService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.LinkedHashMap;

/**
 * @Author: sunxiang
 * @Date: 2018/6/27 14:28
 * @Description:
 **/
@Controller
@RequestMapping(value = "/open/userverify")
public class UserVerifyController extends BaseController{

    @Autowired
    private IUserVerifyService userVerifyService;
    @RequiresAuthentication
    @RequestMapping(value="detail.htm")
    public ModelAndView detail(HttpSession session) {
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        String imageContextPath = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.IMAGE_CONTEXT_PATH);
        ModelAndView modelAndView = null;
        UserPersonalModel userPersonalModel= userVerifyService.getPersonalDetail(loginUser.getId());
        if(userPersonalModel != null && (userPersonalModel.getAuthState().equals(DicUserAuthState.PENDING) || userPersonalModel.getAuthState().equals(DicUserAuthState.WAITING))){
            modelAndView=new ModelAndView("open/user_verify/personalDetail");//个人认证页面
            modelAndView.addObject("outputModel",userPersonalModel);
            return  modelAndView;
        }
        UserCompanyModel userCompanyModel= userVerifyService.getCompanyDetail(loginUser.getId());
        if(userCompanyModel !=null && (userCompanyModel.getAuthState().equals(DicUserAuthState.PENDING)|| userCompanyModel.getAuthState().equals(DicUserAuthState.WAITING))){
            modelAndView=new ModelAndView("open/user_verify/companyDetail");//企业认证页面
            modelAndView.addObject("outputModel",userCompanyModel);
            modelAndView.addObject("imageContextPath",imageContextPath);
            return  modelAndView;
        }
        User user = userVerifyService.getUserBaseInforamtion(loginUser.getId());
        modelAndView=new ModelAndView("open/user_verify/baseInformation");//未认证基本页面
        modelAndView.addObject("outputModel",user);
        return modelAndView;
    }

    @RequiresAuthentication
    @RequestMapping(value="changePassword.action")
    @ResponseBody
    public ResultState changePassword(String oldpassword,String newpassword,String renewpassword,HttpSession session) {
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        User user = userVerifyService.getUserBaseInforamtion(loginUser.getId());
        if(StringUtils.isEmpty(oldpassword) || StringUtils.isEmpty(newpassword) || loginUser==null){
            LinkedHashMap<Object, Object> hashMap = new LinkedHashMap<>();
            hashMap.put("oldpassword","密码不能为空");
            hashMap.put("newpassword","密码不能为空");
            return buildInvalidResultState("",hashMap);
        }
        if(StringUtils.isNotEmpty(renewpassword) && StringUtils.isNotEmpty(newpassword) && !(newpassword.equals(renewpassword))){
            LinkedHashMap<Object, Object> hashMap = new LinkedHashMap<>();
            hashMap.put("newpassword","两次密码输入不正确");
            hashMap.put("renewpassword","两次密码输入不正确");
            return buildInvalidResultState("",hashMap);
        }
        if(! user.getPassword().equals(new Md5Hash(oldpassword, user.getUsername() + user.getSalt(), 3).toHex())){
            LinkedHashMap<Object, Object> hashMap = new LinkedHashMap<>();
            hashMap.put("oldpassword","旧密码不正确");
            return buildInvalidResultState("",hashMap);
        }
        user.setPassword(new Md5Hash(newpassword, user.getUsername() + user.getSalt(), 3).toHex());
        ResultState resultState1 = userVerifyService.changePassword(user);
        return  resultState1;
    }

    /*
    *@Description 接受“个人认证”和“企业认证”
    *@Param param:1：个人认证    2：企业认证
    *@Date 2018/6/28
    *@return
    **/
    @RequiresAuthentication
    @RequestMapping(value="verifyCompany.action")
    @ResponseBody
    public ResultState verifyCompany(@Validated UserCompanyModel userCompanyModel,BindingResult bindingResult,HttpSession session,MultipartFile commercialInstrumentCopyImg) {
        if(session.getAttribute("isVerify")!=null){
            return new ResultState();
        }
        try {
            session.setAttribute("isVerify",true);
            LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
            if(bindingResult.hasErrors()){
                return getAllFieldInvalidResultState(userCompanyModel,bindingResult);
            }
            if( !(commercialInstrumentCopyImg.getSize()>0)){
                LinkedHashMap<Object, Object> hashMap = new LinkedHashMap<>();
                hashMap.put("commercialInstrumentCopyImg","营业执照副本必须上传");
                return buildInvalidResultState("",hashMap);
            }
            // 保存文件
            String uniqueDir = GuidGenerator.generate() + File.separator;
            String dataFileDir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.USER_COMPANY_VERIFY_DIR, uniqueDir, SysContants.UploadFilePath.USER_COMPANY_VERIFY_IMG_DIR);
            if (commercialInstrumentCopyImg != null && !commercialInstrumentCopyImg.isEmpty()){
                if (UploadFileUtils.writeUploadFile(commercialInstrumentCopyImg, dataFileDir, SysContants.PropertyKey.UPLOAD_IMAGE_ROOT_DIR)){
                    userCompanyModel.setCommercialInstrumentCopy(dataFileDir + commercialInstrumentCopyImg.getOriginalFilename());
                }else {
                    return buildInvalidResultState(ResultStateCode.UNKNOWN_ERROR, "数据文件保存失败");
                }
            }
            userCompanyModel.setUserId(loginUser.getId());
            ResultState resultState = userVerifyService.verifyCompany(userCompanyModel);
            return resultState;
        } finally {
            session.removeAttribute("isVerify");
        }
    }

    @RequiresAuthentication
    @RequestMapping(value="verifyPersonal.action")
    @ResponseBody
    public ResultState verifyPersonal(@Validated UserPersonalModel userPersonalModel,BindingResult bindingResult,HttpSession session) {
        System.out.println(11111);
        if(session.getAttribute("isVerify")!=null){
            return new ResultState();
        }
        try {
            session.setAttribute("isVerify",true);
            if(bindingResult.hasErrors()){
                return getAllFieldInvalidResultState(userPersonalModel,bindingResult);
            }
            boolean notError=false;
            String errorName="";
            String errorNameTemp="";
            if(userPersonalModel.getAuthMethod().equals("银行卡号认证")){
                notError=userPersonalModel.getBankCard()!=null && userPersonalModel.getBankCard().matches("^(\\d{16}|\\d{19})$");
                errorName="bankCard";
            }else if(userPersonalModel.getAuthMethod().equals("手机认证")){
                notError=userPersonalModel.getAuthPhone()!=null && userPersonalModel.getAuthPhone().matches("\\d{11}$") &&
                        userPersonalModel.getIdCard()!=null &&  userPersonalModel.getIdCard().matches("(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}$)");
                errorName=userPersonalModel.getAuthPhone()!=null && userPersonalModel.getAuthPhone().matches("\\d{11}$")?"":"authPhone";
                errorNameTemp=userPersonalModel.getIdCard()!=null &&  userPersonalModel.getIdCard().matches("(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}$)")?"":"idCard";
            }else{
                notError=userPersonalModel.getIdCard()!=null && userPersonalModel.getIdCard().matches("(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}$)");
                errorName="idCard";
            }
            if(!notError){
                ResultState<Object> resultState = new ResultState<>();
                resultState.setStateCode(400);
                JSONObject object = new JSONObject();
                if(!StringUtils.isEmpty(errorNameTemp)){
                    object.accumulate(errorNameTemp,"输入正确的号码");
                }
                object.accumulate(errorName,"请输入正确的号码");
                if(!StringUtils.isEmpty(errorNameTemp)){
                    object.accumulate(errorNameTemp,"输入正确的号码");
                }
                resultState.setData(object);
                return resultState;
            }
            LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
            userPersonalModel.setUserId(loginUser.getId());
            ResultState resultState = userVerifyService.verifyPersonal(userPersonalModel);
            return resultState;
        } finally {
            session.removeAttribute("isVerify");
        }
    }
}
