package com.friday.custody.service.tenantService.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.friday.base.common.response.DubboResult;
import com.friday.custody.dto.InterProviderResponseDto;
import com.friday.mystery.forwardapi.dto.DistributorGetDatePostResponseDto;
import com.friday.mystery.forwardapi.service.IHttpRequestService;
import com.google.common.collect.Lists;
import com.friday.custody.dao.CustodyTenantMappingDao;
import com.friday.custody.dto.TenantEscrowAuthorizationInfoDto;
import com.friday.custody.entity.CustodyTenantMappingEntity;
import com.friday.custody.enums.RetCodeEnum;
import com.friday.custody.req.TenantMappingReq;
import com.friday.custody.service.basicService.impl.TenantEscrowAuthorizationInfoServiceImpl;
import com.friday.custody.service.tenantService.CustodyTenantMappingService;
import com.friday.custody.utils.R;
import com.friday.custody.vo.CustodyTenantMappingVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service("peTenantMappingService")
@Slf4j
public class CustodyTenantMappingServiceImpl extends ServiceImpl<CustodyTenantMappingDao, CustodyTenantMappingEntity> implements CustodyTenantMappingService {

    @Resource
    private IHttpRequestService httpRequestService;
    @Autowired
    private CustodyTenantMappingDao custodyTenantMappingDao;
    @Autowired
    private TenantEscrowAuthorizationInfoServiceImpl tenantEscrowAuthorizationInfoService;

