package org.dromara.payment.channel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.payment.channel.domain.BusChannelCashout;
import org.dromara.payment.channel.domain.vo.BusChannelVo;
import org.dromara.payment.channel.mapper.BusChannelMapper;
import org.dromara.payment.common.domain.BusAccounts;
import org.dromara.payment.common.domain.bo.BusAccountsBo;
import org.dromara.payment.common.mapper.BusAccountsMapper;
import org.dromara.payment.sys.domain.vo.SysSydAccountVo;
import org.dromara.payment.sys.domain.vo.SysSydVo;
import org.springframework.stereotype.Service;
import org.dromara.payment.channel.domain.bo.BusChannelAccountBo;
import org.dromara.payment.channel.domain.vo.BusChannelAccountVo;
import org.dromara.payment.channel.domain.BusChannelAccount;
import org.dromara.payment.channel.mapper.BusChannelAccountMapper;
import org.dromara.payment.channel.service.IBusChannelAccountService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 代理商账户Service业务层处理
 *
 * @author LionLi
 * @date 2024-04-10
 */
@RequiredArgsConstructor
@Service
public class BusChannelAccountServiceImpl implements IBusChannelAccountService {

    private final BusChannelAccountMapper baseMapper;

    private final BusChannelMapper channelMapper;

    private final BusAccountsMapper accountsMapper;

    /**
     * 查询代理商账户
     */
    @Override
    public BusChannelAccountVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询代理商账户列表
     */
    @Override
    public TableDataInfo<BusChannelAccountVo> queryPageList(BusChannelAccountBo bo, PageQuery pageQuery) {
        QueryWrapper<BusChannelAccount> lqw = buildQueryWrapper(bo);
        Page<BusChannelAccountVo> result = baseMapper.queryPageList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询代理商账户列表
     */
    @Override
    public List<BusChannelAccountVo> queryList(BusChannelAccountBo bo) {
        QueryWrapper<BusChannelAccount> lqw = buildQueryWrapper(bo);
        return baseMapper.queryList(lqw);
    }

    private QueryWrapper<BusChannelAccount> buildQueryWrapper(BusChannelAccountBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<BusChannelAccount> lqw = new QueryWrapper<BusChannelAccount>(new BusChannelAccount());
        lqw.eq(bo.getChannelId() != null,"t.channel_id",bo.getChannelId());
        lqw.eq(bo.getStatus() != null,"t.status",bo.getStatus());
        if(StringUtils.isNotBlank(bo.getParams().get("begin_time")) && StringUtils.isNotBlank(bo.getParams().get("end_time"))){
            lqw.between("t.add_time",bo.getParams().get("begin_time")+" 00:00:00",bo.getParams().get("end_time")+" 23:59:59");
        }
        if(StringUtils.isNotBlank(bo.getParams().get("channel_name"))){
            lqw.like("t1.name",bo.getParams().get("channel_name"));
        }
        if(StringUtils.isNotBlank(params.get("channel_no"))){
            lqw.eq("t1.no",params.get("channel_no"));
        }
        if(StringUtils.isNotBlank(params.get("level_channel_no"))){
            lqw.likeRight("t1.no",params.get("level_channel_no"));
        }
        if(StringUtils.isNotBlank(params.get("dw_level"))){
            lqw.eq("t1.dw_level",params.get("dw_level"));
        }
        String yesterday = DateUtils.parseDateToString(DateUtils.YYYY_MM_DD,DateUtils.getEndDateByDays(new Date(),-1));
        lqw.getEntity().setFlowsBeginTime(yesterday+" 00:00:00");
        lqw.getEntity().setFlowsEndTime(yesterday+" 23:59:59");
        return lqw;
    }

    /**
     * 新增代理商账户
     */
    @Override
    @Transactional
    public Boolean insertByBo(BusChannelAccountBo bo) {
        BusChannelAccount add = MapstructUtils.convert(bo, BusChannelAccount.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        BusAccounts bab = new BusAccounts();
        bab.setAccId(0L);
        bab.setIsDefault(1L);
        bab.setUnitId(bo.getChannelId());
        bab.setAddYpe(7);
        bab.setSydId(0L);
        this.accountsMapper.insert(bab);
        return flag;
    }

    /**
     * 修改代理商账户
     */
    @Override
    public Boolean updateByBo(BusChannelAccountBo bo) {
        BusChannelAccount update = MapstructUtils.convert(bo, BusChannelAccount.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusChannelAccount entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除代理商账户
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateBalance(long unitId, long amount) {
        Integer baseNum = accountsMapper.updateBalance(0L,unitId,amount,null);
        Integer curNum = baseMapper.updateBalance(unitId,amount);
        return baseNum > 0 && curNum > 0 ? 1 : 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateFrozen(long unitId, long amount) {
        Integer baseNum = accountsMapper.updateFrozen(0L,unitId,amount,null);
        Integer curNum = baseMapper.updateFrozen(unitId,amount);
        return baseNum > 0 && curNum > 0 ? 1 : 0;
    }

    @Override
    public BusChannelAccountVo getCashoutAccount(Long id) {
        BusChannelAccountVo rtn = baseMapper.selectVoById(id);
        if(rtn != null){
            BusChannelVo vo  = channelMapper.selectVoById(rtn.getChannelId());
            rtn.setAccName(vo.getKhm());
            rtn.setBankCard(vo.getBankCard());
            rtn.setKfd(vo.getKhd());
            rtn.setKfh(vo.getKhh());
            rtn.setKhhNo(vo.getKhhNo());
            rtn.setChannelNo(vo.getNo());
        }
        return rtn;
    }
}
