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.trustService.htsc.common.HtscConstants;
import com.friday.custody.dao.TgAccountBalanceInfoDao;
import com.friday.custody.entity.TgAccountBalanceInfoEntity;
import com.friday.custody.enums.RetCodeEnum;
import com.friday.custody.exception.RRException;
import com.friday.custody.req.QueryDataReq;
import com.friday.custody.req.TgAccountBalanceInfoReq;
import com.friday.custody.service.basicService.TgAccountBalanceInfoService;
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.TgAccountBalanceInfoVo;
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;

/**
 * 16 托管⼾银⾏账⼾余额信息表（TGAccount_balance_info）
 */
@Service("tgAccountBalanceInfoService")
@Slf4j
public class TgAccountBalanceInfoServiceImpl extends ServiceImpl<TgAccountBalanceInfoDao, TgAccountBalanceInfoEntity>
        implements TgAccountBalanceInfoService, DataProcessService<TgAccountBalanceInfoEntity> {

    @Autowired
    TgAccountBalanceInfoDao tgAccountBalanceInfoDao;

    @Autowired
    AccoBalanceChangeRecordServiceImpl accoBalanceChangeRecordService;

    @Autowired
    private DataDictionaryBasicService dataDictionaryBasicService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveData(String type, List<TgAccountBalanceInfoEntity> datas) {
        if (CollectionUtils.isEmpty(datas)){
            return R.ok();
        }
        //设置主键
        datas.forEach(x -> {
            x.setUniqueKey(x.getAdmin() + x.getBankAcco());
        });
        //根据主键去重
        List<TgAccountBalanceInfoEntity> newList = datas.stream().collect(Collectors.collectingAndThen
                (Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing
                        (TgAccountBalanceInfoEntity::getUniqueKey))), ArrayList::new));
        for (TgAccountBalanceInfoEntity entity : newList) {
            try {
                //1.查询库中数据的余额 并查看是否变动
                TgAccountBalanceInfoEntity oldEntity = baseMapper.selectOne(new QueryWrapper<TgAccountBalanceInfoEntity>()
                        .eq("unique_key", entity.getUniqueKey())
                        .eq("trust_no", entity.getTrustNo()));
                if (oldEntity != null && oldEntity.getAccoBalance() != null
                        && entity.getAccoBalance() != null && oldEntity.getAccoBalance().compareTo(entity.getAccoBalance()) != 0) {
                    //查询出该条数据对应的产品名称,产品代码
                    Map<String, String> fundPrdMap = baseMapper.queryTgFundPrt(entity.getAdmin(), entity.getTrustNo(), entity.getBankAcco());
                    accoBalanceChangeRecordService.balanceChangeRemind(fundPrdMap, entity.getAccoBalance(), oldEntity.getAccoBalance(),
                            entity.getAdmin(), HtscConstants.TG_ACCOUNT_TYPE_CODE, entity.getTrustNo());

                }

            } catch (Exception e) {
                log.error("托管余额变动提醒失败!", e);
            }
        }
        List<String> rawUniqueKeyList = newList
                .stream()
                .map(TgAccountBalanceInfoEntity::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(newList);
        if (!saveStatus) {
            log.error("保存TgAccountBalanceInfo失败:{}", ukList);
        }
        return R.ok();
    }

    @Override
    public R queryData(QueryDataReq vo) {
        try {
            log.info("开始查询托管户银行账户余额信息表...,租户信息为:{}", JSON.toJSONString(vo));
            //1 封装查询参数
            TgAccountBalanceInfoReq tgAccountBalanceInfoReq = JSON.parseObject(vo.getParams(), TgAccountBalanceInfoReq.class);
            //1.1 封装分页查询参数
            Map<String, Object> pageParams = PageUtil.getPageParams(tgAccountBalanceInfoReq);
            //1.2 封装查询参数
            QueryWrapper<TgAccountBalanceInfoEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("admin", vo.getTenantName());
            if (StringUtils.isNotBlank(tgAccountBalanceInfoReq.getBankAcco())) {
                queryWrapper.eq("bank_acco", tgAccountBalanceInfoReq.getBankAcco());
            }
            //按银行账号bankAcco（若存在）、更新日期updateDate（若存在）、托管人编码trustNo逆序排列）
            queryWrapper.orderBy(true,false, "bank_acco","update_date","trust_no");
            //2 执行检索
            IPage<TgAccountBalanceInfoEntity> page = this.page(
                    new Query<TgAccountBalanceInfoEntity>().getPage(pageParams),
                    queryWrapper
            );
            //封装数据
            PageUtils pageUtils = new PageUtils(page);
            List<TgAccountBalanceInfoEntity> entities = page.getRecords();
            //entities 转vo
            ArrayList<TgAccountBalanceInfoVo> vos = new ArrayList<>();
            for (TgAccountBalanceInfoEntity entity : entities) {
                vos.add(TgAccountBalanceInfoVo.builder()
                        .id(entity.getId())
                        .bankAcco(entity.getBankAcco())
                        .accoBalance(Objects.isNull(entity.getAccoBalance())?null:entity.getAccoBalance().toString())
                        .availableBalance(Objects.isNull(entity.getAvailableBalance())?null:entity.getAvailableBalance()+"")
                        .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 TgAccountBalanceInfoServiceImpl RRException is :", rrException);
            return R.error(RetCodeEnum.OPERATION_ERROR.getCode(), rrException.getMsg());
        } catch (Exception e) {
            log.error("the QueryDataVo is :" + JSON.toJSONString(vo) + ".the TgAccountBalanceInfoServiceImpl Exception is :", e);
            return R.error(RetCodeEnum.OPERATION_ERROR.getCode(), "查询数据失败!");
        }
    }

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

    public List<String> getBankAccoList(String trustNo,String admin){
        return tgAccountBalanceInfoDao.getBankAccoList(trustNo,admin);
    }
}