    @Override
    public R saveTenantMapping(String params){
        String tenant = "";
        try{
            TenantMappingReq req = JSON.parseObject(params, TenantMappingReq.class);
            tenant = req.getTenant();
            TenantEscrowAuthorizationInfoDto tenantEscrowAuthorizationInfoDto = tenantEscrowAuthorizationInfoService.queryAuthorizationByTrustNo("99");
            log.info("获取用户筛选字段ids={}"+ tenant);
            //先查数据库，如果有直接返回
            CustodyTenantMappingEntity tenantMappingEntity = custodyTenantMappingDao.queryByTenant(tenant);
            Map<String, String> dataMap = new HashMap<>();
            if(tenantMappingEntity != null && StringUtils.isNotBlank(tenantMappingEntity.getAdmin()) && StringUtils.isNotBlank(tenantMappingEntity.getCompanyName())){
                dataMap.put("admin", tenantMappingEntity.getAdmin());
                dataMap.put("companyName", tenantMappingEntity.getCompanyName());
                return R.ok("保存官网租户成功！").put("data", dataMap);
            }
            //调用资讯 ZX_COMPANYINFO 接口获取公司名称
            Map<String, String> companyNameMap = getCompanyName(tenantEscrowAuthorizationInfoDto.getAppKey(), tenant);
            if (companyNameMap.containsKey("error")){
                return R.error(RetCodeEnum.SYS_ERROR.getCode(), companyNameMap.get("error"));
            }
            String companyName = companyNameMap.get("name");
            //调用资讯ZX_FNDORGCY接口获得登记编号
            Map<String, String> adminMap = getAdmin(tenantEscrowAuthorizationInfoDto.getAppKey(), companyName);
            if (adminMap.containsKey("error")){
                return R.error(RetCodeEnum.SYS_ERROR.getCode(), adminMap.get("error"));
            }
            String admin = adminMap.get("admin");
            //校验数据库是否有该数据
            CustodyTenantMappingEntity entity = new CustodyTenantMappingEntity();
            entity.setAdmin(admin);
            entity.setCompanyName(companyName);
            entity.setTenant(tenant);
            entity.setCreateTime(new Date());
            entity.setUpdateTime(new Date());
            entity.setIsDeleted(0);
            custodyTenantMappingDao.insertOrUpdate(entity);
            //result.setObject(admin);
            dataMap.put("admin", admin);
            dataMap.put("companyName", companyName);
            return R.ok("保存官网租户成功!").put("data", dataMap);
        } catch (Exception e) {
            log.error("保存官网租户失败",e);
            //return DubboResult.newFailure(DubboResult.SERVER_EXCEPTION, "获取资讯平台数据错误");
        }
        return R.error(RetCodeEnum.OPERATION_ERROR.getCode(), "保存官网租户失败!");
    }
    public Map<String, String> getCompanyName(String appKey, String tenant){
        HashMap<String, String> returnMap = new HashMap<>();
        // 查询字段(为空则查询全部字段)
        List<String> selectedFields = Lists.newArrayList("CHINAME");
        Map<String, List<String>> paramMaps = new HashMap<>();
        paramMaps.put("COMCREDITCODE", Lists.newArrayList(tenant));  // 交易代码
        log.info("调用资讯中心接口入参：{}, {}", "ZX_COMPANYINFO", JSON.toJSONString(paramMaps));
        DubboResult<DistributorGetDatePostResponseDto> resultData = httpRequestService.getInformationByDistributor("ZX_COMPANYINFO", paramMaps, 0, 10000, "", selectedFields);
        InterProviderResponseDto responseDto = getInterProviderResponse(resultData);
        String returnMsg = "";
        if (!responseDto.isSuccess()) {
            returnMsg = "调用资讯中心接口查询Resource= [ZX_COMPANYINFO]的数据失败! resultData= " + JSON.toJSONString(resultData);
            log.error(returnMsg);
            returnMap.put("error", returnMsg);
            return returnMap;
            //return DubboResult.newFailure(DubboResult.SERVER_EXCEPTION,"调用资讯中心接口查询CHINAME失败");
        }
        List<Map<String, Object>> resultDataList = responseDto.getDataList();
        if (CollectionUtils.isEmpty(resultDataList)) {
            returnMsg = "调用资讯中心接口查询resource=[ZX_COMPANYINFO]的数据为空! resultData= " + JSON.toJSONString(resultDataList);
            log.warn(returnMsg);
            returnMap.put("error", returnMsg);
            return returnMap;
            //return DubboResult.newFailure(DubboResult.SERVER_EXCEPTION,"调用资讯中心接口查询CHINAME数据为空");
        }
        returnMsg = String.valueOf(resultDataList.get(0).get("CHINAME"));
        returnMap.put("name", returnMsg);
        return returnMap;
    }
    public Map<String, String> getAdmin(String appKey, String name){
        HashMap<String, String> returnMap = new HashMap<>();
        // 封装查询参数
        // 查询字段(为空则查询全部字段)
        List<String> selectedFields = Lists.newArrayList("REGCODE");
        // 查询条件
        Map<String, List<String>> paramMaps = new HashMap<>();
        paramMaps.put("ORGFULLNAME", Lists.newArrayList(name));  // 交易代码
        // 执行查询操作
        log.info("调用资讯中心接口入参：{}, {}", "ZX_FNDORGCY", JSON.toJSONString(paramMaps));
        DubboResult<DistributorGetDatePostResponseDto> resultData = httpRequestService.getInformationByDistributor("ZX_FNDORGCY", paramMaps, 0, 10000, "", selectedFields);
        InterProviderResponseDto responseDto = getInterProviderResponse(resultData);
        String returnMsg = "";
        if (!responseDto.isSuccess()) {
            returnMsg = "调用资讯中心接口查询Resource= [ZX_FNDORGCY]的数据失败! resultData= " + JSON.toJSONString(resultData);
            log.error(returnMsg);
            returnMap.put("error", returnMsg);
            return returnMap;
        }
        List<Map<String, Object>> dataList = responseDto.getDataList();
        if (CollectionUtils.isEmpty(dataList)) {
            returnMsg = "调用资讯中心接口查询resource=[ZX_FNDORGCY]的数据为空! resultData= " + JSON.toJSONString(dataList);
            log.warn(returnMsg);
            returnMap.put("error", returnMsg);
            return returnMap;
        }
        returnMsg = String.valueOf(dataList.get(0).get("REGCODE"));
        returnMap.put("admin", returnMsg);
        return returnMap;
    }

