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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.friday.custody.service.logicService.impl.DataDictionaryBasicServiceImpl;
import com.friday.custody.dao.InvestorInfoDao;
import com.friday.custody.entity.InvestorInfoEntity;
import com.friday.custody.enums.RetCodeEnum;
import com.friday.custody.exception.RRException;
import com.friday.custody.req.InvestorInfoReq;
import com.friday.custody.req.QueryDataReq;
import com.friday.custody.service.basicService.DataDictionaryTypeCertificateCsdcService;
import com.friday.custody.service.basicService.InvestorInfoService;
import com.friday.custody.service.logicService.DataProcessService;
import com.friday.custody.utils.PageUtil;
import com.friday.custody.utils.PageUtils;
import com.friday.custody.utils.Query;
import com.friday.custody.utils.R;
import com.friday.custody.vo.InvestorInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service("investorInfoService")
@Slf4j
public class InvestorInfoServiceImpl extends ServiceImpl<InvestorInfoDao, InvestorInfoEntity>
        implements InvestorInfoService, DataProcessService<InvestorInfoEntity> {

    @Autowired
    InvestorInfoDao investorInfoDao;
    @Autowired
    private DataDictionaryBasicServiceImpl dataDictionaryBasicService;
    @Autowired
    private DataDictionaryTypeCertificateCsdcService certificateCsdcService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveData(String type, List<InvestorInfoEntity> investorInfoEntities) {
        if (CollectionUtils.isEmpty(investorInfoEntities)){
            return R.ok();
        }
        for (InvestorInfoEntity entity : investorInfoEntities) {
            if ("33".equals(entity.getTrustNo()) || "41".equals(entity.getTrustNo())) {
                entity.setUniqueKey(entity.getAdmin() + entity.getTrustNo() + entity.getFundAcco());
            } else {
                entity.setUniqueKey(entity.getAdmin() + entity.getFundAcco());
            }
        }
        List<InvestorInfoEntity> uniqueInvestrInfoList = investorInfoEntities.stream().collect(Collectors.collectingAndThen
                (Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing
                        (InvestorInfoEntity::getUniqueKey))), ArrayList::new));

        List<String> rawUniqueKeyList = uniqueInvestrInfoList
                .stream()
                .map(InvestorInfoEntity::getUniqueKey)
                .collect(Collectors.toList());

        String ukList = String.join("--", rawUniqueKeyList);
        if (CollectionUtils.isNotEmpty(rawUniqueKeyList)) {
            Set<String> uniqueKeySet = baseMapper.queryUniqueKeyList(rawUniqueKeyList);
            if (CollectionUtils.isNotEmpty(uniqueKeySet)) {
                baseMapper.deleteByUniqueKeys(uniqueKeySet);
            }

        }
        boolean saveStatus = this.saveBatch(uniqueInvestrInfoList);
        if (!saveStatus) {
            log.error("保存InvestorInfo失败:{}", ukList);
        }
        return R.ok();
    }

    @Override
    public R queryData(QueryDataReq vo) {
        try {
            log.info("开始查询基金出资人信息表...,租户信息为:{}", JSON.toJSONString(vo));
            //1 封装查询参数
            InvestorInfoReq investorInfoReq = JSON.parseObject(vo.getParams(), InvestorInfoReq.class);
            //1.1 封装分页查询参数
            Map<String, Object> pageParams = PageUtil.getPageParams(investorInfoReq);
            //1.2 封装查询参数
            QueryWrapper<InvestorInfoEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("admin", vo.getTenantName());
            if (StringUtils.isNotBlank(investorInfoReq.getCustName())) {
                queryWrapper.likeRight("cust_name", investorInfoReq.getCustName());
            }
            if (StringUtils.isNotBlank(investorInfoReq.getCustType())) {
                queryWrapper.eq("cust_type", investorInfoReq.getCustType());
            }
            if (StringUtils.isNotBlank(investorInfoReq.getIdentityNo())) {
                queryWrapper.eq("identity_no", investorInfoReq.getIdentityNo());
            }
            if (StringUtils.isNotBlank(investorInfoReq.getIdentityType())) {
                queryWrapper.eq("identity_type", investorInfoReq.getIdentityType());
            }
            if (StringUtils.isNotBlank(investorInfoReq.getFundAcco())) {
                queryWrapper.eq("fund_acco", investorInfoReq.getFundAcco());
            }
            queryWrapper.orderBy(true,false, "update_date","cust_name","fund_acco","trust_no");
            //2 执行检索
            IPage<InvestorInfoEntity> page = this.page(
                    new Query<InvestorInfoEntity>().getPage(pageParams),
                    queryWrapper
            );
            //封装数据
            PageUtils pageUtils = new PageUtils(page);
            List<InvestorInfoEntity> entities = page.getRecords();
            //entities 转vo
            ArrayList<InvestorInfoVo> vos = new ArrayList<>();
            for (InvestorInfoEntity entity : entities) {
                vos.add(InvestorInfoVo.builder()
                        .id(entity.getId())
                        .custName(entity.getCustName())
                        .custType(entity.getCustType())
                        .identityNo(entity.getIdentityNo())
                        .identityType(entity.getIdentityType())
                        .fundAcco(entity.getFundAcco())
                        .accoOpenDate(entity.getAccoOpenDate())
                        .individualOrInstitution(entity.getIndividualOrInstitution())
                        .mobileNo(entity.getMobileNo())
                        .email(entity.getEmail())
                        .address(entity.getAddress())
                        .zipCode(entity.getZipCode())
                        .updateDate(entity.getUpdateDate())
                        .trustNo(entity.getTrustNo())
                        .build());
            }
            pageUtils.setList(vos);
            log.info("基金出资人信息查询成功...");
            return R.ok("基金出资人信息查询成功").put("data", pageUtils);
        } catch (RRException rrException) {
            log.error("the QueryDataVo is :" + JSON.toJSONString(vo) + ".the InvestorInfoServiceImpl RRException is :", rrException);
            return R.error(RetCodeEnum.OPERATION_ERROR.getCode(), rrException.getMsg());
        } catch (Exception e) {
            log.error("the QueryDataVo is :" + JSON.toJSONString(vo) + ".the InvestorInfoServiceImpl Exception is :", e);
            return R.error(RetCodeEnum.OPERATION_ERROR.getCode(), "查询数据失败!");
        }
    }

    @Override
    public R updateData(String type, List<InvestorInfoEntity> datas) {
        return null;
    }

    public String queryInvestor(String custName, String identityNo) {
        List<String> strings = investorInfoDao.queryInvestor(custName, identityNo);

        if(!CollectionUtils.isEmpty(strings)){
            for (String string : strings) {
                if(StringUtils.isNotBlank(string)){
                    return string;
                }
            }
        }

        return null;
    }
public void queryFundAcco(){

}
}