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

import com.alibaba.dubbo.common.utils.CollectionUtils;
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.FundOpenInfoDao;
import com.friday.custody.entity.FundInfoEntity;
import com.friday.custody.entity.FundOpenInfoEntity;
import com.friday.custody.enums.RetCodeEnum;
import com.friday.custody.exception.RRException;
import com.friday.custody.req.FundOpenInfoReq;
import com.friday.custody.req.QueryDataReq;
import com.friday.custody.service.basicService.FundOpenInfoService;
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.FundOpenInfoVO;
import lombok.extern.slf4j.Slf4j;
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 org.springframework.util.ObjectUtils;

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("fundOpenInfoService")
@Slf4j
public class FundOpenInfoServiceImpl extends ServiceImpl<FundOpenInfoDao, FundOpenInfoEntity>
        implements FundOpenInfoService, DataProcessService<FundOpenInfoEntity> {

    @Autowired
    private FundInfoServiceImpl fundInfoService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveData(String type, List<FundOpenInfoEntity> fundOpenInfoEntities) {
        if (ObjectUtils.isEmpty(fundOpenInfoEntities)) {
            return R.ok();
        }
        for (FundOpenInfoEntity entity : fundOpenInfoEntities) {
            //如果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 ("25".equals(entity.getTrustNo())) {
                entity.setUniqueKey(entity.getAdmin() + entity.getTrustNo() + entity.getInnerFundCode() + entity.getFundName() + entity.getFundOpenDate());
            } else if ("31".equals(entity.getTrustNo())) {
                //当innerFundCode为空的时候，不添加innerFundCode作为唯一索引
                if (StringUtils.isBlank(entity.getInnerFundCode())) {
                    entity.setUniqueKey(entity.getAdmin() + entity.getTrustNo() + entity.getFundCode() + entity.getFundOpenDate());
                } else {
                    entity.setUniqueKey(entity.getAdmin() + entity.getTrustNo() + entity.getFundCode() + entity.getInnerFundCode() + entity.getFundOpenDate());
                }
            } else if ("21".equals(entity.getTrustNo()) || "35".equals(entity.getTrustNo())) {
                entity.setUniqueKey(entity.getAdmin() + entity.getTrustNo() + entity.getFundCode() + entity.getFundOpenDate());
            } else {
                entity.setUniqueKey(entity.getAdmin() + entity.getTrustNo() + entity.getInnerFundCode() + entity.getFundOpenDate());
            }

        }
        //根据主键去重
        List<FundOpenInfoEntity> uniqueFundOpenInfoList = fundOpenInfoEntities.stream().collect(Collectors.collectingAndThen
                (Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing
                        (FundOpenInfoEntity::getUniqueKey))), ArrayList::new));
        List<String> rawUniqueKeyList = uniqueFundOpenInfoList.stream().map(FundOpenInfoEntity::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(uniqueFundOpenInfoList);
        if (!saveStatus) {
            log.error("保存基金开放日:{}", ukList);
        }
        return R.ok();

    }

    @Override
    public R queryData(QueryDataReq vo) {
        try {
            log.info("开始查询基金产品开放信息表...,租户信息为:{}", JSON.toJSONString(vo));
            //1 封装查询参数
            FundOpenInfoReq fundOpenInfoReq = JSON.parseObject(vo.getParams(), FundOpenInfoReq.class);
            //1.1 封装分页查询参数
            Map<String, Object> pageParams = PageUtil.getPageParams(fundOpenInfoReq);
            //1.2 封装查询参数
            QueryWrapper<FundOpenInfoEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("admin", vo.getTenantName());
            if (StringUtils.isNotBlank(fundOpenInfoReq.getFundCode())) {
                queryWrapper.eq("fund_code", fundOpenInfoReq.getFundCode());
            }
            if (StringUtils.isNotBlank(fundOpenInfoReq.getInnerFundCode())) {
                queryWrapper.likeRight("inner_fund_code", fundOpenInfoReq.getInnerFundCode());
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            Calendar c = Calendar.getInstance();
            //开始和结束时间都为空，默认为一年
            if (StringUtils.isBlank(fundOpenInfoReq.getBeginDate())&&StringUtils.isBlank(fundOpenInfoReq.getEndDate())) {
                c.setTime(new Date());
                c.add(Calendar.YEAR, -1);
                Date m = c.getTime();
                String beginYear = format.format(m);
                fundOpenInfoReq.setBeginDate(beginYear);
                fundOpenInfoReq.setEndDate(format.format(new Date()));
            }
            //开始不为空和结束时间为空，默认当天
            if (StringUtils.isBlank(fundOpenInfoReq.getEndDate())&&StringUtils.isNotBlank(fundOpenInfoReq.getBeginDate())) {
                c.setTime(format.parse(fundOpenInfoReq.getBeginDate()));
                c.add(Calendar.YEAR, 1);
                Date m = c.getTime();
                String endYear = format.format(m);
                fundOpenInfoReq.setBeginDate(fundOpenInfoReq.getBeginDate());
                fundOpenInfoReq.setEndDate(endYear);
            }
            try {
                LocalDate beginDate = LocalDate.parse(fundOpenInfoReq.getBeginDate(), DateTimeFormatter.ofPattern("yyyyMMdd"));
                LocalDate endDate = LocalDate.parse(fundOpenInfoReq.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 :{"+ fundOpenInfoReq.getBeginDate() + "}, endDate :{"+ fundOpenInfoReq.getEndDate() +"}",e);
                return R.error(RetCodeEnum.PARAM_ERROR.getCode(),"beginDate或endDate格式不正确");
            }
            queryWrapper.ge("fund_open_date", fundOpenInfoReq.getBeginDate());
            queryWrapper.le("fund_open_date",fundOpenInfoReq.getEndDate());
            queryWrapper.orderBy(true,false, "fund_open_date","fund_code","inner_fund_code","trust_no");

            //2 执行检索
            IPage<FundOpenInfoEntity> page = this.page(
                    new Query<FundOpenInfoEntity>().getPage(pageParams),
                    queryWrapper
            );
            //封装数据
            PageUtils pageUtils = new PageUtils(page);
            List<FundOpenInfoEntity> entities = page.getRecords();
            //entities 转vo
            ArrayList<FundOpenInfoVO> vos = new ArrayList<>();
            for (FundOpenInfoEntity entity : entities) {
                String openStatus = entity.getOpenStatus();
                String[] openStatusArr = new String[10];
                if (StringUtils.isNotBlank(openStatus)) {
                    openStatusArr = openStatus.split(",");
                }
                vos.add(FundOpenInfoVO.builder()
                        .id(entity.getId())
                        .fundCode(entity.getFundCode())
                        .fundName(entity.getFundName())
                        .innerFundCode(entity.getInnerFundCode())
                        .fundOpenDate(entity.getFundOpenDate())
                        .openType(entity.getOpenType())
                        .openStatus(openStatusArr)
                        .ifFixedTime(String.valueOf(entity.getIfFixedTime()))
                        .remark(entity.getRemark())
                        .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 FundOpenInfoServiceImpl RRException is :", rrException);
            return R.error(RetCodeEnum.OPERATION_ERROR.getCode(), rrException.getMsg());
        } catch (Exception e) {
            log.error("the QueryDataVo is :" + JSON.toJSONString(vo) + ".the FundOpenInfoServiceImpl Exception is :", e);
            return R.error(RetCodeEnum.OPERATION_ERROR.getCode(), "查询数据失败!");
        }
    }

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

}