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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.friday.custody.utils.*;
import com.friday.custody.enums.RetCodeEnum;
import com.friday.custody.exception.RRException;
import com.friday.custody.req.QueryDataReq;
import com.friday.custody.req.TgAccountSeqInfoReq;
import com.friday.custody.service.basicService.TgAccountSeqInfoService;
import com.friday.custody.service.logicService.DataProcessService;
import com.friday.custody.vo.TgAccountSeqInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

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.TgAccountSeqInfoDao;
import com.friday.custody.entity.TgAccountSeqInfoEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

/**
 * 17 托管⼾流⽔表（TGAccount_seq_info）
 */
@Service("tgAccountSeqInfoService")
@Slf4j
public class TgAccountSeqInfoServiceImpl extends ServiceImpl<TgAccountSeqInfoDao, TgAccountSeqInfoEntity>
        implements TgAccountSeqInfoService, DataProcessService<TgAccountSeqInfoEntity> {

    @Autowired
    TgAccountSeqInfoDao tgAccountSeqInfoDao;

    @Autowired
    TenantEscrowAuthorizationInfoServiceImpl tenantEscrowAuthorizationInfoService;


    @Override
    public R saveData(String type, List<TgAccountSeqInfoEntity> datas) {
        for (TgAccountSeqInfoEntity entity : datas) {
            try {
                //判断seqNo是否为空
                //1.如果不为空,根据admin,trustNo,seqNo查询是否已存在 如果已存在则不落库
                if (StringUtils.isNotBlank(entity.getSeqNo())) {
                    List<TgAccountSeqInfoEntity> tgAccountSeqInfoEntities = baseMapper.queryBySeqNo(entity.getSeqNo(), entity.getTrustNo(), entity.getAdmin());
                    if (!CollectionUtils.isEmpty(tgAccountSeqInfoEntities)) {
                        continue;
                    }
                    entity.setUniqueKey(entity.getAdmin() + entity.getTrustNo() + entity.getSeqNo());
                    baseMapper.insert(entity);
                }
                //2.如果为空, 根据【基金备案编码fundCode】、【对方账户opAccount】、【发生日期transferDate】、【发生时间tranferTime】、【银行摘要summary】查询是否已存在,如果已存在则不落库
                if (StringUtils.isBlank(entity.getSeqNo())) {
                    List<TgAccountSeqInfoEntity> tgAccountSeqInfoEntities = queryByEntity(entity);
                    if (!CollectionUtils.isEmpty(tgAccountSeqInfoEntities)) {
                        continue;
                    }
                    entity.setSeqNo(StrUtil.getRandomStr(32));
                    entity.setUniqueKey(entity.getAdmin() + entity.getFundCode() + entity.getOpAccount() + entity.getTransferDate() + entity.getTransferTime() + entity.getSummary());
                    baseMapper.insert(entity);
                }
            } catch (Exception e) {
                log.error("保存tg_Account_seq_info失败!", e);
            }
            //todo 需要写一个记录失败的表
        }
        return R.ok();
    }

    private List<TgAccountSeqInfoEntity> queryByEntity(TgAccountSeqInfoEntity entity) {
        if (ObjectUtils.isEmpty(entity)) {
            return null;
        }
        LambdaQueryWrapper<TgAccountSeqInfoEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TgAccountSeqInfoEntity::getOpAccount, entity.getOpAccount());
        queryWrapper.eq(TgAccountSeqInfoEntity::getTransferDate, entity.getTransferDate());
        queryWrapper.eq(TgAccountSeqInfoEntity::getTransferTime, entity.getTransferTime());
        queryWrapper.eq(TgAccountSeqInfoEntity::getSummary, entity.getSummary());
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public R queryData(QueryDataReq vo) {
        try {
            log.info("开始查询托管户流水信息表...,租户信息为:{}", JSON.toJSONString(vo));
            //1 封装查询参数
            TgAccountSeqInfoReq tgAccountSeqInfoReq = JSON.parseObject(vo.getParams(), TgAccountSeqInfoReq.class);
            //1.1 封装分页查询参数
            Map<String, Object> pageParams = PageUtil.getPageParams(tgAccountSeqInfoReq);
            //1.2 封装查询参数
            QueryWrapper<TgAccountSeqInfoEntity> queryWrapper = new QueryWrapper<>();
            String tenantName = vo.getTenantName();
            queryWrapper.eq("admin", tenantName);
            if (StringUtils.isNotBlank(tgAccountSeqInfoReq.getFundCode())) {
                queryWrapper.eq("fund_code", tgAccountSeqInfoReq.getFundCode());
            }
            if (StringUtils.isNotBlank(tgAccountSeqInfoReq.getAccount())) {
                queryWrapper.eq("account", tgAccountSeqInfoReq.getAccount());
            }
            if (StringUtils.isNotBlank(tgAccountSeqInfoReq.getInnerFundCode())) {
                queryWrapper.eq("inner_fund_code", tgAccountSeqInfoReq.getInnerFundCode());
            }
            //（按本方银行账号account（若存在）、发生日期transferDate（若存在）、发生时间transferTime（若存在）、托管人编码trustNo逆序排列）
            queryWrapper.orderBy(true, false, "account", "transfer_date", "transfer_time", "trust_no");
            //2 执行检索
            IPage<TgAccountSeqInfoEntity> page = this.page(
                    new Query<TgAccountSeqInfoEntity>().getPage(pageParams),
                    queryWrapper
            );
            //封装数据
            PageUtils pageUtils = new PageUtils(page);
            List<TgAccountSeqInfoEntity> entities = page.getRecords();
            //entities 转vo
            ArrayList<TgAccountSeqInfoVo> vos = new ArrayList<>();
            for (TgAccountSeqInfoEntity entity : entities) {
                //中信查询特别处理
                String trustNo = entity.getTrustNo();
                String opAccount;
                if ("35".equals(trustNo)) {
                    opAccount = entity.getOpAccount();
                } else {
                    opAccount = StringUtils.isEmpty(entity.getOpAccount()) ? null : entity.getOpAccount();
                }

                vos.add(TgAccountSeqInfoVo.builder()
                        .id(entity.getId())
                        .seqNo(entity.getSeqNo())
                        .fundCode(entity.getFundCode())
                        .innerFundCode(entity.getInnerFundCode())
                        .fundName(entity.getFundName())
                        .transferInOut(entity.getTransferInOut())
                        .bankName(entity.getBankName())
                        .account(entity.getAccount())
                        .accountName(entity.getAccountName())
                        .largePayAcco(entity.getLargePayAcco())
                        .largeBankName(entity.getLargeBankName())
                        .opBankName(entity.getOpBankName())
                        .opAccount(opAccount)
                        .opAccountName(entity.getOpAccountName())
                        .opLargePayAcco(entity.getOpLargePayAcco())
                        .opLargeBankName(entity.getOpLargeBankName())
                        .amount(Objects.isNull(entity.getAmount()) ? null : entity.getAmount().toString())
                        .balance(Objects.isNull(entity.getBalance()) ? null : entity.getBalance().toString())
                        .transferDate(Objects.isNull(entity.getTransferDate()) ? null : entity.getTransferDate().split(" ")[0].replace("-", ""))
                        .transferTime(entity.getTransferTime())
                        .summary(entity.getSummary())
                        .currency(entity.getCurrency())
                        .updateDate(entity.getUpdateDate())
                        .memo(entity.getMemo())
                        .trustNo(trustNo)
                        .build());
            }
            pageUtils.setList(vos);
            log.info("托管户流水信息查询成功...");
            return R.ok("托管户流水信息查询成功").put("data", pageUtils);
        } catch (RRException rrException) {
            log.error("the QueryDataVo is :" + JSON.toJSONString(vo) + ".the TgAccountSeqInfoServiceImpl RRException is :", rrException);
            return R.error(RetCodeEnum.OPERATION_ERROR.getCode(), rrException.getMsg());
        } catch (Exception e) {
            log.error("the QueryDataVo is :" + JSON.toJSONString(vo) + ".the TgAccountSeqInfoServiceImpl Exception is :", e);
            return R.error(RetCodeEnum.OPERATION_ERROR.getCode(), "查询数据失败!");
        }
    }

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

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

    public List<String> getFundCodeList(String trustNo) {
        return tgAccountSeqInfoDao.getFundCodeList(trustNo);
    }


    public List<TgAccountSeqInfoEntity> getFundCodeAndAccountList(String trustNo, String admin) {
        log.info("TgAccountSeqInfoServiceImpl:getFundCodeAndAccountList:trustNo={},admin={}",trustNo,admin);
        QueryWrapper<TgAccountSeqInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("trust_no", trustNo);
        queryWrapper.eq("admin", admin);

        queryWrapper.select("DISTINCT fund_code,account");
        List<TgAccountSeqInfoEntity> tgAccountSeqInfoEntities = this.baseMapper.selectList(queryWrapper);
        log.info("TgAccountSeqInfoServiceImpl:getFundCodeAndAccountList:result={}",JSON.toJSONString(tgAccountSeqInfoEntities));
        return tgAccountSeqInfoEntities;
    }

}