package cn.quantgroup.customer.service.impl;

import cn.quantgroup.customer.constant.Constant;
import cn.quantgroup.customer.enums.ErrorCodeEnum;
import cn.quantgroup.customer.exception.BusinessException;
import cn.quantgroup.customer.rest.param.repay.EarlySettleOperateQueryReq;
import cn.quantgroup.customer.rest.param.repay.EarlySettleOperateReq;
import cn.quantgroup.customer.rest.param.repay.RepayOrderInfoQuery;
import cn.quantgroup.customer.rest.param.repay.RepayOrderQuery;
import cn.quantgroup.customer.rest.vo.JsonResult;
import cn.quantgroup.customer.rest.vo.MoResult;
import cn.quantgroup.customer.rest.vo.repay.RepayInfoResult;
import cn.quantgroup.customer.rest.vo.repay.RepayOptRecord;
import cn.quantgroup.customer.rest.vo.repay.XyqbRepayInfo;
import cn.quantgroup.customer.service.*;
import cn.quantgroup.user.retbean.XUser;
import cn.quantgroup.user.vo.UserSysResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service("repayService")
public class RepayServiceImpl implements IRepayService {

    private final IUserService userService;
    private final UserSdkImpl userSdk;
    private final IXyqbService xyqbService;
    private final ISidecarService sidecarService;
    private final IKoalaService koalaService;

    @Autowired
    public RepayServiceImpl(IUserService userService, UserSdkImpl userSdk, IXyqbService xyqbService, ISidecarService sidecarService, IKoalaService koalaService) {
        this.userService = userService;
        this.userSdk = userSdk;
        this.xyqbService = xyqbService;
        this.sidecarService = sidecarService;
        this.koalaService = koalaService;
    }

    @Override
    public String findRepayOrders(RepayOrderQuery repayOrderQuery) {
        String phoneNo = repayOrderQuery.getPhoneNo();
        String idNo = repayOrderQuery.getIdNo();
        if (StringUtils.isEmpty(phoneNo) && StringUtils.isEmpty(idNo)) {
            throw new BusinessException(ErrorCodeEnum.PARAM_ERROR);
        }
        if (StringUtils.isEmpty(phoneNo)) {
            String uuid = userService.findUuidByIdNo(idNo);
            UserSysResult<XUser> userUserSysResult = userSdk.getService().findUserByUuid(uuid);
            if (!userUserSysResult.isSuccess()) {
                throw new BusinessException(ErrorCodeEnum.RETURN_ERROR);
            }
            Long userId = userUserSysResult.getData().getId();
            repayOrderQuery.setUserId(userId);
        }

        return xyqbService.findRepayOrders(repayOrderQuery);
    }

