package cn.qg.qaplatform.service.xyqb.impl;

import cn.qg.qaplatform.config.WebSocketServer;
import cn.qg.qaplatform.entity.vo.XyqbApplyDataVo;
import cn.qg.qaplatform.process.Common;
import cn.qg.qaplatform.process.Lexin;
import cn.qg.qaplatform.process.Xyqb;
import cn.qg.qaplatform.service.xyqb.AssignFundingRecordService;
import cn.qg.qaplatform.service.xyqbUser.UserService;
import cn.qg.qaplatform.service.xyqb.LexinDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Slf4j
public class LexinDataServiceImpl implements LexinDataService {
    @Autowired
    UserService userService;

    @Autowired
    AssignFundingRecordService assignFundingRecordService;

    @Autowired
    RedisTemplate redisTemplate;

    public void queryFundingAssignProgress(String namespace, String phoneNo, Integer fundId, String symbol) throws InterruptedException {
        String userId = String.valueOf(userService.getUserInfoByPhoneNo(namespace, phoneNo).getId());
        while (true) {
            Integer searchResult = Math.toIntExact(assignFundingRecordService.getFundRecordByUserId(namespace, userId).getFundingCorpId());
            log.info(searchResult.toString());
            if (fundId.equals(searchResult)) {
                log.info("用户：" + userId + "资方分配成功!");
                if (!StringUtils.isEmpty(symbol)) {
                    WebSocketServer.sendInfo("查询到的资方为：" + searchResult +",资方分配成功.", symbol);
                }
                break;
            } else {
                if (!StringUtils.isEmpty(symbol)) {
                    WebSocketServer.sendInfo("查询到的资方为：" + searchResult +",资方还未分配成功，10秒后重试", symbol);
                }
                Thread.sleep(10000);
            }
        }
    }

    @Override
    public boolean genLexinData(XyqbApplyDataVo xyqbApplyDataVo) throws Exception {
        String namespace = xyqbApplyDataVo.getNamespace();
        String phoneNo = xyqbApplyDataVo.getPhoneNo();
        String bankCardNo = xyqbApplyDataVo.getBankCardNo();
        String bankCode = xyqbApplyDataVo.getBankCode();
        String bankName = xyqbApplyDataVo.getBankName();
        Integer fundId = xyqbApplyDataVo.getFundId();
        String symbol = xyqbApplyDataVo.getSymbol();
        Integer amount = xyqbApplyDataVo.getAmount();
        Integer term = xyqbApplyDataVo.getTerm();
        Xyqb.symbol = symbol;
        Common.symbol = symbol;
        // 分配资产计划
        boolean fundAssignResult = Common.assignFundCorp(namespace, fundId);
        // 进件
        boolean createOrderResult = Lexin.createOrder(xyqbApplyDataVo);
        if (!createOrderResult) {
            return false;
        }
        String token = Xyqb.login(namespace, 1, phoneNo);
        Map userInfoResult = Xyqb.checkUserId(namespace, phoneNo);
        String uuid = userInfoResult.get("uuid").toString();
        String userId = userInfoResult.get("id").toString();
//        String channelOrderNo = Common.queryChannelOrderNoByPhone(namespace, phoneNo, ChannelEnum.LEXIN.getChannelId());
        String channelOrderNo = Common.queryChannelOrderNoByPhone(namespace, phoneNo, 159886);
        Common.channelOrderApprove(namespace, channelOrderNo, amount, "0", true, term);
        // 风控授信回调
//        Xyqb.creditAuthNotify(namespace, token, uuid, ChannelEnum.LEXIN.getChannelId(), fundId, channelOrderNo, 0, true, amount, term);
        setUserStatusRedisValue(namespace, phoneNo, 0);
        // 查询到资方分配成功才进行下一步
        queryFundingAssignProgress(namespace, phoneNo, fundId, symbol);
        // api提现
        boolean withDrawResult = Common.withDraw(namespace, "LEXIN", channelOrderNo, bankCardNo, bankCode, bankName, phoneNo);
        if (!withDrawResult) {
            return false;
        }
        setUserStatusRedisValue(namespace, phoneNo, 2);
        // 二次风控
//        Integer loanId = Common.queryLoanId(namespace, phoneNo, ChannelEnum.LEXIN.getChannelId());
        Integer loanId = Common.queryLoanId(namespace, phoneNo, 159886);
        boolean secondWindControlResult = Xyqb.externalQuotaOrderAuditNotify(namespace, 1, token, uuid, loanId, 11, true);

        Xyqb.modifyContactStatus(namespace, userId);
        // 放款
        String opToken = Xyqb.loginOP(namespace);
        // 查询待打款数量
        Map<String, Integer> peopleMap = Xyqb.checkWaitingFundingCorpOperatePeople(namespace, fundId);
        Integer money = peopleMap.get("money");
        Integer people = peopleMap.get("people");
        // 修改待放款用户创建时间
        Xyqb.modifyWaitingFundingCreatedAt(namespace, loanId);
        Thread.sleep(5000);
        // 直接打款
        Xyqb.fundsPlanLoanApply(namespace, opToken, fundId, money, people);
        Thread.sleep(30000);
        // 放款结果通知
        boolean makeLoanResult = Xyqb.payNotify(namespace, loanId, true);
        setUserStatusRedisValue(namespace, phoneNo, 3);
        return makeLoanResult;
    }

    public void setUserStatusRedisValue(String namespace, String phoneNo, Integer status) {
        String redisKey = namespace + "_" + phoneNo;
        redisTemplate.opsForValue().set(redisKey, status);
    }
}
