package cn.quantgroup.customer.service.impl;

import cn.quantgroup.customer.common.adapter.LocalDateTypeAdapter;
import cn.quantgroup.customer.entity.User;
import cn.quantgroup.customer.enums.ErrorCodeEnum;
import cn.quantgroup.customer.exception.BusinessException;
import cn.quantgroup.customer.model.Tuple;
import cn.quantgroup.customer.model.kaordermapping.LoanOrderMapping;
import cn.quantgroup.customer.model.order.ActiveApplyOrder;
import cn.quantgroup.customer.model.order.ApplyOrder;
import cn.quantgroup.customer.model.order.SettleStatus;
import cn.quantgroup.customer.model.xyqbuser.UserBasicInfo;
import cn.quantgroup.customer.model.xyqbuser.UserCombination;
import cn.quantgroup.customer.repo.UserRepo;
import cn.quantgroup.customer.rest.param.applyorder.ApplyOrderQuery;
import cn.quantgroup.customer.rest.param.ordermapping.OrderQueryParam;
import cn.quantgroup.customer.rest.param.phone.ModifyPhoneAudit;
import cn.quantgroup.customer.rest.param.phone.ModifyPhoneFeedback;
import cn.quantgroup.customer.rest.param.phone.ModifyPhoneQuery;
import cn.quantgroup.customer.rest.param.phone.ModifyPhoneRecord;
import cn.quantgroup.customer.rest.param.user.UserCombinationParam;
import cn.quantgroup.customer.rest.param.user.UserQueryParam;
import cn.quantgroup.customer.rest.vo.JsonResult;
import cn.quantgroup.customer.rest.vo.MoResult;
import cn.quantgroup.customer.rest.vo.phone.ModifyPhoneNo;
import cn.quantgroup.customer.rest.vo.phone.UserModifyPhoneRecord;
import cn.quantgroup.customer.service.IIceService;
import cn.quantgroup.customer.service.IKaService;
import cn.quantgroup.customer.service.IUserService;
import cn.quantgroup.customer.service.IXyqbService;
import cn.quantgroup.customer.service.http.IHttpService;
import cn.quantgroup.customer.util.*;
import cn.quantgroup.riskcontrol.model.AuthenticationUserDetail;
import cn.quantgroup.tech.util.TechEnvironment;
import cn.quantgroup.user.retbean.XUser;
import cn.quantgroup.user.retbean.XUserDetail;
import cn.quantgroup.user.vo.UserSysResult;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.quantgroup.customer.constant.Constant.GSON;

@Slf4j
@Service("userService")
public class UserServiceImpl implements IUserService {

    @Value("${passportapi2.http}")
    private String userSysUrl;

    @Value("${mo-sidecar.http}")
    private String sidecarUrl;
    @Value("${kdsp.http.api}")
    private String kdspUrl;
    @Value("${kdsp-operation}")
    private String kdspOperationUrl;
    //新修改注销账户逻辑
    @Value("${vcc-talos.tjzimu.http}")
    private String talosHttp;





    private final UserRepo userRepo;
    private final IHttpService httpService;

    private final UserSdkImpl userSdk;

    private final IXyqbService xyqbService;
    private final IKaService kaService;
    private final IIceService iceService;

