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

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.checkerframework.checker.units.qual.C;
import org.dromara.common.core.service.BaseService;
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.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.dromara.payment.channel.domain.bo.BusChannelSalesmanBo;
import org.dromara.payment.channel.domain.vo.BusChannelSalesmanVo;
import org.dromara.payment.channel.domain.BusChannelSalesman;
import org.dromara.payment.channel.mapper.BusChannelSalesmanMapper;
import org.dromara.payment.channel.service.IBusChannelSalesmanService;

import java.sql.SQLIntegrityConstraintViolationException;
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 BusChannelSalesmanServiceImpl extends BaseService implements IBusChannelSalesmanService {

    private final BusChannelSalesmanMapper baseMapper;

    @Override
    public TableDataInfo<BusChannelSalesmanVo> selectSaleMans(BusChannelSalesmanBo bo, PageQuery pageQuery) {

        QueryWrapper<BusChannelSalesman> lqw = Wrappers.query();
        lqw.between(bo.getStartTime() != null ,"t.create_time",bo.getStartTime(),bo.getEndTime());
        lqw.like(StringUtils.isNotEmpty(bo.getName()),"t.name",bo.getName());
        lqw.like(StringUtils.isNotEmpty(bo.getNo()),"t.no",bo.getNo());
        lqw.like(StringUtils.isNotEmpty(bo.getChannelName()),"t2.name",bo.getChannelName());
        lqw.orderByDesc("t.create_time");
        Page page =  pageQuery.build();
        Page<BusChannelSalesmanVo> result = this.baseMapper.selectSaleMans(page, lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询代理商业务员
     */
    @Override
    public BusChannelSalesmanVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询代理商业务员列表
     */
    @Override
    public TableDataInfo<BusChannelSalesmanVo> queryPageList(BusChannelSalesmanBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BusChannelSalesman> lqw = buildQueryWrapper(bo);
        Page<BusChannelSalesmanVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询代理商业务员列表
     */
    @Override
    public List<BusChannelSalesmanVo> queryList(BusChannelSalesmanBo bo) {
        return baseMapper.selectSaleMansList();
    }

    private LambdaQueryWrapper<BusChannelSalesman> buildQueryWrapper(BusChannelSalesmanBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BusChannelSalesman> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getChannelId() != null, BusChannelSalesman::getChannelId, bo.getChannelId());
        lqw.eq(StringUtils.isNotBlank(bo.getChannelNo()), BusChannelSalesman::getChannelNo, bo.getChannelNo());
        lqw.like(StringUtils.isNotBlank(bo.getName()), BusChannelSalesman::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getNo()), BusChannelSalesman::getNo, bo.getNo());
        lqw.eq(bo.getCreateTime() != null, BusChannelSalesman::getCreateTime, bo.getCreateTime());
        lqw.eq(StringUtils.isNotBlank(bo.getCreateBy()), BusChannelSalesman::getCreateBy, bo.getCreateBy());
        lqw.orderByDesc(true, BusChannelSalesman::getCreateTime);
        return lqw;
    }

    public static void main(String[] args) {
        for(int i = 0 ; i < 100 ;i++){
            System.out.println(getSalemano());
        }
    }

    /**
     * 新增代理商业务员
     */
    @Override
    public Boolean insertByBo(BusChannelSalesmanBo bo) {
        BusChannelSalesman add = MapstructUtils.convert(bo, BusChannelSalesman.class);
        validEntityBeforeSave(add);
        add.setChannelId(LoginHelper.getBusId());
        add.setChannelNo(LoginHelper.getNo());
        add.setCreateBy(LoginHelper.getUserId());
        add.setCreateTime(new Date());

        if(StringUtils.isEmpty(add.getNo())){
            String no = getSalemano();
            add.setNo(no);
        }
        add.setChannelId(LoginHelper.getBusId());
        boolean flag = false;
        try{
             flag = baseMapper.insert(add) > 0;
        }catch (Exception e){
            e.printStackTrace();
            if(e instanceof DuplicateKeyException){
                String no = getSalemano();
                bo.setNo(no);
                return this.insertByBo(bo);
            }else{
                throw  e;
            }
        }
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    public static String getSalemano() {
        return RandomUtil.randomString("0123456789",6);
    }

    /**
     * 修改代理商业务员
     */
    @Override
    public Boolean updateByBo(BusChannelSalesmanBo bo) {
        if(bo.getId() == null){
            this.invalidationParamsException("业务员ID不能为空");
        }
        if(StringUtils.isEmpty(bo.getName())){
            this.invalidationParamsException("业务员名称不能为空");
        }
        BusChannelSalesman update = MapstructUtils.convert(bo, BusChannelSalesman.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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