package com.izouma.nineth.service;

import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.izouma.nineth.config.RedisKeys;
import com.izouma.nineth.config.SysConstants;
import com.izouma.nineth.domain.IdentityAuth;
import com.izouma.nineth.domain.User;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.enums.AuthStatus;
import com.izouma.nineth.enums.InviteeQualificationsType;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.lock.RedisLockable;
import com.izouma.nineth.repo.*;
import com.izouma.nineth.utils.DateTimeUtils;
import com.izouma.nineth.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service
@AllArgsConstructor
public class IdentityAuthService {

    private final IdentityAuthRepo identityAuthRepo;
    private final UserRepo         userRepo;
    private final SysConfigService sysConfigService;
    private final ActivityInviteService activityInviteService;
    public Page<IdentityAuth> all(PageQuery pageQuery) {
        return identityAuthRepo.findAll(JpaUtils.toSpecification(pageQuery, IdentityAuth.class), JpaUtils.toPageRequest(pageQuery));
    }

    public void apply(IdentityAuth identityAuth) {
        if (identityAuth.getUserId() == null) {
            throw new BusinessException("用户不存在");
        }

        if(StringUtils.isBlank(identityAuth.getRealName())){
            throw new BusinessException("真实姓名不能为空");
        }

        int age = DateTimeUtils.getAge(identityAuth.getIdNo());
        if (age < 18){
            throw new BusinessException("网络交易有风险,请结合自身风险承担能力谨慎交易。");
        }
        User user = userRepo.findByIdAndDelFalse(identityAuth.getUserId()).orElseThrow(new BusinessException("用户不存在"));
        //卡号不能重复 查询有没有其他人绑定了IdentityAuthService
        if(identityAuthRepo.findByIdNoAndAuthSuccess(identityAuth.getIdNo())>= sysConfigService.getInt(SysConstants.REGISTERED_NUMBER)){
            throw new BusinessException("身份证已经被绑定过");
        }
        List<IdentityAuth> auths = identityAuthRepo.findByUserIdAndDelFalse(identityAuth.getUserId());
        auths.stream().filter(auth -> auth.getStatus() == AuthStatus.PENDING).findAny().ifPresent(a -> {
            throw new BusinessException("正在审核中，请勿重复提交");
        });

        auths.stream().filter(auth -> auth.getStatus() == AuthStatus.SUCCESS).findAny().ifPresent(a -> {
            throw new BusinessException("已认证，请勿重复提交");
        });
        identityAuth.setStatus(AuthStatus.PENDING);
        identityAuthRepo.save(identityAuth);
        user.setAuthStatus(AuthStatus.PENDING);
        userRepo.save(user);
    }



    @Transactional
    public synchronized void audit(Long id, AuthStatus status) {
        IdentityAuth auth = identityAuthRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("申请不存在"));
        if (auth.getStatus() != AuthStatus.PENDING) {
            throw new BusinessException("已经审核过");
        }
        User user = userRepo.findByIdAndDelFalse(auth.getUserId()).orElseThrow(new BusinessException("用户不存在"));
        if (status == AuthStatus.SUCCESS) {
            user.setAuthId(auth.getId());
        }
        user.setAuthStatus(status);
        userRepo.save(user);
        auth.setStatus(status);
        identityAuthRepo.save(auth);
        activityInviteService.risingStar(user.getId(), null , InviteeQualificationsType.CERTIFICATION);
    }


    public void validate(String name, String phone, String idno) {
        String body = HttpRequest.post("https://jubrige.market.alicloudapi.com/mobile/3-validate-transfer")
                .header("Authorization", "APPCODE b48bc8f6759345a79ae20a951f03dabe")
                .contentType(HttpRequest.CONTENT_TYPE_FORM)
                .form("idCardNo", idno)
                .form("mobile", phone)
                .form("name", name)
                .body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (jsonObject.getInteger("code") != 200) {
            String msg = jsonObject.getString("msg");
            throw new BusinessException(msg);
        }
    }


    /**
     * 一键审核
     */
    @RedisLockable(prefix= RedisKeys.USER_AUDIT_LOCK)
    public void oneButtonPass() {
        List<Long> ids = identityAuthRepo.findAllPendingId();
        ids.forEach(id -> this.audit(id,AuthStatus.SUCCESS));
    }


}