    @Override
    public R queryTenantMapping(String params) {
        TenantMappingReq req = new TenantMappingReq();
        try {
            //1 封装查询参数
            req = JSON.parseObject(params, TenantMappingReq.class);
            log.info("开始查询租户映射信息...,租户映射信息为:{}", JSON.toJSONString(req));
            if (StringUtils.isBlank(req.getTenant()) && StringUtils.isBlank(req.getAdmin()) && StringUtils.isBlank(req.getCompanyName())){
                return R.error(RetCodeEnum.PARAM_ERROR.getCode(), "传入参数不能为空!");
            }
            //2 执行检索
            LambdaQueryWrapper<CustodyTenantMappingEntity> queryWrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isNotBlank(req.getTenant())) {
                queryWrapper.eq(CustodyTenantMappingEntity::getTenant, req.getTenant());
            }
            if (StringUtils.isNotBlank(req.getAdmin())) {
                queryWrapper.eq(CustodyTenantMappingEntity::getAdmin, req.getAdmin());
            }
            if (StringUtils.isNotBlank(req.getCompanyName())) {
                queryWrapper.like(CustodyTenantMappingEntity::getCompanyName, req.getCompanyName());
            }
            List<CustodyTenantMappingEntity> entities = custodyTenantMappingDao.selectList(queryWrapper);
            if (CollectionUtils.isNotEmpty(entities) && entities.size() > 10){
                return R.error(RetCodeEnum.PARAM_ERROR.getCode(), "查询结果过多,请精确查询参数!");
            }
            //封装数据
            //entities 转vo
            ArrayList<CustodyTenantMappingVO> vos = new ArrayList<>();
            for (CustodyTenantMappingEntity entity : entities) {
                vos.add(CustodyTenantMappingVO.builder()
                      .admin(entity.getAdmin())
                      .tenant(entity.getTenant())
                      .companyName(entity.getCompanyName())
                      .build());
            }
            return R.ok("查询官网租户信息成功!").put("data",vos);
        } catch (Exception e) {
            log.error("the TenantMappingReq is :" + JSON.toJSONString(req) + ".the TenantEscrowAuthorizationInfoServiceImpl Exception is :", e);
            return R.error(RetCodeEnum.OPERATION_ERROR.getCode(), "查询官网租户数据失败!");
        }
    }
    @Override
    public Set<String> queryAdminList(){
        LambdaQueryWrapper<CustodyTenantMappingEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(CustodyTenantMappingEntity::getAdmin);
        queryWrapper.groupBy(CustodyTenantMappingEntity::getAdmin);
        List<CustodyTenantMappingEntity> entityList = baseMapper.selectList(queryWrapper);
        return entityList.stream().map(CustodyTenantMappingEntity::getAdmin).collect(Collectors.toSet());
    }

    @Override
    public R insertOrUpdate(String params) {
        TenantMappingReq req = JSON.parseObject(params, TenantMappingReq.class);
        CustodyTenantMappingEntity entity = new CustodyTenantMappingEntity();
        entity.setAdmin(req.getAdmin());
        entity.setCompanyName(req.getCompanyName());
        entity.setTenant(req.getTenant());
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        entity.setIsDeleted(0);
        custodyTenantMappingDao.insertOrUpdate(entity);
        return null;
    }

    private InterProviderResponseDto getInterProviderResponse(DubboResult<DistributorGetDatePostResponseDto> resultData){
        if (resultData == null) {
            return InterProviderResponseDto.builder().success(false).failMsg("资讯接口调用失败，返回结果为空！").build();
        }
        if (resultData.success()) {
            DistributorGetDatePostResponseDto responseDto = resultData.getObject();
            if (responseDto.getRetCode() == 0) {
                String value = JSON.toJSONString(responseDto.getValue());
                if (StringUtils.isNotEmpty(value)) {
                    return JSON.parseObject(value, InterProviderResponseDto.class);
                }
            } else {
                return InterProviderResponseDto.builder().success(false).failMsg(responseDto.getMessage()).build();
            }
        }
        return InterProviderResponseDto.builder().success(false).failMsg(resultData.getError() + resultData.getMessage()).build();
    }
}