    @Autowired
    public UserServiceImpl(UserRepo userRepo, IHttpService httpService, UserSdkImpl userSdk, IXyqbService xyqbService, IKaService kaService, IIceService iceService) {
        this.userRepo = userRepo;
        this.httpService = httpService;
        this.userSdk = userSdk;
        this.xyqbService = xyqbService;
        this.kaService = kaService;
        this.iceService = iceService;
    }

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = userRepo.findByUsername(userName);
        if (user == null) {
            throw new UsernameNotFoundException("user: " + userName + " do not exist!");
        }
        return new AuthenticationUserDetail(user);
    }

    @Override
    public String modifyPhoneQuery(ModifyPhoneQuery modifyPhoneQuery) {
        String url = userSysUrl + "/v1/user/modify/phone_no";
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
                .create();
        Map param = gson.fromJson(gson.toJson(modifyPhoneQuery), Map.class);
        try {
            String response = httpService.get(url, param);
//            log.info("[user][query modify phone list] 请求业务系统返回值,modifyPhoneQuery:{},response={}", modifyPhoneQuery, response);
            if (StringUtils.isEmpty(response)) {
                log.error("[user][query modify phone list] 请求业务系统返回值为空,modifyPhoneQuery:{}", modifyPhoneQuery);
                return response;
            }

            JSONObject jsonObject = JSONObject.parseObject(response);
            JSONObject data = jsonObject.getJSONObject("data");
            if (data == null) {
                log.error("[user][query modify phone list] 请求业务系统返回值为空,modifyPhoneQuery:{}", modifyPhoneQuery);
                return response;
            }
            String content = data.getString("content");
            if (StringUtils.isEmpty(content)) {
                log.error("[user][query modify phone list] 请求业务系统返回值为空,modifyPhoneQuery:{}", modifyPhoneQuery);
                return response;
            }

            TypeReference<List<ModifyPhoneNo>> typeToken = new TypeReference<List<ModifyPhoneNo>>() {
            };
            List<ModifyPhoneNo> list = JSONTools.deserialize(content, typeToken);
            if (list == null) {
                return response;
            }

            list.stream().peek(it -> {
                it.setPrevPhoneNo(DesensitizeUtil.mobileDesensitization(it.getPrevPhoneNo()));
                it.setCurPhoneNo(DesensitizeUtil.mobileDesensitization(it.getCurPhoneNo()));
                it.setIdCard(DesensitizeUtil.idcardDesensitization(it.getIdCard()));
            }).collect(Collectors.toList());

            data.put("content", list);
            jsonObject.put("data", data);
            return JSONTools.serialize(jsonObject);
        } catch (Exception e) {
            log.error("[user][query modify phone list] 网络通讯异常,modifyPhoneQuery:{},ex:{}", modifyPhoneQuery, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }

    @Override
    public String modifyPhoneAudit(ModifyPhoneAudit modifyPhoneAudit) {
        String url = userSysUrl + "/v1/user/modify/phone_no/audit";
        Map param = GSON.fromJson(GSON.toJson(modifyPhoneAudit), Map.class);
        try {
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/json");
            String result = httpService.post(url, header, param);
            log.info("[user][query modify audit ] 请求业务系统返回值:{}", result);
            return result;
        } catch (Exception e) {
            log.error("[user][query modify audit ] 网络通讯异常,modifyPhoneAudit:{},ex:{}", modifyPhoneAudit, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }

    @Override
    public String deleteToken(ModifyPhoneAudit modifyPhoneAudit) {
        String url = kdspUrl + "/inner/kdsp/user/clearToken";
        Map param = GSON.fromJson(GSON.toJson(modifyPhoneAudit), Map.class);
        try {
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/json");
            String result = httpService.post(url, header, param);
            log.info("[user][query modify audit ] 请求业务系统返回值:{}", result);
            return result;
        } catch (Exception e) {
            log.error("[user][query modify audit ] 网络通讯异常,modifyPhoneAudit:{},ex:{}", modifyPhoneAudit, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }

    @Override
    public String modifyPhoneFeedback(ModifyPhoneFeedback modifyPhoneFeedback) {
        String url = userSysUrl + "/v1/user/modify/phone_no/{id}/feedback";
        try {
            String id = modifyPhoneFeedback.getId();
            url = url.replace("{id}", id);
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/json");
            String result = httpService.post(url, header, null);
            log.info("[user][query modify feedback ] 请求业务系统返回值:{}", result);
            return result;
        } catch (Exception e) {
            log.error("[user][query modify feedback ] 网络通讯异常,modifyPhoneFeedback:{},ex:{}", modifyPhoneFeedback, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }

    @Override
    public String findUuidByIdNo(String idNo) {
        String url = userSysUrl + "/innerapi/fetchUuid";
        try {
            Map<String, Object> param = Maps.newHashMap();
            param.put("idNo", idNo);
            String result = httpService.post(url, param);
            log.info("[user][query uuid by idNo ] 请求业务系统返回值:{}", result);
            JsonResult jsonResult = GSON.fromJson(result, JsonResult.class);
            Object uuid = jsonResult.getData();
            return String.valueOf(uuid);
        } catch (Exception e) {
            log.error("[user][query uuid by idNo ] 网络通讯异常,idNo:{},ex:{}", idNo, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }


    @Override
    public JsonResult<UserBasicInfo> findUserInfo(UserQueryParam userQueryParam) {
        final String LOG_PRE = "UserServiceImpl.findUserInfo";
        log.info("{} 查询用户信息 userCombinationParam={}", LOG_PRE, userQueryParam);

        //通过userId查询
        if (Objects.nonNull(userQueryParam.getUserId())) {
            log.info("{} 通过userId查询 userId={}", LOG_PRE, userQueryParam.getUserId());
            UserSysResult<XUser> userByUserId = userSdk.getService().findUserByUserId(userQueryParam.getUserId());
            UserSysResult<XUserDetail> userDetailByUserId = userSdk.getService().findUserDetailByUserId(userQueryParam.getUserId());
            return getUserBasicInfoResult(userByUserId, userDetailByUserId);
        }

        if (StringUtils.isNotBlank(userQueryParam.getPhoneNo())) {
            log.info("{} 通过phoneNo查询 phoneNo={}", LOG_PRE, userQueryParam.getPhoneNo());
            UserSysResult<XUser> userByPhoneNo = userSdk.getService().findUserByPhoneNo(userQueryParam.getPhoneNo());
            UserSysResult<XUserDetail> userDetailByPhone = userSdk.getService().findUserDetailByPhone(userQueryParam.getPhoneNo());
            //根据传入的身份证和查询出的用户信息中身份证进行比较,如果不一致返回查询失败
            if (StringUtils.isNotEmpty(userQueryParam.getIdNo()) && userDetailByPhone.getData() != null) {
                XUserDetail xUserDetail = userDetailByPhone.getData();
                String idNo = xUserDetail.getIdNo();
                if (StringUtils.isNotEmpty(idNo)) {
                    idNo = idNo.trim().toUpperCase();
                }

                String paramIdNo = userQueryParam.getIdNo().trim().toUpperCase();
                if (!paramIdNo.equals(idNo)) {
                    return JsonResult.buildErrorStateResult("无有效查询参数", null);
                }
            }
            return getUserBasicInfoResult(userByPhoneNo, userDetailByPhone);
        }

        if (StringUtils.isNotBlank(userQueryParam.getUuid())) {
            log.info("{} 通过uuid查询 uuid={}", LOG_PRE, userQueryParam.getUuid());
            UserSysResult<XUser> xUserByUuid = userSdk.getService().findUserByUuid(userQueryParam.getUuid());
            Object jsonResultData = getJsonResultData(xUserByUuid);
            if(Objects.isNull(jsonResultData)){
                log.error("{} 用户不存在 uuid={}",LOG_PRE,userQueryParam.getUuid());
                return JsonResult.buildErrorStateResult("用户不存在",1L);
            }
            if (jsonResultData instanceof XUser) {
                XUser xUser = (XUser) jsonResultData;
                UserSysResult<XUserDetail> userDetailByPhone = userSdk.getService().findUserDetailByPhone(xUser.getPhoneNo());
                return getUserBasicInfoResult(xUserByUuid, userDetailByPhone);
            } else {
                return (JsonResult) jsonResultData;
            }

        }

        //通过身份证号获得
        if (StringUtils.isNotBlank(userQueryParam.getIdNo())) {
            //通过业务系统获得
            log.info("{} 通过phoneNo查询 idNo={}", LOG_PRE, userQueryParam.getIdNo());
            JsonResult userDetailResult = findUserDetailByIdNo(userQueryParam.getIdNo());
            /*
            if (StringUtils.isNotEmpty(userQueryParam.getPhoneNo()) && userDetailResult.isSuccess() && userDetailResult.getData() != null) {
                UserBasicInfo userBasicInfo = (UserBasicInfo) userDetailResult.getData();
                String phoneNo = userBasicInfo.getPhoneNo();
                String paramPhoneNo = userQueryParam.getPhoneNo();
                if (!paramPhoneNo.equals(phoneNo)) {
                    return JsonResult.buildErrorStateResult("无有效查询参数", null);
                }
            }
            */
            return userDetailResult;
        }

        return JsonResult.buildErrorStateResult("无有效查询参数", null);
    }


    private JsonResult findUserDetailByIdNo(String idNo) {
        String url = userSysUrl + "/innerapi/user_detail/fuzzyQuery";
        try {
            Map<String, Object> param = Maps.newHashMap();
            param.put("idNo", idNo);
            String result = httpService.post(url, param);

            if (StringUtils.isBlank(result)) {
                log.error("UserServiceImpl.findUserDetailByIdNo请求业务系统返回值:{}", result);
                return JsonResult.buildErrorStateResult(ErrorCodeEnum.RETURN_ERROR.getMessage(), ErrorCodeEnum.RETURN_ERROR.getCode());
            }

            TypeReference<JsonResult<List<XUserDetail>>> typeToken = new TypeReference<JsonResult<List<XUserDetail>>>() {
            };

            JsonResult<List<XUserDetail>> jsonResult = JSONTools.deserialize(result, typeToken);
            if (!jsonResult.isSuccess()) {
                log.error("UserServiceImpl.findUserDetailByIdNo 查询失败 result={}", jsonResult);
                return jsonResult;
            }

            List<XUserDetail> xUserDetails = jsonResult.getData();

            if (xUserDetails.size() > 1) {
                return JsonResult.buildErrorStateResult("身份证查询返回多条数据，请用其他参数查询", null);
            }
            if (xUserDetails.size() == 0) {
                return JsonResult.buildErrorStateResult("不存在相关用户信息", null);
            }

            XUserDetail userDetail = xUserDetails.get(0);
            UserBasicInfo userBasicInfo = new UserBasicInfo();
            String createdAt = DateUtil.format(userDetail.getCreatedAt(), DateUtil.DATE_FORMAT_1);
            userBasicInfo.setCreatedAt(createdAt);
            userBasicInfo.setGender(userDetail.getGender().getName());
            userBasicInfo.setIdNo(DesensitizeUtil.idNoMark(userDetail.getIdNo()));
            userBasicInfo.setName(userDetail.getName());
            userBasicInfo.setPhoneNo(DesensitizeUtil.phoneMark(userDetail.getPhoneNo()));
            userBasicInfo.setPhoneNumber(userDetail.getPhoneNo());
            userBasicInfo.setUserId(userDetail.getUserId());
            UserSysResult<XUser> userByUserId = userSdk.getService().findUserByUserId(userDetail.getUserId());
            if (userByUserId != null && userByUserId.isSuccess()) {
                Boolean enable = userByUserId.getData().getEnable();
                userBasicInfo.setStatus(enable == null ? "未知" : (enable ? "正常" : "封禁"));
            }
            return JsonResult.buildSuccessResult(null, userBasicInfo);

        } catch (Exception e) {
            log.error("[user][findUserDetailByIdNo ] 网络通讯异常,idNo:{},ex:{}", idNo, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }

    }

    private JsonResult getUserBasicInfoResultNew(UserSysResult<XUser> xUserUserSysResult) {
        Object xUserData = getJsonResultData(xUserUserSysResult);
        UserBasicInfo userBasicInfo = new UserBasicInfo();

        if (Objects.isNull(xUserData)) {
            log.error(" 用户不存在 userSysResult={}", xUserData);
            return JsonResult.buildErrorStateResult("用户不存在", xUserData);
        }

        if (xUserData instanceof XUser) {
            XUser xUser = (XUser) xUserData;
            userBasicInfo.setUserId(xUser.getId());
            userBasicInfo.setPhoneNo(DesensitizeUtil.phoneMark(xUser.getPhoneNo()));
            userBasicInfo.setPhoneNumber(xUser.getPhoneNo());
            String createAt = DateUtil.format(xUser.getCreatedAt(), DateUtil.DATE_FORMAT_1);
            userBasicInfo.setCreatedAt(createAt);
            Boolean enable = xUser.getEnable();
            userBasicInfo.setStatus(enable == null ? "未知" : (enable ? "正常" : "封禁"));
        }else{
            log.error("查询用户失败 user={}",xUserData);
            return (JsonResult) xUserData;
        }
        return JsonResult.buildSuccessResult(null, userBasicInfo);
    }

    private JsonResult getUserBasicInfoResult(UserSysResult<XUser> xUserUserSysResult, UserSysResult<XUserDetail> detailUserSysResult) {
        Object detailUser = getJsonResultData(detailUserSysResult);
        Object xUserData = getJsonResultData(xUserUserSysResult);
        UserBasicInfo userBasicInfo = new UserBasicInfo();

        if (Objects.isNull(xUserData)) {
            log.error(" 用户不存在 userSysResult={}", xUserData);
            return JsonResult.buildErrorStateResult("用户不存在", xUserData);
        }

        if (xUserData instanceof XUser) {
            XUser xUser = (XUser) xUserData;
            userBasicInfo.setUserId(xUser.getId());
            userBasicInfo.setPhoneNo(DesensitizeUtil.phoneMark(xUser.getPhoneNo()));
            userBasicInfo.setPhoneNumber(xUser.getPhoneNo());
            String createAt = DateUtil.format(xUser.getCreatedAt(), DateUtil.DATE_FORMAT_1);
            userBasicInfo.setCreatedAt(createAt);
            Boolean enable = xUser.getEnable();
            userBasicInfo.setStatus(enable == null ? "未知" : (enable ? "正常" : "封禁"));
        }else{
            log.error("查询用户失败 user={}",xUserData);
            return (JsonResult) xUserData;
        }

        if (detailUser instanceof XUserDetail) {
            XUserDetail userDetail = (XUserDetail) detailUser;
            userBasicInfo.setGender(userDetail.getGender().getName());
            userBasicInfo.setIdNo(DesensitizeUtil.idNoMark(userDetail.getIdNo()));
            userBasicInfo.setName(userDetail.getName());
        }
        return JsonResult.buildSuccessResult(null, userBasicInfo);
    }

    private Object getJsonResultData(UserSysResult userSysResult) {
        String logPre = "UserServiceImpl.getJsonResultData";
        log.info("{} 转换为对象 userSysResult={}", logPre, userSysResult);

        if (Objects.isNull(userSysResult)) {
            log.error("{} 转换参数为空 userSysResult={}", logPre, userSysResult);
            return JsonResult.buildErrorStateResult("远程调用结果为空", null);
        }

        if (!userSysResult.isSuccess()) {
            log.error("{} 远程调用失败 userSysResult={}", logPre, userSysResult);
            return JsonResult.buildErrorStateResult("查询用户失败", userSysResult.getData());
        }


        return userSysResult.getData();
    }

    /**
     * 验证参数
     * 分两类 订单类查询参数  用户类查询参数
     * 每类参数只能有一个 如 订单类参数只能有一个（有申请订单号就不能有借款订单号和渠道订单号）   用户类同理
     *
     * @param userCombinationParam
     * @return Tuple<Boolean, String> false 参数验证失败  value失败描述 true表示参数验证成功 value 表示使用哪类参数 1 表示order 2 表示user
     */
    private Tuple<Boolean, String> validate(UserCombinationParam userCombinationParam) {
        log.info("综合查询参数验证 param={}", userCombinationParam);
        Tuple<Boolean, String> result = new Tuple<>();
        int userParam = 0;
        int orderParam = 0;
        result.setKey(false);
        if (Objects.isNull(userCombinationParam)) {
            result.setValue("对象为空");
            return result;
        }

        if (StringUtils.isNotBlank(userCombinationParam.getChannelOrderNo())) {
            if (Objects.isNull(userCombinationParam.getChannelId())) {
                result.setValue("查询参数渠道订单号和渠道号要同时存在");
                return result;
            }
            orderParam++;
        }

        if (StringUtils.isNotBlank(userCombinationParam.getIdNo())) {
            if (IdcardUtils.validateIdCard18(userCombinationParam.getIdNo()) || IdcardUtils.validateIdCard15(userCombinationParam.getIdNo())) {
                userParam++;
            } else {
                result.setValue("身份证号格式有误");
                return result;
            }
        }

        if (StringUtils.isNotBlank(userCombinationParam.getOrderNo())) {
            orderParam++;
        }

        if (Objects.nonNull(userCombinationParam.getUserId())) {
            userParam++;
        }

        if (StringUtils.isNotBlank(userCombinationParam.getPhoneNo())) {
            if (ValidationUtil.validatePhoneNo(userCombinationParam.getPhoneNo())) {
                userParam++;
            } else {
                result.setValue("手机号格式错误");
                return result;
            }
        }

        if (StringUtils.isNotBlank(userCombinationParam.getUuid())) {
            userParam++;
        }

        if (!Objects.isNull(userCombinationParam.getLoanId())) {
            orderParam++;
        }

        //参数个数验证
        if (orderParam + userParam == 0) {
            result.setValue("参数不能为空");
            return result;
        } else if (orderParam + userParam > 1) {
            result.setValue("只能使用渠道号和渠道订单号组合查询");
            return result;
        }


        //分类参数验证 订单参数优先
        if (orderParam == 1) {
            result.setKey(true);
            result.setValue("1");
            return result;
        }
        if (userParam == 1) {
            result.setKey(true);
            result.setValue("2");
            return result;
        }
        result.setValue("只能通过单一条件查询");
        return result;
    }


    @Override
    public JsonResult findUserCombination(UserCombinationParam userCombinationParam) {
        String logPre = "UserServiceImpl.findUserCombination";
        log.info("{},综合查询 userCombinationParam={}", logPre, userCombinationParam);
        Tuple<Boolean, String> tuple = validate(userCombinationParam);

        if (!tuple.getKey()) {
            log.error("{},参数验证失败，{}", logPre, tuple.getValue());
            return JsonResult.buildErrorStateResult(tuple.getValue(), null);
        }
        JsonResult<UserBasicInfo> userInfo;
        JsonResult<ApplyOrder> applyOrder;
        if ("1".equals(tuple.getValue())) {
            //订单参数查询
            OrderQueryParam orderQueryParam = new OrderQueryParam();
            orderQueryParam.setApplyOrderNo(userCombinationParam.getOrderNo());
            orderQueryParam.setLoanId(userCombinationParam.getLoanId());
            orderQueryParam.setChannelId(userCombinationParam.getChannelId());
            orderQueryParam.setChannelOrderNo(userCombinationParam.getChannelOrderNo());
            userInfo = this.findUserInfoByOrderParam(orderQueryParam);
            if (!userInfo.isSuccess()) {
                log.error("{} 查询用户失败 result={}", logPre, userInfo);
                return userInfo;
            }
            applyOrder = this.findApplyOrders(orderQueryParam);
        } else {
            //用户参数查询
            UserQueryParam userQueryParam = new UserQueryParam();
            userQueryParam.setIdNo(userCombinationParam.getIdNo());
            userQueryParam.setPhoneNo(userCombinationParam.getPhoneNo());
            userQueryParam.setUserId(userCombinationParam.getUserId());
            userQueryParam.setUuid(userCombinationParam.getUuid());
            userInfo = this.findUserInfo(userQueryParam);
            if (!userInfo.isSuccess()) {
                log.error("{} 查询用户失败 result={}", logPre, userInfo);
                return userInfo;
            }
            userQueryParam.setUserId(userInfo.getData().getUserId());
            applyOrder = this.findApplyOrders(userQueryParam);
        }


        if (!applyOrder.isSuccess()) {
            log.error("{} 查询申请订单失败 result={}", logPre, applyOrder);
            return applyOrder;
        }

        List<ActiveApplyOrder> activeApplyOrders = applyOrder.getData().getActiveOrders();
        List<ActiveApplyOrder> invalidApplyOrders = applyOrder.getData().getInvalidOrders();
        if (CollectionUtils.isNotEmpty(activeApplyOrders)) {
            //通过申请订单号获得渠道订单号
            List<String> applyOrderNoList = activeApplyOrders.stream().map(e -> e.getApplyOrderNo()).distinct().collect(Collectors.toList());
            JsonResult<Map<String, String>> mapJsonResult = kaService.findChannelOrderNosByApplyOrderNos(applyOrderNoList);
            if (mapJsonResult.isSuccess()) {
                Map<String, String> data = mapJsonResult.getData();
                activeApplyOrders.forEach(e -> e.setChannelOrderNo(data.get(e.getApplyOrderNo())));
            }
            // 添加能否申请结清证明
            JsonResult<List<SettleStatus>> settleFlagResult = null;
            if (CollectionUtils.isNotEmpty(activeApplyOrders)) {
                settleFlagResult = iceService.findSettleFlag(activeApplyOrders.stream().filter(it-> it.getLoanId() != null).map(ActiveApplyOrder::getLoanId).collect(Collectors.toList()));
            }
            if (settleFlagResult != null && settleFlagResult.isCodeSuccess()) {
                for (ActiveApplyOrder activeOrder : activeApplyOrders) {
                    for (SettleStatus settleStatus : settleFlagResult.getData()) {
                        if(settleStatus.getLoanId().equals(activeOrder.getLoanId())) {
                            activeOrder.setSettleFlag(settleStatus.getProofProgress());
                        }
                    }
                }
            }
        }

        if (CollectionUtils.isNotEmpty(invalidApplyOrders)) {
            //通过申请订单号获得渠道订单号
            List<String> applyOrderNoList = invalidApplyOrders.stream().map(e -> e.getApplyOrderNo()).distinct().collect(Collectors.toList());
            JsonResult<Map<String, String>> mapJsonResult = kaService.findChannelOrderNosByApplyOrderNos(applyOrderNoList);
            if (mapJsonResult.isSuccess()) {
                Map<String, String> data = mapJsonResult.getData();
                invalidApplyOrders.forEach(e -> e.setChannelOrderNo(data.get(e.getApplyOrderNo())));
            }
        }
        UserBasicInfo userBasicInfo = userInfo.getData();
        UserCombination userCombination = new UserCombination();
        userCombination.setUserInfo(userBasicInfo);
        userCombination.setApplyOrder(applyOrder.getData());
        return JsonResult.buildSuccessResult("", userCombination);


    }


    //订单信息综合查询
    private JsonResult findApplyOrders(OrderQueryParam orderQueryParam) {
        String logPre = "UserService.findApplyOrders";
        log.info("{} 通过订单参数查询申请订单 orderQueryParam={}", logPre, orderQueryParam);
        ApplyOrderQuery applyOrderQuery = new ApplyOrderQuery();
        Long loanId = orderQueryParam.getLoanId();
        String applyNo = orderQueryParam.getApplyOrderNo();
        //申请订单查询（如果查询参数是渠道订单号）将渠道订单号转为借款订单号和申请订单号
        if (StringUtils.isNotBlank(orderQueryParam.getChannelOrderNo())) {
            JsonResult<LoanOrderMapping> orderMappingJsonResult = kaService.findOrderMapping(orderQueryParam);
            LoanOrderMapping data;
            if (!orderMappingJsonResult.isSuccess() || Objects.isNull(data = orderMappingJsonResult.getData())) {
                log.error("{} 根据渠道号查询orderMapping失败 result={}", logPre, orderMappingJsonResult);
                return orderMappingJsonResult;
            }
            loanId = data.getLoanId();
            applyNo = data.getApplyNo();
        }
        applyOrderQuery.setLoanId(loanId);
        applyOrderQuery.setOrderNo(applyNo);
        //申请订单查询
        //JsonResult<ApplyOrder> applyOrders = xyqbService.findApplyOrders(applyOrderQuery);
        //todo 替换中台接口
        JsonResult<ApplyOrder> applyOrders = iceService.findApplyOrders(applyOrderQuery);
//        // 添加能否结清标记
//        if (applyOrders.isSuccess()) {
//            JsonResult<Map<Long, Integer>> settleFlagResult = null;
//            List<ActiveApplyOrder> activeOrders = applyOrders.getData().getActiveOrders();
//            if (CollectionUtils.isNotEmpty(activeOrders)) {
//                settleFlagResult = iceService.findSettleFlag(activeOrders.stream().filter(it-> it.getLoanId() != null).map(ActiveApplyOrder::getLoanId).collect(Collectors.toList()));
//            }
//            if (settleFlagResult != null && settleFlagResult.isSuccess()) {
//                for (ActiveApplyOrder activeOrder : activeOrders) {
//                    Integer flag = settleFlagResult.getData().get(activeOrder.getLoanId());
//                    if (activeOrder.getLoanId() != null && flag != null) {
//                        activeOrder.setSettleFlag(flag);
//                    }
//                }
//            }
//        }
        return applyOrders;
    }

    //用户信息综合查询
    private JsonResult findApplyOrders(UserQueryParam userQueryParam) {
        String logPre = "UserServiceImpl.findApplyOrders";
        log.info("{} 通过用户参数查询申请订单 userQueryParam={}", logPre, userQueryParam);
        ApplyOrderQuery applyOrderQuery = new ApplyOrderQuery();
        applyOrderQuery.setUserId(userQueryParam.getUserId());
        //申请订单查询
        //JsonResult<ApplyOrder> applyOrders = xyqbService.findApplyOrders(applyOrderQuery);
        //todo 替换中台接口
        JsonResult<ApplyOrder> applyOrders = iceService.findApplyOrders(applyOrderQuery);
        return applyOrders;
    }

    @Override
    public JsonResult<UserBasicInfo> findUserInfoByOrderParam(OrderQueryParam orderQueryParam) {

        String logPre = "UserServiceImpl.findUserInfoByOrderParam";
        log.info("{} 订单参数查询用户信息 orderQueryParam={}", logPre, orderQueryParam);
        //渠道订单号需要有渠道号
        boolean channelParam = StringUtils.isNotBlank(orderQueryParam.getChannelOrderNo()) && Objects.nonNull(orderQueryParam.getChannelId());
        if (channelParam) {
            //通过ka获得userId然后通过userId查询
            JsonResult<LoanOrderMapping> orderMapping = kaService.findOrderMapping(orderQueryParam);
            if (!orderMapping.isSuccess()) {
                log.error("{} 查询orderMapping失败 param={} result={}", logPre, orderQueryParam, orderMapping);
                return JsonResult.buildErrorStateResult("查询失败", null);
            }
            if (Objects.isNull(orderMapping.getData())) {
                return JsonResult.buildErrorStateResult("请确认搜索条件后再查询", null);
            }
            Long qgUserId = orderMapping.getData().getQgUserId();
            UserSysResult<XUser> userByUserId = userSdk.getService().findUserByUserId(qgUserId);
            UserSysResult<XUserDetail> userDetailByUserId = userSdk.getService().findUserDetailByUserId(qgUserId);
            return getUserBasicInfoResult(userByUserId,userDetailByUserId);
        }
        if (Objects.nonNull(orderQueryParam.getLoanId()) ||
                StringUtils.isNotBlank(orderQueryParam.getApplyOrderNo())) {
            Long loanId = orderQueryParam.getLoanId();
            String applyOrderNo = orderQueryParam.getApplyOrderNo();
            ApplyOrderQuery applyOrderQuery = new ApplyOrderQuery();
            applyOrderQuery.setOrderNo(applyOrderNo);
            applyOrderQuery.setLoanId(loanId);
            //申请订单查询
            //JsonResult<ApplyOrder> applyOrder = xyqbService.findApplyOrders(applyOrderQuery);
            //todo 替换中台接口
            JsonResult<ApplyOrder> applyOrder = iceService.findApplyOrders(applyOrderQuery);
            if (!applyOrder.isSuccess()) {
                log.error("{} 获得申请订单失败 applyOrderQuery={} result={}", logPre, applyOrderQuery, applyOrder);
                return JsonResult.buildErrorStateResult("查询失败", null);
            }
            if (CollectionUtils.isEmpty(applyOrder.getData().getActiveOrders())
                    && CollectionUtils.isEmpty(applyOrder.getData().getInvalidOrders())) {
                return JsonResult.buildErrorStateResult("请确认搜索条件后再查询", null);
            }

            Long userId;
            if(CollectionUtils.isNotEmpty(applyOrder.getData().getActiveOrders())){
                userId = applyOrder.getData().getActiveOrders().get(0).getUserId();
            }else {
                userId = applyOrder.getData().getInvalidOrders().get(0).getUserId();
            }
            UserSysResult<XUser> userByUserId = userSdk.getService().findUserByUserId(userId);
            UserSysResult<XUserDetail> userDetailByUserId = userSdk.getService().findUserDetailByUserId(userId);
            return getUserBasicInfoResult(userByUserId,userDetailByUserId);
        }

        //走到这里申请订单号和借款订单号都为空， 渠道订单号和渠道号至少一个为空
        if (StringUtils.isNotBlank(orderQueryParam.getChannelOrderNo()) || Objects.nonNull(orderQueryParam.getChannelId())) {
            log.error("{} 渠道订单号和渠道号只输入了一个 param={} ", logPre, orderQueryParam);
            return JsonResult.buildErrorStateResult("渠道订单号和渠道号要同时输入", null);
        }
        return JsonResult.buildErrorStateResult("参数全部为空", null);
    }

    //旧逻辑，先调用sidecar系统，再调用用户中心
    @Override
    public MoResult<String> passwordRest(String phoneNo) {
        String url = sidecarUrl + "/middle_office/kefu/password/reset";
        try {
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/x-www-form-urlencoded");
            Map param = Maps.newHashMap();
            param.put("phone", phoneNo);
            String result = httpService.post(url, header, param);
            MoResult moResult = GSON.fromJson(result, MoResult.class);
            log.info("[user][passwordRest] 请求业务系统返回值:{}", result);
            return moResult;
        } catch (Exception e) {
            log.error("[user][passwordRest] 网络通讯异常,phoneNo:{},ex:{}", phoneNo, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }
    //新逻辑，直接调用用户中心，不经过sidecar系统
    @Override
    public JsonResult passwordRestNew(String phone) {
        try {
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/x-www-form-urlencoded");
            Map param = Maps.newHashMap();
            param.put("phone", phone);
            String userUrl = userSysUrl + "/innerapi/user/password/reset";
            String userResult = httpService.post(userUrl, header, param);
            JSONObject userJsonObject =null;
            if(userResult != null){
                userJsonObject = JSONObject.parseObject(userResult);
                String userBusinessCode = userJsonObject.getString("businessCode");
                if("0000".equals(userBusinessCode)){
                   return JsonResult.buildSuccessResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
                }else{
                    return JsonResult.buildErrorStateResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
                }
            }else{
                return JsonResult.buildErrorStateResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
            }
        } catch (Exception e) {
            log.error("[user][passwordRestNew] 网络通讯异常,phone:{},ex:{}", phone, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }
    //旧逻辑
    @Override
    public MoResult<Boolean> modifyAccountStatusDisable(Long userId) {
        String url = sidecarUrl + "/middle_office/kefu/user/disable";
        try {
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/x-www-form-urlencoded");
            Map param = Maps.newHashMap();
            param.put("userId", String.valueOf(userId));
            String result = httpService.post(url, header, param);
            MoResult moResult = GSON.fromJson(result, MoResult.class);
            log.info("[user][modifyAccountStatus] 请求业务系统返回值:{}", result);
            return moResult;
        } catch (Exception e) {
            log.error("[user][modifyAccountStatus] 网络通讯异常,userId:{},ex:{}", userId, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }
    //新逻辑,直接调用kdsp，方便维护
/*    @Override
    public JsonResult modifyAccountStatusDisableNew(Long userId) {
        try {
            //调用天津自牧finance-gateway接口,将电商userid,转换为金融userid
            String url = talosHttp + "/api/inner/kdsp/hasBusiness";
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/x-www-form-urlencoded");
            Map param = Maps.newHashMap();
            param.put("userId", userId);
            String result = httpService.get(url,header,param);
            if(result!=null){
                JSONObject jsonObject = JSONObject.parseObject(result);;
                String businessCode = jsonObject.getString("businessCode");
                //返回信息
                JSONObject userJsonObject = null;
                if("0000".equals(businessCode)){
                    //调用用户中心，将账户状态更新为冻结
                    Map param1 = Maps.newHashMap();
                    param1.put("userId", userId.toString());
                    String userUrl = userSysUrl + "/innerapi/user/disable";
                    String userResult = httpService.post(userUrl, header, param1);
                    userJsonObject = JSONObject.parseObject(userResult);
                    String userBusinessCode = userJsonObject.getString("businessCode");
                    if("0000".equals(userBusinessCode)){
                        return JsonResult.buildSuccessResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
                    }else{
                        return JsonResult.buildErrorStateResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
                    }
                }else{
                    return JsonResult.buildErrorStateResult(jsonObject.getString("msg"),jsonObject.get("data"));
                }
            }else{
                return JsonResult.buildErrorStateResult("调用第三方接口报错",null);
            }
        } catch (Exception e) {
            log.error("[user][modifyAccountStatusDisableNew] 网络通讯异常,userId:{},ex:{}", userId, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }*/

    //新逻辑
    @Override
    public JsonResult modifyAccountStatusDisableNew(Long userId, String reason, HttpServletRequest request) {
        try {
            if (StringUtils.isBlank(reason)) {
                return JsonResult.buildErrorStateResult("冻结原因不能为空");
            }
            if (reason.length() > 10) {
                return JsonResult.buildErrorStateResult("冻结原因不能大于10个字");
            }
            //调用kdsp接口校验是否有在途数据（订单在途+金融在途）
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/x-www-form-urlencoded");
            header.put("qg-tenant-id", "560761");
            String kdsp = kdspUrl  + "/api/kdsp/user/customer/validate/can-logged-off";
            Map param = Maps.newHashMap();
            param.put("userId", userId.toString());
            param.put("tenantId", "560761");
            String result = httpService.post(kdsp, header, param);
            log.info("[user][modifyAccountStatusDisableNew] 请求业务系统返回值:{}", result);
            if(result!=null){
                JSONObject jsonObject = JSONObject.parseObject(result);;
                String businessCode = jsonObject.getString("businessCode");
                //返回信息
                if("0000".equals(businessCode)){
                    String data = jsonObject.getString("data");
                    JSONObject dataObject = JSONObject.parseObject(data);
                    Integer userStatus = dataObject.getInteger("userStatus");
                    String message = dataObject.getString("message");
                    //1.不支持注销  2 可以注销
                    if(userStatus!=null && userStatus.intValue() == 1){
                        return JsonResult.buildErrorStateResult(message);
                    }
                    //调用用户中心，将账户状态更新为冻结
                    Map param1 = Maps.newHashMap();
                    param1.put("userId", userId.toString());
                    param1.put("reason", reason);
                    String userUrl = userSysUrl + "/innerapi/user/disable";
                    header.put("Access-Token", request.getHeader("Access-Token"));
                    String userResult = httpService.post(userUrl, header, param1);
                    log.info("[user][modifyAccountStatusDisableNew] 请求业务系统返回值:{}", userResult);
                    JSONObject userJsonObject = JSONObject.parseObject(userResult);
                    String userBusinessCode = userJsonObject.getString("businessCode");
                    if("0000".equals(userBusinessCode)){
                        return JsonResult.buildSuccessResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
                    }else{
                        return JsonResult.buildErrorStateResult("调用用户中心接口报错，注销失败");
                    }
                }else{
                    return JsonResult.buildErrorStateResult("调用电商接口报错，注销失败");
                }
            }else{
                return JsonResult.buildErrorStateResult("调用电商接口报错，注销失败");
            }
        } catch (Exception e) {
            log.error("[user][modifyAccountStatusDisableNew] 网络通讯异常,userId:{},ex:{}", userId, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }

    /**
     * 真正的注销账户，删除账户信息
     * @param userId
     * @return
     */
    @Override
    public JsonResult deleteAccount(Long userId) {
        try{
            //调用kdsp接口
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/x-www-form-urlencoded");
            header.put("qg-tenant-id", "560761");
            String kdsp = kdspUrl  + "/api/kdsp/user/customer/logged-off";
            Map param = Maps.newHashMap();
            param.put("userId", userId.toString());
            param.put("tenantId", "560761");
            String result = httpService.post(kdsp, header, param);
            log.info("[user][modifyAccountStatusDisableNew] 请求业务系统返回值:{}", result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String businessCode = jsonObject.getString("businessCode");
            if(!"0000".equals(businessCode)){
                return JsonResult.buildErrorStateResult("调用电商注销接口报错，注销失败");
            }else{
                String data = jsonObject.getString("data");
                JSONObject dataObject = JSONObject.parseObject(data);;
                Integer userStatus = dataObject.getInteger("userStatus");
                //不能注销
                if(userStatus !=null && userStatus.intValue() ==1){
                    String message = dataObject.getString("message");
                    return JsonResult.buildErrorStateResult(message);
                }
                return JsonResult.buildSuccessResult("注销成功",data);
            }
        }catch (Exception e) {
            log.error("[user][modifyAccountStatusDisableNew] 网络通讯异常,userId:{},ex:{}", userId, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }

    @Override
    public MoResult<Boolean> modifyAccountStatusActive(Long userId) {
        String url = sidecarUrl + "/middle_office/kefu/user/active";
        try {
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/x-www-form-urlencoded");
            Map param = Maps.newHashMap();
            param.put("userId", String.valueOf(userId));
            String result = httpService.post(url, header, param);
            MoResult moResult = GSON.fromJson(result, MoResult.class);
            log.info("[user][modifyAccountStatusActive] 请求业务系统返回值:{}", result);
            return moResult;
        } catch (Exception e) {
            log.error("[user][modifyAccountStatusActive] 网络通讯异常,userId:{},ex:{}", userId, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }
    //新逻辑，不通过sidecar，直接调用用户中心
    @Override
    public JsonResult modifyAccountStatusActiveNew(Long userId, HttpServletRequest request) {
        try {
            if(userId == null || "0".equals(userId.toString())){
                return JsonResult.buildErrorStateResult("userId非法",null);
            }
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/x-www-form-urlencoded");
            header.put("Access-Token", request.getHeader("Access-Token"));
            Map param = Maps.newHashMap();
            param.put("userId", userId.toString());
            String userUrl = userSysUrl + "/innerapi/user/active";
            String userResult = httpService.post(userUrl, header, param);
            JSONObject userJsonObject = null;
            if(userResult != null){
                userJsonObject = JSONObject.parseObject(userResult);
                String userBusinessCode = userJsonObject.getString("businessCode");
                if("0000".equals(userBusinessCode)){
                    return JsonResult.buildSuccessResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
                }else{
                    return JsonResult.buildErrorStateResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
                }
            }else{
                return JsonResult.buildErrorStateResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
            }
        } catch (Exception e) {
            log.error("[user][modifyAccountStatusActiveNew] 网络通讯异常,userId:{},ex:{}", userId, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }

    /**
     * 用户冻结解冻记录
     * @param userId
     * @param pageNo
     * @param pageSize
     * @param request
     * @return
     */
    @Override
    public JsonResult userStatusRecords(Long userId, int pageNo, int pageSize, HttpServletRequest request) {
        try {
            if(userId == null || "0".equals(userId.toString())){
                return JsonResult.buildErrorStateResult("userId非法",null);
            }
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/x-www-form-urlencoded");
            header.put("Access-Token", request.getHeader("Access-Token"));
            Map param = Maps.newHashMap();
            param.put("page", String.valueOf(pageNo));
            param.put("size", String.valueOf(pageSize));
            String userUrl = userSysUrl + "/innerapi/user/records/" + userId;
            String userResult = httpService.post(userUrl, header, param);
            JSONObject userJsonObject = null;
            if(userResult != null){
                userJsonObject = JSONObject.parseObject(userResult);
                String userBusinessCode = userJsonObject.getString("businessCode");
                if("0000".equals(userBusinessCode)){
                    return JsonResult.buildSuccessResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
                }else{
                    return JsonResult.buildErrorStateResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
                }
            }else{
                return JsonResult.buildErrorStateResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
            }
        } catch (Exception e) {
            log.error("[user][userRecords] 网络通讯异常,userId:{},ex:{}", userId, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }

    @Override
    public JsonResult modifyUserDetailNew(Long userId, String realName, String idNO) {
        try {
            if(userId == null || "0".equals(userId.toString())){
                return JsonResult.buildErrorStateResult("userId非法",null);
            }
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/x-www-form-urlencoded");
            Map param = Maps.newHashMap();
            param.put("name", realName);
            param.put("idNo", idNO);
            String userUrl = userSysUrl + "/innerapi/userDetail/reset/"+userId;
            String userResult = httpService.post(userUrl, header, param);
            JSONObject userJsonObject = null;
            if(userResult != null){
                userJsonObject = JSONObject.parseObject(userResult);
                String userBusinessCode = userJsonObject.getString("businessCode");
                if("0000".equals(userBusinessCode)){
                    return JsonResult.buildSuccessResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
                }else{
                    return JsonResult.buildErrorStateResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
                }
            }else{
                return JsonResult.buildErrorStateResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
            }
        } catch (Exception e) {
            log.error("[user][modifyUserDetailNew] 网络通讯异常,userId:{},ex:{}", userId, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }

    @Override
    public MoResult<String> modifyUserDetail(Long userId, String realName, String idNO) {
        String url = sidecarUrl + "/middle_office/kefu/userDetail/reset";
        try {
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/x-www-form-urlencoded");
            Map param = Maps.newHashMap();
            param.put("userId", String.valueOf(userId));
            param.put("realName", realName);
            param.put("idNO", idNO);
            String result = httpService.post(url, header, param);
            MoResult moResult = GSON.fromJson(result, MoResult.class);
            log.info("[user][modifyUserDetail] 请求业务系统返回值:{}", result);
            return moResult;
        } catch (Exception e) {
            log.error("[user][modifyUserDetail] 网络通讯异常,userId:{},ex:{}", userId, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }
    //add by wuq 2022-01-15 begin
    @Override
    public MoResult<String> getRewardPointsType(){
        String url = kdspOperationUrl + "/api/kdsp/op/userBenefits/center/getEventType";
        try {
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/x-www-form-urlencoded");
            String result = httpService.post(url, header);
            MoResult moResult = GSON.fromJson(result, MoResult.class);
            log.info("[user][getRewardPointsType] 请求业务系统返回值:{}", result);
            return moResult;
        } catch (Exception e) {
            log.error("[user][modifyUserDetail] 网络通讯异常,userId:{},ex:{}",ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }
    //旧逻辑
    @Override
    public JsonResult findUserInfoByUserParam(UserQueryParam userQueryParam) {
        final String LOG_PRE = "UserServiceImpl.findUserInfoByUserParam";
        log.info("{} 查询用户信息 UserQueryParam={}", LOG_PRE, userQueryParam);
        //通过userId查询
        UserSysResult<XUser> userByUserId = null;
        UserSysResult<XUserDetail> userDetailByUserId= null;
        if (Objects.nonNull(userQueryParam.getUserId())) {
            log.info("{} 通过userId查询 userId={}", LOG_PRE, userQueryParam.getUserId());
            userByUserId = userSdk.getService().findUserByUserId(userQueryParam.getUserId());
            userDetailByUserId = userSdk.getService().findUserDetailByUserId(userQueryParam.getUserId());

        }
        UserSysResult<XUser> userByPhoneNo  = null;
        UserSysResult<XUserDetail> userDetailByPhone  = null;
        if (StringUtils.isNotBlank(userQueryParam.getPhoneNo())) {
            log.info("{} 通过phoneNo查询 phoneNo={}", LOG_PRE, userQueryParam.getPhoneNo());
            userByPhoneNo = userSdk.getService().findUserByPhoneNo(userQueryParam.getPhoneNo());
            userDetailByPhone = userSdk.getService().findUserDetailByPhone(userQueryParam.getPhoneNo());
            //根据传入的身份证和查询出的用户信息中身份证进行比较,如果不一致返回查询失败
            if (StringUtils.isNotEmpty(userQueryParam.getIdNo()) && userDetailByPhone.getData() != null) {
                XUserDetail xUserDetail = userDetailByPhone.getData();
                String idNo = xUserDetail.getIdNo();
                if (StringUtils.isNotEmpty(idNo)) {
                    idNo = idNo.trim().toUpperCase();
                }
                String paramIdNo = userQueryParam.getIdNo().trim().toUpperCase();
                if (!paramIdNo.equals(idNo)) {
                    return JsonResult.buildErrorStateResult("无有效查询参数", null);
                }
            }

        }
        //校验手机号查不到用户的情况
        if (Objects.nonNull(userQueryParam.getUserId())) {
            if(userByUserId == null || userDetailByUserId ==null || userByUserId.getData() ==null || userDetailByUserId.getData() ==null){
                return JsonResult.buildErrorStateResult("用户不存在", null);
            }
        }
        if (StringUtils.isNotBlank(userQueryParam.getPhoneNo())) {
            if(userByPhoneNo == null || userDetailByPhone ==null || userByPhoneNo.getData() ==null || userDetailByPhone.getData() ==null){
                return JsonResult.buildErrorStateResult("用户不存在", null);
            }
        }
        //校验手机号和userid不是一个人
        if(Objects.nonNull(userQueryParam.getUserId()) && StringUtils.isNotBlank(userQueryParam.getPhoneNo())){
            if(userByUserId != null && userDetailByUserId != null && userByPhoneNo != null && userDetailByPhone != null){
                if(userByUserId.getData() != null && userByPhoneNo.getData() != null
                        && !userByUserId.getData().getId().equals(userByPhoneNo.getData().getId())){
                    return JsonResult.buildErrorStateResult("用户不存在", null);
                }
            }
        }
        //调用kdsp接口获取会员权益相关信息
        String url= kdspOperationUrl +"/api/kdsp/op/userBenefits/user-benefits-point/getUserBenefit";
        //String url= "http://192.168.28.55:8033/api/kdsp/op/userBenefits/user-benefits-point/getUserBenefit";
        String result = "";
        try {
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/x-www-form-urlencoded");
            Map param = Maps.newHashMap();
            if (Objects.nonNull(userQueryParam.getUserId())) {
                param.put("userId", String.valueOf(userQueryParam.getUserId()));
            }
            if (StringUtils.isNotBlank(userQueryParam.getPhoneNo())) {
                param.put("userId", String.valueOf(userByPhoneNo.getData().getId()));
            }
            result = httpService.post(url, header,param);
        } catch (Exception e) {
            log.error("[userServiceImpl][findUserInfoByUserParam] 网络通讯异常,userId:{},ex:{}",ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
        if (Objects.nonNull(userQueryParam.getUserId())) {
            return getUserBasicInfoResultAndUserBenefits(userByUserId, userDetailByUserId,result);
        }
        if (StringUtils.isNotBlank(userQueryParam.getPhoneNo())) {
            return getUserBasicInfoResultAndUserBenefits(userByPhoneNo, userDetailByPhone,result);
        }

        return null;
    }
    //新逻辑,新用户不需要实名认证
    @Override
    public JsonResult findUserInfoByUserParamNew(UserQueryParam userQueryParam) {
        final String LOG_PRE = "UserServiceImpl.findUserInfoByUserParamNew";
        log.info("{} 查询用户信息 UserQueryParam={}", LOG_PRE, userQueryParam);
        //通过userId查询
        UserSysResult<XUser> userByUserId = null;
        //UserSysResult<XUserDetail> userDetailByUserId= null;
        if (Objects.nonNull(userQueryParam.getUserId())) {
            log.info("{} 通过userId查询 userId={}", LOG_PRE, userQueryParam.getUserId());
            userByUserId = userSdk.getService().findUserByUserId(userQueryParam.getUserId());
            //userDetailByUserId = userSdk.getService().findUserDetailByUserId(userQueryParam.getUserId());

        }
        UserSysResult<XUser> userByPhoneNo  = null;
        //UserSysResult<XUserDetail> userDetailByPhone  = null;
        if (StringUtils.isNotBlank(userQueryParam.getPhoneNo())) {
            log.info("{} 通过phoneNo查询 phoneNo={}", LOG_PRE, userQueryParam.getPhoneNo());
            userByPhoneNo = userSdk.getService().findUserByPhoneNo(userQueryParam.getPhoneNo());
            //userDetailByPhone = userSdk.getService().findUserDetailByPhone(userQueryParam.getPhoneNo());
            //根据传入的身份证和查询出的用户信息中身份证进行比较,如果不一致返回查询失败
            /*if (StringUtils.isNotEmpty(userQueryParam.getIdNo()) && userDetailByPhone != null && userDetailByPhone.getData() != null) {
                XUserDetail xUserDetail = userDetailByPhone.getData();
                String idNo = xUserDetail.getIdNo();
                if (StringUtils.isNotEmpty(idNo)) {
                    idNo = idNo.trim().toUpperCase();
                }
                String paramIdNo = userQueryParam.getIdNo().trim().toUpperCase();
                if (!paramIdNo.equals(idNo)) {
                    return JsonResult.buildErrorStateResult("无有效查询参数", null);
                }
            }*/

        }
        //校验手机号查不到用户的情况
        if (Objects.nonNull(userQueryParam.getUserId())) {
            if(userByUserId == null || userByUserId.getData() ==null){
                return JsonResult.buildErrorStateResult("用户不存在", null);
            }
        }
        if (StringUtils.isNotBlank(userQueryParam.getPhoneNo())) {
            if(userByPhoneNo == null || userByPhoneNo.getData() ==null){
                return JsonResult.buildErrorStateResult("用户不存在", null);
            }
        }
        //校验手机号和userid不是一个人
        if(Objects.nonNull(userQueryParam.getUserId()) && StringUtils.isNotBlank(userQueryParam.getPhoneNo())){
            if(userByUserId != null  && userByPhoneNo != null){
                if(userByUserId.getData() != null && userByPhoneNo.getData() != null
                        && !userByUserId.getData().getId().equals(userByPhoneNo.getData().getId())){
                    return JsonResult.buildErrorStateResult("用户不存在", null);
                }
            }
        }
        //调用kdsp接口获取会员权益相关信息
        String url= kdspOperationUrl +"/api/kdsp/op/userBenefits/user-benefits-point/getUserBenefit";
        String result = "";
        try {
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/x-www-form-urlencoded");
            Map param = Maps.newHashMap();
            if (Objects.nonNull(userQueryParam.getUserId())) {
                param.put("userId", String.valueOf(userQueryParam.getUserId()));
            }
            if (StringUtils.isNotBlank(userQueryParam.getPhoneNo())) {
                param.put("userId", String.valueOf(userByPhoneNo.getData().getId()));
            }
            result = httpService.post(url, header,param);
        } catch (Exception e) {
            log.error("[userServiceImpl][findUserInfoByUserParamNew] 网络通讯异常,userId:{},ex:{}",ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
        if (Objects.nonNull(userQueryParam.getUserId())) {
            return getUserBasicInfoResultAndUserBenefits(userByUserId, null,result);
        }
        if (StringUtils.isNotBlank(userQueryParam.getPhoneNo())) {
            return getUserBasicInfoResultAndUserBenefits(userByPhoneNo, null,result);
        }

        return null;
    }

    @Override
    public MoResult<String> queryUserCouponInfoByUserParam(UserQueryParam userQueryParam) {
        final String LOG_PRE = "UserServiceImpl.getUserCouponInfoByUserParam";
        log.info("{} 查询用户信息 UserQueryParam={}", LOG_PRE, userQueryParam);
        //调用kdsp接口获取会员优惠券相关信息
        String url= kdspOperationUrl +"/api/kdsp/op/coupon/receiver/pickup-list";
        //String url= "http://192.168.28.55:8033/api/kdsp/op/coupon/receiver/pickup-list";

        try {
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/x-www-form-urlencoded");
            header.put("qg-tenant-id","560761");
            Map param = Maps.newHashMap();
            if (Objects.nonNull(userQueryParam.getUserId())) {
                param.put("userId", String.valueOf(userQueryParam.getUserId()));
            }
            if (Objects.nonNull(userQueryParam.getStatus())) {
                param.put("status", userQueryParam.getStatus());
            }
            if (Objects.nonNull(userQueryParam.getPageNo())) {
                param.put("pageNo", userQueryParam.getPageNo());
            }
            if (Objects.nonNull(userQueryParam.getPageSize())) {
                param.put("pageSize", userQueryParam.getPageSize());
            }
            String result = httpService.get(url, header, param);
            MoResult moResult = GSON.fromJson(result, MoResult.class);
            log.info("[user][queryUserCouponInfoByUserParam] 请求业务系统返回值:{}", result);
            return moResult;
        } catch (Exception e) {
            log.error("[userServiceImpl][queryUserCouponInfoByUserParam] 网络通讯异常,userId:{},ex:{}",ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }

    }

    @Override
    public JsonResult submitModiyPhoneNo(ModifyPhoneRecord modifyPhoneRecord) {
        String url = userSysUrl + "/v1/user/modify/phone_no/submitModify";
        Map param = GSON.fromJson(GSON.toJson(modifyPhoneRecord), Map.class);
        try {
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/json");
            String result = httpService.post(url, header, param);
            System.out.println(result);
            JSONObject userJsonObject =null;
            if(result != null){
                userJsonObject = JSONObject.parseObject(result);
                String userBusinessCode = userJsonObject.getString("businessCode");
                if("0000".equals(userBusinessCode)){
                    return JsonResult.buildSuccessResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
                }else{
                    return JsonResult.buildErrorStateResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
                }
            }else{
                return JsonResult.buildErrorStateResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
            }
        } catch (Exception e) {
            log.error("[user][query modify phoneNo] 网络通讯异常,modifyPhoneRecord:{},ex:{}", modifyPhoneRecord, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }

    @Override
    public JsonResult modifyPhoneNolist(Long userId, int pageNo, int pageSize) {
        String url = userSysUrl + "/v1/user/modify/phone_no/modifyPhoneNolist";
        Map<String, String> param = new HashMap<String, String>();
        param.put("userId", String.valueOf(userId));
        param.put("pageNo", String.valueOf(pageNo));
        param.put("pageSize", String.valueOf(pageSize));
        try {
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/x-www-form-urlencoded");
            String result = httpService.post(url, header, param);
            System.out.println(result);
            JSONObject userJsonObject =null;
            if(result != null){
                userJsonObject = JSONObject.parseObject(result);
                String userBusinessCode = userJsonObject.getString("businessCode");
                if("0000".equals(userBusinessCode)){
                    return JsonResult.buildSuccessResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
                }else{
                    return JsonResult.buildErrorStateResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
                }
            }else{
                return JsonResult.buildErrorStateResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
            }

        } catch (Exception e) {
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }

    @Override
    public JsonResult modifyRecord(String prevPhoneNo) {
        String url = userSysUrl + "/v1/user/modify/phone_no/modifyRecord";
        ImmutableMap<String, String> param = ImmutableMap.of("prevPhoneNo", prevPhoneNo);
        JSONObject userJsonObject = null;
        try {
            String response = httpService.get(url, param);
//            log.info("[user][query modify phone list] 请求业务系统返回值,modifyPhoneQuery:{},response={}", modifyPhoneQuery, response);
            if(response != null){
                userJsonObject = JSONObject.parseObject(response);
                String userBusinessCode = userJsonObject.getString("businessCode");
                if("0000".equals(userBusinessCode)){
                    String data = userJsonObject.getString("data");
                    if (StringUtils.isBlank(data)){
                        return JsonResult.buildSuccessResult(userJsonObject.getString("msg"), null);
                    }
                    UserModifyPhoneRecord userModifyPhoneRecord = JSONTools.deserialize(data,
                        UserModifyPhoneRecord.class);
                    userModifyPhoneRecord.setPrevPhoneNo(DesensitizeUtil.mobileDesensitization(userModifyPhoneRecord.getPrevPhoneNo()));
                    userModifyPhoneRecord.setCurPhoneNo(DesensitizeUtil.mobileDesensitization(userModifyPhoneRecord.getCurPhoneNo()));
                    return JsonResult.buildSuccessResult(userJsonObject.getString("msg"), userModifyPhoneRecord);
                }else{
                    return JsonResult.buildErrorStateResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
                }
            }else{
                return JsonResult.buildErrorStateResult(userJsonObject.getString("msg"),userJsonObject.get("data"));
            }
        } catch (Exception e) {
            log.error("[user][query modify phone record] 网络通讯异常,modifyPhoneQuery:{},ex:{}", prevPhoneNo, ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }

    /**
     *根据userid和phoneNo获取基本信息
     * @param xUserUserSysResult
     * @param detailUserSysResult
     * @return
     */
    private JsonResult getUserBasicInfoResultAndUserBenefits
            (UserSysResult<XUser> xUserUserSysResult, UserSysResult<XUserDetail> detailUserSysResult,String result) {
        UserBasicInfo userBasicInfo = new UserBasicInfo();
        //处理json字符串
        JSONObject json =JSONObject.parseObject(result);
        String jsonResult = json.getString("data");
        if(jsonResult != null){
            JSONObject jsonObject = JSONObject.parseObject(jsonResult);
            userBasicInfo.setLevelBenefit(jsonObject.getString("levelBenefit"));
            userBasicInfo.setLevel(Integer.valueOf(jsonObject.getString("level")));
            userBasicInfo.setLevelName(jsonObject.getString("levelName"));
            userBasicInfo.setPoint(new BigDecimal(jsonObject.getString("point")));
            userBasicInfo.setLevelValidityTerm(jsonObject.getString("levelValidityTerm"));
        }

        Object xUserData = getJsonResultData(xUserUserSysResult);
        if (Objects.isNull(xUserData)) {
            log.error(" 用户不存在 userSysResult={}", xUserData);
            return JsonResult.buildErrorStateResult("用户不存在", xUserData);
        }

        if (xUserData instanceof XUser) {
            XUser xUser = (XUser) xUserData;
            userBasicInfo.setUserId(xUser.getId());
            userBasicInfo.setPhoneNo(DesensitizeUtil.phoneMark(xUser.getPhoneNo()));
            userBasicInfo.setPhoneNumber(xUser.getPhoneNo());
            String createAt = DateUtil.format(xUser.getCreatedAt(), DateUtil.DATE_FORMAT_1);
            userBasicInfo.setCreatedAt(createAt);
            Boolean enable = xUser.getEnable();
            //userBasicInfo.setStatus(enable == null ? "未知" : (enable ? "正常" : "封禁"));
            userBasicInfo.setStatus(enable == null ? "未知" : (enable ? "启用" : "冻结"));
        }else{
            log.error("查询用户失败 user={}",xUserData);
            return (JsonResult) xUserData;
        }

        if(detailUserSysResult != null){
            Object detailUser = getJsonResultData(detailUserSysResult);
            if (detailUser instanceof XUserDetail) {
                XUserDetail userDetail = (XUserDetail) detailUser;
                userBasicInfo.setGender(userDetail.getGender().getName());
                userBasicInfo.setIdNo(DesensitizeUtil.idNoMark(userDetail.getIdNo()));
                userBasicInfo.setName(userDetail.getName());
            }
        }
        return JsonResult.buildSuccessResult(null, userBasicInfo);
    }

    /**
     * 根据积分类型和操作时间查询积分明细
     * @return
     */
    public MoResult<String> queryPointDetailByPage(UserQueryParam  userQueryParam) {
        String url = kdspOperationUrl + "/api/kdsp/op/userBenefits/user-benefits-detail/queryPointDetailByPage";
        //String url = "http://192.168.28.55:8033/api/kdsp/op/userBenefits/user-benefits-detail/queryPointDetailByPage";
        try {
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-type", "application/json");
            Map param = Maps.newHashMap();
            param.put("userId",userQueryParam.getUserId());
            param.put("operationTime",userQueryParam.getOperationTime());
            param.put("eventType",userQueryParam.getEventType());
            param.put("pageNo",userQueryParam.getPageNo());
            param.put("pageSize",userQueryParam.getPageSize());
            String result = httpService.post(url, header, param);
            MoResult<String> moResult = GSON.fromJson(result, MoResult.class);
            return moResult;
        } catch (Exception e) {
            log.error("[userServiceImpl][queryPointDetailByPage] 网络通讯异常,userId:{},ex:{}", ExceptionUtils.getStackTrace(e));
            throw new BusinessException(ErrorCodeEnum.NET_ERROR);
        }
    }
}
