package com.lightinit.hsdataportal.impl;

import com.lightinit.hsdataportal.WXsdk.MyWXUtils;
import com.lightinit.hsdataportal.common.AuthenticUtil;
import com.lightinit.hsdataportal.common.HttpTookitUtils;
import com.lightinit.hsdataportal.common.HttpUtil;
import com.lightinit.hsdataportal.common.TokenUtils;
import com.lightinit.hsdataportal.dictionary.DicCompanyAuthResult;
import com.lightinit.hsdataportal.dictionary.DicNewGateway;
import com.lightinit.hsdataportal.dictionary.DicUserAuthState;
import com.lightinit.hsdataportal.dictionary.DicUserType;
import com.lightinit.hsdataportal.entity.*;
import com.lightinit.hsdataportal.mapper.*;
import com.lightinit.hsdataportal.model.ResultState;
import com.lightinit.hsdataportal.model.ResultStateCode;
import com.lightinit.hsdataportal.model.UserCompanyModel;
import com.lightinit.hsdataportal.model.UserPersonalModel;
import com.lightinit.hsdataportal.service.IUserVerifyService;
import com.lightinit.hsdataportal.spring.DynamicDataContextHolder;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

/**
 * @Author: sunxiang
 * @Date: 2018/6/27 15:31
 * @Description:
 **/
@Service
public class UserVerifyServiceImpl implements IUserVerifyService {

    @Autowired
    private UserPersonalMapper userPersonalMapper;
    @Autowired
    private UserCompanyMapper userCompanyMapper;
    @Autowired
    private UserAuthSettingMapper userAuthSettingMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private SectorMapper sectorMapper;

    private static Logger logger = LoggerFactory.getLogger(UserVerifyServiceImpl.class);
    @Override
    public UserPersonalModel getPersonalDetail(Long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return userMapper.getPersonalDetailByUserId(id);
    }

    @Override
    public UserCompanyModel getCompanyDetail(Long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return userMapper.getCompanyDetail(id);
    }

