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.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.friday.custody.dao.FundFeeDataInfoDao;
import com.friday.custody.entity.FundFeeDataInfoEntity;
import com.friday.custody.entity.FundInfoEntity;
import com.friday.custody.enums.RetCodeEnum;
import com.friday.custody.exception.RRException;
import com.friday.custody.req.FundFeeDataInfoReq;
import com.friday.custody.req.QueryDataReq;
import com.friday.custody.service.basicService.FundFeeDataInfoService;
import com.friday.custody.service.logicService.DataDictionaryBasicService;
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.FundFeeDataInfoVO;
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("fundFeeDataInfoService")
@Slf4j
public class FundFeeDataInfoServiceImpl extends ServiceImpl<FundFeeDataInfoDao, FundFeeDataInfoEntity> implements FundFeeDataInfoService, DataProcessService<FundFeeDataInfoEntity> {

    @Autowired
    private DataDictionaryBasicService dataDictionaryBasicService;
    @Autowired
    private FundInfoServiceImpl fundInfoService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveData(String type, List<FundFeeDataInfoEntity> datas) {
        List<FundFeeDataInfoEntity> insertList = new ArrayList<>();
        List<FundFeeDataInfoEntity> updateList = new ArrayList<>();
        for (FundFeeDataInfoEntity 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);
                }
            }

            entity.setUniqueKey(entity.getAdmin() + entity.getTrustNo() + entity.getInnerFundCode() + entity.getSubjectCode() + entity.getConfirmDate());
            if ("34".equals(entity.getTrustNo()) || "31".equals(entity.getTrustNo())) {
                entity.setUniqueKey(entity.getAdmin() + entity.getTrustNo() + entity.getFundCode() + entity.getFundName() + entity.getSubjectCode() + entity.getConfirmDate());
            }
            if ("21".equals(entity.getTrustNo()) || "43".equals(entity.getTrustNo())) {
                entity.setUniqueKey(entity.getAdmin() + entity.getTrustNo() + entity.getFundCode() + entity.getSubjectCode() + entity.getConfirmDate());
            }
        }
        List<String> rawUniqueKeyList = datas.stream().map(FundFeeDataInfoEntity::getUniqueKey).collect(Collectors.toList());
        String ukList = String.join("--", rawUniqueKeyList);
        Set<String> uniqueKeySet = new HashSet<>();
        if (CollectionUtils.isNotEmpty(rawUniqueKeyList)) {
            uniqueKeySet = baseMapper.queryUniqueKeyList(rawUniqueKeyList);

        }
        for (FundFeeDataInfoEntity entity : datas){
            if (uniqueKeySet.contains(entity.getUniqueKey())){
                updateList.add(entity);
            } else{
                insertList.add(entity);
            }
        }
        if (CollectionUtils.isNotEmpty(insertList)){
            boolean saveStatus = this.saveBatch(insertList);
            if (!saveStatus){
                log.error("保存基金费用数据失败:{}",ukList);
            }
        }

        this.batchUpdateByUniqueKey(updateList);
        return R.ok();
    }

    private void batchUpdateByUniqueKey(List<FundFeeDataInfoEntity> updateList) {
        for (FundFeeDataInfoEntity entity : updateList){
            LambdaUpdateWrapper<FundFeeDataInfoEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(FundFeeDataInfoEntity::getUniqueKey, entity.getUniqueKey());
            this.update(entity, updateWrapper);
        }
    }


    @Override
    public R queryData(QueryDataReq vo) {
        try {
            log.info("开始查询基金费用数据表...,租户信息为:{}", JSON.toJSONString(vo));
            //1 封装查询参数
            FundFeeDataInfoReq fundFeeDataInfoReq = JSON.parseObject(vo.getParams(), FundFeeDataInfoReq.class);
            //1.1 封装分页查询参数
            Map<String, Object> pageParams = PageUtil.getPageParams(fundFeeDataInfoReq);
            //1.2 封装查询参数
            QueryWrapper<FundFeeDataInfoEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("admin", vo.getTenantName());
            if (StringUtils.isNotBlank(fundFeeDataInfoReq.getFundCode())) {
                queryWrapper.eq("fund_code", fundFeeDataInfoReq.getFundCode());
            }
            if (StringUtils.isNotBlank(fundFeeDataInfoReq.getInnerFundCode())) {
                queryWrapper.eq("inner_fund_code", fundFeeDataInfoReq.getInnerFundCode());
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            Calendar c = Calendar.getInstance();
            //开始和结束时间都为空，默认为一年
            if (StringUtils.isBlank(fundFeeDataInfoReq.getBeginDate()) && StringUtils.isBlank(fundFeeDataInfoReq.getEndDate())) {
                c.setTime(new Date());
                c.add(Calendar.YEAR, -1);
                Date m = c.getTime();
                String beginYear = format.format(m);
                fundFeeDataInfoReq.setBeginDate(beginYear);
                fundFeeDataInfoReq.setEndDate(format.format(new Date()));
            }
            //开始不为空和结束时间为空，默认当天
            if (StringUtils.isBlank(fundFeeDataInfoReq.getEndDate()) && StringUtils.isNotBlank(fundFeeDataInfoReq.getBeginDate())) {
                c.setTime(format.parse(fundFeeDataInfoReq.getBeginDate()));
                c.add(Calendar.YEAR, 1);
                Date m = c.getTime();
                String endYear = format.format(m);
                fundFeeDataInfoReq.setBeginDate(fundFeeDataInfoReq.getBeginDate());
                fundFeeDataInfoReq.setEndDate(endYear);
            }
            //开始为空和结束时间不为空，默认结束时间往前推一年
            if (StringUtils.isNotBlank(fundFeeDataInfoReq.getEndDate()) && StringUtils.isBlank(fundFeeDataInfoReq.getBeginDate())) {
                c.setTime(format.parse(fundFeeDataInfoReq.getEndDate()));
                c.add(Calendar.YEAR, -1);
                Date m = c.getTime();
                String beginYear = format.format(m);
                fundFeeDataInfoReq.setBeginDate(beginYear);
            }
            try {
                LocalDate beginDate = LocalDate.parse(fundFeeDataInfoReq.getBeginDate(), DateTimeFormatter.ofPattern("yyyyMMdd"));
                LocalDate endDate = LocalDate.parse(fundFeeDataInfoReq.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 :{" + fundFeeDataInfoReq.getBeginDate() + "}, endDate :{" + fundFeeDataInfoReq.getEndDate() + "}", e);
                return R.error(RetCodeEnum.PARAM_ERROR.getCode(), "beginDate或endDate格式不正确");
            }
            if (StringUtils.isNotBlank(fundFeeDataInfoReq.getBeginDate())) {
                queryWrapper.ge("confirm_date", fundFeeDataInfoReq.getBeginDate());
            }
            if (StringUtils.isNotBlank(fundFeeDataInfoReq.getEndDate())) {
                queryWrapper.lt("confirm_date", fundFeeDataInfoReq.getEndDate());
            }
            if (StringUtils.isNotBlank(fundFeeDataInfoReq.getSubjectCode())) {
                queryWrapper.eq("subject_code", fundFeeDataInfoReq.getSubjectCode());
            }
            //（按费用计算日期confirmDate（若存在）、基金备案编码fundCode（若存在）、基金内部代码innerFundCode（若存在）、科目编码subjectCode（若存在）、托管人编码trustNo逆序排列）
            queryWrapper.orderBy(true, false, "confirm_date", "fund_code", "inner_fund_code", "subject_code", "trust_no");

            //2 执行检索
            IPage<FundFeeDataInfoEntity> page = this.page(
                    new Query<FundFeeDataInfoEntity>().getPage(pageParams),
                    queryWrapper
            );
            //封装数据
            PageUtils pageUtils = new PageUtils(page);
            List<FundFeeDataInfoEntity> entities = page.getRecords();
            //entities 转vo;
            List<FundFeeDataInfoVO> vos = new ArrayList<>();
            for (FundFeeDataInfoEntity entity : entities) {
                vos.add(FundFeeDataInfoVO.builder()
                        .id(entity.getId())
                        .fundCode(entity.getFundCode())
                        .innerFundCode(entity.getInnerFundCode())
                        .fundName(entity.getFundName())
                        .confirmDate(entity.getConfirmDate())
                        .subjectCode(entity.getSubjectCode())
                        .subjectName(entity.getSubjectName())
                        .fareDebit(Objects.isNull(entity.getFareDebit()) ? null : entity.getFareDebit().toString())
                        .fareCredit(Objects.isNull(entity.getFareCredit()) ? null : entity.getFareCredit().toString())
                        .fareUnpaid(Objects.isNull(entity.getFareUnpaid()) ? null : entity.getFareUnpaid().toString())
                        .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 fundFeeDataInfoServiceImpl RRException is :", rrException);
            return R.error(RetCodeEnum.OPERATION_ERROR.getCode(), rrException.getMsg());
        } catch (Exception e) {
            log.error("the QueryDataVo is :" + JSON.toJSONString(vo) + ".the fundFeeDataInfoServiceImpl Exception is :", e);
            return R.error(RetCodeEnum.OPERATION_ERROR.getCode(), "查询数据失败!");
        }
    }

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