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.dao.CustShareSeqInfoDao;
import com.friday.custody.entity.CustShareSeqInfoEntity;
import com.friday.custody.entity.FundInfoEntity;
import com.friday.custody.enums.RetCodeEnum;
import com.friday.custody.exception.RRException;
import com.friday.custody.req.CustShareSeqInfoReq;
import com.friday.custody.req.QueryDataReq;
import com.friday.custody.service.basicService.CustShareSeqInfoService;
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.CustShareSeqInfoVo;
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.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


@Service("custShareSeqInfoService")
@Slf4j
public class CustShareSeqInfoServiceImpl extends ServiceImpl<CustShareSeqInfoDao, CustShareSeqInfoEntity>
        implements CustShareSeqInfoService , DataProcessService<CustShareSeqInfoEntity> {
    @Autowired
    private FundInfoServiceImpl fundInfoService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveData(String type, List<CustShareSeqInfoEntity> datas) {
        if (CollectionUtils.isEmpty(datas)){
            return R.ok();
        }
        //设置主键 / 补全fundCode或 fundName
        List<CustShareSeqInfoEntity> custShareSeqInfoEntityList = this.handleData(datas);
        List<CustShareSeqInfoEntity> uniqueCustShareSeqInfoList = custShareSeqInfoEntityList.stream().collect(Collectors.collectingAndThen
                (Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing
                        (CustShareSeqInfoEntity::getUniqueKey))), ArrayList::new));

        List<String> rawUniqueKeyList = uniqueCustShareSeqInfoList
                .stream()
                .map(CustShareSeqInfoEntity::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(uniqueCustShareSeqInfoList);
        if (!saveStatus) {
            log.error("保存 CustShareSeqInfo失败:{}", ukList);
        }
        return R.ok();

    }

    private List<CustShareSeqInfoEntity> handleData(List<CustShareSeqInfoEntity> datas) {

        for (CustShareSeqInfoEntity entity : datas) {
            //如果fundCode，fundName为null，innerFundCode不为null则通过innerFundCode查询fundName，fundCode
            if (StringUtils.isBlank(entity.getFundCode()) && StringUtils.isBlank(entity.getFundName()) && StringUtils.isNotBlank(entity.getInnerFundCode())) {
                FundInfoEntity fundInfoEntity = fundInfoService.queryByInnerFundCode(entity.getTrustNo(), entity.getAdmin(), entity.getInnerFundCode());
                if (fundInfoEntity != null) {
                    entity.setFundCode(fundInfoEntity.getFundCode());
                    entity.setFundName(fundInfoEntity.getFundName());
                }
            } else {
                //如果fundCode为null，fundName不为null，则通过fundName查询fundCode
                if (StringUtils.isBlank(entity.getFundCode()) && StringUtils.isNotBlank(entity.getFundName())) {
                    String fundCode = fundInfoService.getFundCodeByFundName(entity.getFundName(), entity.getTrustNo(), entity.getAdmin());
                    entity.setFundCode(fundCode);
                }
                //如果fundCode不为null，fundName为null，则通过fundCode查询fundName
                if (StringUtils.isNotBlank(entity.getFundCode()) && StringUtils.isBlank(entity.getFundName())) {
                    String fundName = fundInfoService.getFundNameByFundCode(entity.getFundCode(), entity.getTrustNo(), entity.getAdmin());
                    entity.setFundName(fundName);
                }
            }

            if ("30".equals(entity.getTrustNo())) {
                entity.setUniqueKey(entity.getFundAcco() + entity.getTradeAcco() + entity.getInnerFundCode() + entity.getConfirmDate() + entity.getTrustNo() + entity.getAdmin());
            } else if ("44".equals(entity.getTrustNo())) {
                entity.setUniqueKey(entity.getRequestNo() + entity.getTrustNo() + entity.getAdmin());
            } else {
                entity.setUniqueKey(entity.getSeqNo() + entity.getTrustNo() + entity.getAdmin());
            }
        }
        return datas;
    }


    @Override
    public R queryData(QueryDataReq vo) {
        try {
            log.info("开始查询基金持有份额变化流水表...,租户信息为:{}", JSON.toJSONString(vo));
            //1 封装查询参数
            CustShareSeqInfoReq req = JSON.parseObject(vo.getParams(), CustShareSeqInfoReq.class);
            //1.1 封装分页查询参数
            Map<String, Object> pageParams = PageUtil.getPageParams(req);
            //1.2 封装查询参数
            QueryWrapper<CustShareSeqInfoEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("admin", vo.getTenantName());
            if (StringUtils.isNotBlank(req.getFundCode())) {
                queryWrapper.eq("fund_code", req.getFundCode());
            }
            if (StringUtils.isNotBlank(req.getInnerFundCode())){
                queryWrapper.eq("inner_fund_code",req.getInnerFundCode());
            }
            if (StringUtils.isNotBlank(req.getAgencyNo())) {
                queryWrapper.eq("agency_no", req.getAgencyNo());
            }
            if (StringUtils.isNotBlank(req.getFundAcco())) {
                queryWrapper.eq("fund_acco", req.getFundAcco());
            }
            if (StringUtils.isNotBlank(req.getTradeAcco())) {
                queryWrapper.eq("trade_acco", req.getTradeAcco());
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            Calendar c = Calendar.getInstance();
            //开始和结束时间都为空，默认为一年
            if (StringUtils.isBlank(req.getBeginDate())&&StringUtils.isBlank(req.getEndDate())) {
                c.setTime(new Date());
                c.add(Calendar.YEAR, -1);
                Date m = c.getTime();
                String beginYear = format.format(m);
                req.setBeginDate(beginYear);
                req.setEndDate(format.format(new Date()));
            }
            //开始不为空和结束时间为空，默认当天
            if (StringUtils.isBlank(req.getEndDate())&&StringUtils.isNotBlank(req.getBeginDate())) {
                c.setTime(format.parse(req.getBeginDate()));
                c.add(Calendar.YEAR, 1);
                Date m = c.getTime();
                String endYear = format.format(m);
                req.setBeginDate(req.getBeginDate());
                req.setEndDate(endYear);
            }
            //开始为空和结束时间不为空，默认结束时间往前推一年
            if (StringUtils.isNotBlank(req.getEndDate())&&StringUtils.isBlank(req.getBeginDate())) {
                c.setTime(format.parse(req.getEndDate()));
                c.add(Calendar.YEAR,-1);
                Date m = c.getTime();
                String beginYear = format.format(m);
                req.setBeginDate(beginYear);
            }
            try {
                LocalDate beginDate = LocalDate.parse(req.getBeginDate(), DateTimeFormatter.ofPattern("yyyyMMdd"));
                LocalDate endDate = LocalDate.parse(req.getEndDate(), DateTimeFormatter.ofPattern("yyyyMMdd"));
                Duration duration = Duration.between(beginDate.atTime(0, 0, 0),endDate.atTime(0, 0, 0));
                long days = duration.toDays(); //相差的天数
                if (days < 0) {
                    return R.error(RetCodeEnum.PARAM_ERROR.getCode(),"endDate早于beginDate");
                }
                if (days > 366) {
                    return R.error(RetCodeEnum.PARAM_ERROR.getCode(),"beginDate与endDate间隔的天数不能超过365天");
                }
            } catch (Exception e) {
                log.error("参数有误：beginDate :{"+ req.getBeginDate() + "}, endDate :{"+ req.getEndDate() +"}",e);
                return R.error(RetCodeEnum.PARAM_ERROR.getCode(),"beginDate或endDate格式不正确");
            }
            queryWrapper.ge("confirm_date", req.getBeginDate());
            queryWrapper.le("confirm_date",req.getEndDate());

            //（按交易确认日期confirmDate（若存在）、交易账号tradeAcco（若存在）、基金账号fundAcco（若存在）、托管人编码trustNo逆序排列）
            queryWrapper.orderBy(true,false, "confirm_date","trade_acco","fund_acco","trust_no");
            //2 执行检索
            IPage<CustShareSeqInfoEntity> page = this.page(
                    new Query<CustShareSeqInfoEntity>().getPage(pageParams),
                    queryWrapper
            );
            //封装数据
            PageUtils pageUtils = new PageUtils(page);
            List<CustShareSeqInfoEntity> entities = page.getRecords();
            //entities 转vo
            ArrayList<CustShareSeqInfoVo> vos = new ArrayList<>();
            for (CustShareSeqInfoEntity entity : entities) {
                vos.add(CustShareSeqInfoVo.builder()
                        .id(entity.getId())
                        .seqNo(entity.getSeqNo())
                        .cserialNo(entity.getCserialNo())
                        .requestNo(entity.getRequestNo())
                        .fundCode(entity.getFundCode())
                        .innerFundCode(entity.getInnerFundCode())
                        .fundName(entity.getFundName())
                        .agencyNo(entity.getAgencyNo())
                        .agencyName(entity.getAgencyName())
                        .branchCode(entity.getBranchCode())
                        .branchName(entity.getBranchName())
                        .fundAcco(entity.getFundAcco())
                        .tradeAcco(entity.getTradeAcco())
                        .businessName(entity.getBusinessName())
                        .requestDate(entity.getRequestDate())
                        .confirmDate(entity.getConfirmDate())
                        .bonusMethod(entity.getBonusMethod())
                        .shareLevel(entity.getShareLevel())
                        .shareType(entity.getShareType())
                        .occurShares(Objects.isNull(entity.getOccurShares())?null:entity.getOccurShares().toString())
                        .occurBalance(Objects.isNull(entity.getOccurBalance())?null:entity.getOccurBalance().toString())
                        .occurSharesFreeze(Objects.isNull(entity.getOccurSharesFreeze())?null:entity.getOccurSharesFreeze().toString())
                        .lastFreezeShare(Objects.isNull(entity.getLastFreezeShare())?"":entity.getLastFreezeShare().toString())
                        .lastHoldShares(Objects.isNull(entity.getLastHoldShares())?null:entity.getLastHoldShares().toString())
                        .currency(entity.getCurrency())
                        .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 CustShareSeqInfoServiceImpl RRException is :", rrException);
            return R.error(RetCodeEnum.OPERATION_ERROR.getCode(), rrException.getMsg());
        } catch (Exception e) {
            log.error("the QueryDataVo is :" + JSON.toJSONString(vo) + ".the CustShareSeqInfoServiceImpl Exception is :", e);
            return R.error(RetCodeEnum.OPERATION_ERROR.getCode(), "查询数据失败!");
        }
    }

    @Override
    public R updateData(String type, List<CustShareSeqInfoEntity> datas) {
        return null;
    }
    public String querySeqNo(String trustNo,String admin,String innerfundCode,String cserialNo){
        QueryWrapper<CustShareSeqInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("trust_no",trustNo);
        queryWrapper.eq("admin",admin);
        queryWrapper.eq("inner_fund_code",innerfundCode);
        queryWrapper.eq("cserial_no",cserialNo);
        queryWrapper.select("seq_no");
        CustShareSeqInfoEntity custShareSeqInfoEntity = baseMapper.selectOne(queryWrapper);
        String seqNo = custShareSeqInfoEntity.getSeqNo();
        return seqNo;
    }
}