package com.yonge.cooleshow.biz.dal.service.impl;

import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.dto.RealnameAuthReq;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.mapper.SysUserMapper;
import com.yonge.cooleshow.biz.dal.service.SysUserContractRecordService;
import com.yonge.cooleshow.biz.dal.service.SysUserService;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.ContractTemplateTypeEnum;
import com.yonge.cooleshow.common.enums.SysUserType;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.thirdparty.user.realname.RealnameAuthenticationPlugin;
import com.yonge.toolset.utils.idcard.IdcardInfoExtractor;
import com.yonge.toolset.utils.idcard.IdcardValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private RealnameAuthenticationPlugin realnameAuthenticationPlugin;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUserContractRecordService sysUserContractRecordService;
    @Override
    public Long getUserId() {
        return Optional.ofNullable(sysUserFeignService.queryUserInfo()).
                map(SysUser::getId).
                orElseThrow(()-> new BizException("请登录"));
    }

    @Override
    public SysUser getUser() {
        Optional<SysUser> optional = Optional.ofNullable(sysUserFeignService.queryUserInfo());
        optional.map(SysUser::getId).
                orElseThrow(()-> new BizException("请登录"));
        return optional.get();
    }

    @Override
    public SysUser findUserById(Long userId) {
        Optional<SysUser> optional = Optional.ofNullable(sysUserFeignService.queryUserById(userId));
        optional.map(SysUser::getId).
                orElseThrow(()-> new BizException("请登录"));
        return optional.get();
    }

    @Override
    public IdcardInfoExtractor updateUserCard(RealnameAuthReq realNameAuthDto, SysUser sysUser,ClientEnum client) {
        IdcardValidator idcardValidator = new IdcardValidator();
        //验证身份证号合法性
        boolean validatedAllIdcard = idcardValidator.isValidatedAllIdcard(realNameAuthDto.getIdCardNo());
        if (!validatedAllIdcard) {
            throw new BizException("身份证号不合法");
        }
        //通过身份证号获取身份信息
        IdcardInfoExtractor idcardInfoExtractor = new IdcardInfoExtractor(realNameAuthDto.getIdCardNo(), validatedAllIdcard);
        //todo 通过环境，不做实名判断
        try {
            boolean verify = realnameAuthenticationPlugin.verify(realNameAuthDto.getRealName(), realNameAuthDto.getIdCardNo());
            if (!verify) {
                throw new BizException("未通过实名认证");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("未通过实名认证");
        }

        if (realNameAuthDto.getSave()) {
            realNameAuthDto.setUserId(sysUser.getId());
            realNameAuthDto.setGender(idcardInfoExtractor.getGender());
            realNameAuthDto.setBirthday(idcardInfoExtractor.getBirthday());
            //实名认证通过后立刻保存
            sysUserMapper.updateUserCard(realNameAuthDto);
        }
        // 签订用户注册协议

        // 判断是否已经签署
        Boolean contractSign = sysUserContractRecordService.checkContractSign(sysUser.getId(),
                                                                              SysUserType.valueOf(client.getCode()),
                                                                              ContractTemplateTypeEnum.REGISTER);
        if (!contractSign && realNameAuthDto.getContract()) {
            sysUser.setRealName(realNameAuthDto.getRealName());
            sysUser.setIdCardNo(realNameAuthDto.getIdCardNo());
            sysUser.setGender(realNameAuthDto.getGender());
            sysUser.setBirthdate(realNameAuthDto.getBirthday());
            HttpResponseResult<Boolean> sign = sysUserContractRecordService.sign(ContractTemplateTypeEnum.REGISTER,
                                                                                 SysUserType.valueOf(client.getCode()),sysUser);
            if (!sign.getStatus() || !sign.getData()) {
                throw new BizException(sign.getMsg());
            }
        }
        return idcardInfoExtractor;
    }
}