    @Override
    public User getUserBaseInforamtion(Long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public UserPersonalModel getAdminBaseInforamtion(Long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return adminMapper.getAdminBaseInforamtion(id);
    }

    @Override
    public Admin getAdmin(Long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return adminMapper.selectByPrimaryKey(id);
    }


    @Transactional
    @Override
    public ResultState verifyPersonal(UserPersonalModel outputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState resultState = new ResultState();
        try {
            User user = userMapper.selectByPrimaryKey(outputModel.getUserId());
            if(DicUserAuthState.PENDING.equals(user.getAuthState())){//防止黑入多次已认证
                return resultState;
            }
            //插入user_personal表
            UserPersonal userPersonal = new UserPersonal();
            userPersonal.setId(user.getId());
            userPersonal.setCreatedAt(new Date());
            userPersonal.setFullName(outputModel.getFullName());
            userPersonal.setAuthMethod(outputModel.getAuthMethod());
            userPersonal.setIdCard(StringUtils.isEmpty(outputModel.getIdCard())?null:outputModel.getIdCard());
            userPersonal.setPhone(StringUtils.isEmpty(outputModel.getAuthPhone())?null:outputModel.getAuthPhone());
            userPersonal.setBankCard(StringUtils.isEmpty(outputModel.getBankCard())?null:outputModel.getBankCard());

            if(DicUserAuthState.APPROVED.equals(user.getAuthState())){//注册未认证情况
                user.setAuthState(DicUserAuthState.WAITING);
                user.setUserType(DicUserType.PERSONAL);
                userPersonalMapper.insertUserPersonal(userPersonal);
                userMapper.updateByPrimaryKeySelective(user);
            }else{
                userPersonalMapper.updateByPrimaryKeySelective(userPersonal);//注册认证失败/待认证情况
            }
            resultState.setMsg("正在认证进行中。。。。。");
            //开启认证
            new Thread(() -> {
                boolean authentic =false;
                String authMethod = outputModel.getAuthMethod();
                if("银行卡号认证".equals(authMethod)){
                    authentic=AuthenticUtil.authenticByBankCard(outputModel.getFullName(),outputModel.getBankCard());
                }else if("手机认证".equals(authMethod)){
                    authentic=AuthenticUtil.authenticByPhone(outputModel.getFullName(),outputModel.getIdCard(),outputModel.getAuthPhone());
                }else if("身份证认证".equals(authMethod)){
                    authentic=AuthenticUtil.authenticByIdCard(outputModel.getFullName(), outputModel.getIdCard());
                }else{
                    return;
                }
                if(authentic){
                    user.setAuthState(DicUserAuthState.PENDING);
                    user.setAuthAt(new Date());
                    userMapper.updateByPrimaryKeySelective(user);

                    //调用认证接口
                    HashMap<String, String> authheaderMap = new HashMap<>();
                    authheaderMap.put("content-type","application/json");
                    HashMap<String, String> requestMap = new HashMap<>();
                    requestMap.put("appId",DicNewGateway.APPLICATIONID);//xiugai
                    requestMap.put("userId",user.getUsername());
                    requestMap.put("signStatus","启用");
                    try {
                        String passMessage = HttpUtil.httpPost(DicNewGateway.SIGNADD, authheaderMap,requestMap);
                        JSONObject userJson = JSONObject.fromObject(passMessage);
                        if("success".equals(userJson.get("status"))&& "code".equals(userJson.get("code").toString())){
                             //2.------>同步到服务开发环境平台
                            //插入user_auth_setting表
                            UserAuthSetting userAuthSetting = new UserAuthSetting();
                            userAuthSetting.setUserId(user.getId());
                            userAuthSetting.setAuthSecret(userJson.get("result").toString());
                            UserAuthSettingExample example = new UserAuthSettingExample();
                            example.createCriteria().andUserIdEqualTo(user.getId());
                            userAuthSettingMapper.updateByExampleSelective(userAuthSetting,example);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.info("认证接口调用失败");
                    }
                }else{
                    user.setAuthState(DicUserAuthState.FAIL);
                    userMapper.updateByPrimaryKeySelective(user);
                }
            }).start();
            return resultState;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg("认证失败");
        return resultState;
    }

    @Transactional
    @Override
    public ResultState verifyCompany(UserCompanyModel outputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState resultState = new ResultState();
        User user = userMapper.selectByPrimaryKey(outputModel.getUserId());
        if(DicUserAuthState.PENDING.equals(user.getAuthState())){
            return resultState;
        }
        try {
            UserCompanyWithBLOBs userCompanyWithBLOBs = new UserCompanyWithBLOBs();
            BeanUtils.copyProperties(outputModel, userCompanyWithBLOBs);
            userCompanyWithBLOBs.setId(user.getId());
            userCompanyWithBLOBs.setPhone(outputModel.getAuthPhone());
            userCompanyWithBLOBs.setCreatedAt(new Date());
            userCompanyWithBLOBs.setCreatedBy(outputModel.getUserId());

            UserAuthSetting userAuthSetting = new UserAuthSetting();
            userAuthSetting.setUserId(user.getId());
            userAuthSetting.setAuthKey(UUID.randomUUID().toString());
            userAuthSetting.setAuthSecret(UUID.randomUUID().toString());

            if(DicUserAuthState.APPROVED.equals(user.getAuthState())) {
                user.setAuthState(DicUserAuthState.WAITING);
                user.setUserType(DicUserType.COMPANY);
                userMapper.updateByPrimaryKeySelective(user);
                //插入user_company表中
                userCompanyMapper.insertUserCompany(userCompanyWithBLOBs);
                //插入user_auth_setting表
                //userAuthSettingMapper.insert(userAuthSetting);
            }else{
                userCompanyMapper.updateByPrimaryKeySelective(userCompanyWithBLOBs);
            }
            resultState.setMsg("正在认证进行中。。。。。");
            /*new Thread(() -> { 后台审核，前台不必验证
                boolean authentic = AuthenticUtil.authenticByIdCard(outputModel.getContact(), outputModel.getIdCard());
                if(authentic){
                    user.setAuthState(DicUserAuthState.PENDING);
                    user.setAuthAt(new Date());
                    userMapper.updateByPrimaryKeySelective(user);
                }else{
                    user.setAuthState(DicUserAuthState.FAIL);
                    userMapper.updateByPrimaryKeySelective(user);
                }
            }).start();*/
            return resultState;
        } catch (BeansException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg("认证失败");
        return resultState;
    }



    @Transactional
    @Override
    public ResultState changePassword(User user) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState resultState = new ResultState();
        try {
            userMapper.updateByPrimaryKeySelective(user);
            resultState.setMsg("修改密码成功");
            return resultState;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg("修改密码失败");
        return resultState;
    }

    @Transactional
    @Override
    public ResultState changeAdminPassword(Admin admin) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState resultState = new ResultState();
        try {
            adminMapper.updateByPrimaryKeySelective(admin);
            resultState.setMsg("修改密码成功");
            return resultState;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg("修改密码失败");
        return resultState;
    }
}