    @Override
    public JsonResult queryRepayInfo(RepayOrderInfoQuery repayOrderQuery) {
        // 参数校验
        if (Objects.isNull(repayOrderQuery)) {
            log.error("查询还款信息,请求参数 repayOrderQuery 为空");
            return JsonResult.buildErrorStateResult(ErrorCodeEnum.PARAM_ERROR.getMessage(), ErrorCodeEnum.PARAM_ERROR.getCode());
        }


        if (Objects.isNull(repayOrderQuery.getLoanId())) {
            log.error("查询还款信息,请求参数 loanId 不能为空");
            return JsonResult.buildErrorStateResult("借款订单号不能为空", ErrorCodeEnum.RETURN_ERROR.getCode());
        }

        Long loanId = repayOrderQuery.getLoanId();
        RepayInfoResult repayInfoResult = new RepayInfoResult();

//        // 处理用户信息
//        OrderQueryParam orderQueryParam = new OrderQueryParam();
//        orderQueryParam.setLoanId(loanId);
//        JsonResult userJsonResult = userService.findUserInfoByOrderParam(orderQueryParam);
//        if (Objects.isNull(userJsonResult)
//                || !userJsonResult.isSuccess()) {
//            log.error("根据loanId查不到用户信息");
//            return JsonResult.buildErrorStateResult("该笔借款申请号查询不到用户信息", ErrorCodeEnum.PARAM_ERROR.getCode());
//        }
//
//        UserBasicInfo userbasicinfo = (UserBasicInfo) userJsonResult.getData();
//        repayInfoResult.setUserInfo(userbasicinfo);


        //处理还款信息
        //String repayInfoStr = xyqbService.queryRepayInfo(repayOrderQuery);
        //todo 替换中台接口
        String repayInfoStr = sidecarService.queryRepayInfo(repayOrderQuery);
        log.info("[查询xyqb返回还款信息],repayInfoStr={}", repayInfoStr);
        if (StringUtils.isBlank(repayInfoStr)) {
            log.error("[查询xyqb返回还款信息],返回结果为null");
            return JsonResult.buildErrorStateResult(ErrorCodeEnum.RETURN_ERROR.getMessage(), ErrorCodeEnum.RETURN_ERROR.getCode());
        }

        MoResult<List<XyqbRepayInfo>> xyqbRepayInfoResult;
        try {
            Type jsonType = new com.google.gson.reflect.TypeToken<MoResult<List<XyqbRepayInfo>>>() {
            }.getType();
            xyqbRepayInfoResult = Constant.GSON.fromJson(repayInfoStr, jsonType);
        } catch (Exception e) {
            log.error("[还款信息转换异常]", e);
            return JsonResult.buildErrorStateResult(ErrorCodeEnum.RETURN_ERROR.getMessage(), ErrorCodeEnum.RETURN_ERROR.getCode());
        }

        if (!xyqbRepayInfoResult.isSuccess()) {
            return JsonResult.buildErrorStateResult(ErrorCodeEnum.RETURN_ERROR.getMessage(), ErrorCodeEnum.RETURN_ERROR.getCode());
        }


//        repayInfoResult.setRepaymentList(xyqbRepayInfoResult.getData());
        log.info("[查询还款信息]，返回 repayInfoResult={}", repayInfoResult);
        return JsonResult.buildSuccessResult("处理成功", xyqbRepayInfoResult.getData());
    }

    @Override
    public JsonResult queryRepayOptRecords(String businessFlowNo) {
        log.info("[查询还款操作记录][queryRepayOptRecords],请求参数:businessFlowNo={}", businessFlowNo);
        if (StringUtils.isBlank(businessFlowNo)) {
            log.error("查询还款操作记录,流水号为空");
            return JsonResult.buildErrorStateResult(ErrorCodeEnum.PARAM_ERROR.getMessage(), ErrorCodeEnum.PARAM_ERROR.getCode());
        }

        //发起xyqb查询
        //String optRecordsStr = xyqbService.queryRepayOptRecords(businessFlowNo);
        //todo 替换中台接口
        String optRecordsStr = sidecarService.queryRepayOptRecords(businessFlowNo);
                log.info("[查询xyqb还款操作记录],optRecordsStr={}", optRecordsStr);
        if (StringUtils.isBlank(optRecordsStr)) {
            log.error("[查询xyqb还款操作记录],返回结果为null");
            return JsonResult.buildErrorStateResult(ErrorCodeEnum.RETURN_ERROR.getMessage(), ErrorCodeEnum.RETURN_ERROR.getCode());
        }

        MoResult<List<RepayOptRecord>> repayOptRecordResult;
        try {
            Type jsonType = new com.google.gson.reflect.TypeToken<MoResult<List<RepayOptRecord>>>() {
            }.getType();
            repayOptRecordResult = Constant.GSON.fromJson(optRecordsStr, jsonType);
        } catch (Exception e) {
            log.error("[还款操作记录转换异常]", e);
            return JsonResult.buildErrorStateResult(ErrorCodeEnum.RETURN_ERROR.getMessage(), ErrorCodeEnum.RETURN_ERROR.getCode());
        }

        log.info("[查询还款操作记录]，返回 repayOptRecordResult={}", repayOptRecordResult);
        return JsonResult.buildSuccessResult("处理成功", repayOptRecordResult.getData());
    }

    @Override
    public JsonResult settleOperateQuery(EarlySettleOperateQueryReq req) {
        return koalaService.settleOperateQuery(req);
    }

    @Override
    public JsonResult earlySettleOperate(EarlySettleOperateReq req) {
        req.setCardNo(req.getCardNo().trim());
        return koalaService.earlySettleOperate(req);
    }

}
