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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.friday.custody.service.trustService.zx.utils.SearchReturnClass;
import com.friday.custody.dao.CdsProductInfoDao;
import com.friday.custody.entity.CdsProductInfoEntity;
import com.friday.custody.service.basicService.CdsProductInfoService;
import com.friday.custody.service.basicService.TenantEscrowAuthorizationInfoService;
import com.friday.custody.service.tenantService.CustodyTenantMappingService;
import com.friday.custody.vo.SearchReturnFundCodeListVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service("cdsProductInfoService")
@Slf4j
public class CdsProductInfoServiceImpl extends ServiceImpl<CdsProductInfoDao, CdsProductInfoEntity> implements CdsProductInfoService {
    @Autowired
    private SearchReturnClass searchReturnClass;
    @Autowired
    private TenantEscrowAuthorizationInfoService tenantEscrowAuthorizationInfoService;


    @Autowired
    private CustodyTenantMappingService custodyTenantMappingService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean syncFundInfoFromHtscCds(String admin) {
        List<Map<String, Object>> productInfoFromCdsList = searchReturnClass.queryPrtInfo(admin);
        List<CdsProductInfoEntity> cdsProductInfoEntities = parseRawProductInfoListFromCds(productInfoFromCdsList, admin);
        LambdaQueryWrapper<CdsProductInfoEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CdsProductInfoEntity::getAdmin, admin);
        this.remove(lambdaQueryWrapper);
        boolean saveStatus = this.saveBatch(cdsProductInfoEntities);
        if ((!cdsProductInfoEntities.isEmpty()) && (!saveStatus)) {
            log.error("save fund info from htsc cds failed,admin:{}",admin);
            return false;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean syncFundInfoFromHtscCds() {
        HashSet<String> adminSet = new HashSet<>();
        Set<String> daasAdminSet = tenantEscrowAuthorizationInfoService.queryAdminList();
        Set<String> privatePlatformAdminSet = custodyTenantMappingService.queryAdminList();
        if (daasAdminSet.isEmpty() && privatePlatformAdminSet.isEmpty()) {
            return false;
        }
        adminSet.addAll(daasAdminSet);
        adminSet.addAll(privatePlatformAdminSet);
        //adminSet
        log.info("adminSet={}", adminSet);
        List<CdsProductInfoEntity> cdsProductInfoEntities = new ArrayList<>();
        for (String admin : adminSet) {
            //后续添加入表的字段：管理人名称(MANAGEMENTCOM) 管理人编码(REGCODE) 产品备案编码(REGCODE) 产品名称(FUNDFULLNAME) 产品状态(FUNDSTATUS) 是否投顾类产品(ISPRIVATE)
            List<Map<String, Object>> searchReturnList = searchReturnClass.queryPrtInfo(admin);
            log.info("cds::queryPrtInfo::admin::{},{}", admin, searchReturnList);
            for (Map<String, Object> stringObjectMap : searchReturnList) {
                SearchReturnFundCodeListVo fundInfoFromCds = JSON.parseObject(JSON.toJSONString(stringObjectMap), SearchReturnFundCodeListVo.class);
                log.info("stringObjectMap::before:{}::after::{}", stringObjectMap, fundInfoFromCds);

                CdsProductInfoEntity cdsProductInfo = CdsProductInfoEntity.builder()
                        .admin(admin)
                        .adminName(fundInfoFromCds.getORGFULLNAME())
                        .fundCode(fundInfoFromCds.getREGCODE())
                        .fundName(fundInfoFromCds.getFUNDFULLNAME())
                        .sunshineFund(fundInfoFromCds.getISPRIVATE())
                        .fundStatus(fundInfoFromCds.getFUNDSTATUS())
                        .liquidation(fundInfoFromCds.getISLIQUIDATION())
                        .manageType(fundInfoFromCds.getMANAGETYPE())
                        .build();
                //资讯数据中分级基金regcode为null,过滤掉
                if (StringUtils.isNotBlank(fundInfoFromCds.getREGCODE())
                        && StringUtils.isNotBlank(fundInfoFromCds.getFUNDFULLNAME())
                        && fundInfoFromCds.getISPRIVATE() != null
                        && fundInfoFromCds.getFUNDSTATUS() != null
                        && fundInfoFromCds.getISLIQUIDATION() != null){
                    cdsProductInfoEntities.add(cdsProductInfo);
                }
            }
        }
        this.remove(null);
        boolean saveStatus = this.saveBatch(cdsProductInfoEntities);
       if ((!cdsProductInfoEntities.isEmpty()) && (!saveStatus)) {
           log.error("save fund info from htsc cds failed");
       }
        return true;
    }

    /**
     * 解析资讯数据，转换成 CdsProductInfoEntity
     * @param responseFromCds  资讯平台返回的原始响应
     * @param admin 管理人编码
     * @return
     */
    private List<CdsProductInfoEntity> parseRawProductInfoListFromCds(List<Map<String, Object>> responseFromCds, String admin){
        List<CdsProductInfoEntity> cdsProductInfoEntities = new ArrayList<>();
        for (Map<String, Object> stringObjectMap : responseFromCds) {
            SearchReturnFundCodeListVo fundInfoFromCds = JSON.parseObject(JSON.toJSONString(stringObjectMap), SearchReturnFundCodeListVo.class);
            log.info("stringObjectMap::before:{}::after::{}", stringObjectMap, fundInfoFromCds);

            CdsProductInfoEntity cdsProductInfo = CdsProductInfoEntity.builder()
                    .admin(admin)
                    .adminName(fundInfoFromCds.getORGFULLNAME())
                    .fundCode(fundInfoFromCds.getREGCODE())
                    .fundName(fundInfoFromCds.getFUNDFULLNAME())
                    .sunshineFund(fundInfoFromCds.getISPRIVATE())
                    .fundStatus(fundInfoFromCds.getFUNDSTATUS())
                    .liquidation(fundInfoFromCds.getISLIQUIDATION())
                    .manageType(fundInfoFromCds.getMANAGETYPE())
                    .build();
            //资讯数据中分级基金regcode为null,过滤掉
            if (StringUtils.isNotBlank(fundInfoFromCds.getREGCODE())
                    && StringUtils.isNotBlank(fundInfoFromCds.getFUNDFULLNAME())
                    && fundInfoFromCds.getISPRIVATE() != null
                    && fundInfoFromCds.getFUNDSTATUS() != null
                    && fundInfoFromCds.getISLIQUIDATION() != null){
                cdsProductInfoEntities.add(cdsProductInfo);
            }
        }
        return cdsProductInfoEntities;
    }
}