package com.jeequan.jeepay.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.db.entity.*;
import com.jeequan.jeepay.service.mapper.DivisionTaskMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户分账模板表 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2024-04-02
 */
@Service
public class DivisionTaskService extends ServiceImpl<DivisionTaskMapper, DivisionTask>{

    @Autowired
    private DivisionSubjectService mchDivisionTemplateConfigService;

    @Autowired
    private MchApplymentService mchApplymentService;
    /**
     * 分页查询
     * @param iPage
     * @param entity
     * @return
     */
    public IPage<DivisionTask> pageList(Page<DivisionTask> iPage, DivisionTask entity) {
        LambdaQueryWrapper<DivisionTask> wrapper = DivisionTask.gw(entity);
        wrapper.orderByDesc(DivisionTask::getUpdatedAt);
        // 时间范围条件
        entity.buildQueryDateRange();
        return baseMapper.pageList(iPage,entity);
    }

    /**
     * 新增分账模板
     * @param template
     * @param mchNo
     */
    public void addSave(DivisionTask template, String mchNo) {
        template.setMchNo(mchNo);
        template.preCheck();
        try {
            save(template);
        }catch (DuplicateKeyException e){
            throw new BizException("每个通道只能设置一种分账模板");
        }
    }

    /**
     * 获取分账对象详情
     * @param taskId
     * @return
     */
    public DivisionTask getDivisionSubject(String taskId) {
        DivisionTask template = baseMapper.selectById(taskId);
        if(template == null){
            throw new BizException("数据异常");
        }
        List<DivisionSubject> receiveList = mchDivisionTemplateConfigService.listByTemplateIdAndType(taskId, DivisionSubject.RECEIVE_TYPE);
        List<DivisionSubject> expendList = mchDivisionTemplateConfigService.listByTemplateIdAndType(taskId, DivisionSubject.EXPEND_TYPE);
        template.setReceiveList(receiveList);
        template.setExpendList(expendList);
        return template;
    }

    /**
     * 保存配置
     * @param template
     */
    public void saveConfig(DivisionTask template) {
        template.preConfigCheck();
        DivisionTask ext = baseMapper.selectById(template.getTaskId());
        if(ext == null){
            throw new BizException("模板数据异常");
        }
        switch (ext.getDivisionMode()){
            case DivisionTask.DIV_MODE_RATIO:
                template.checkDivisionRationValue(ext);
                break;
            case DivisionTask.DIV_MODE_AMOUNT:
                template.checkDivisionAmountValue(ext);
                break;
            default:
                throw new BizException("未知的分账模式");
        }
        List<DivisionSubject> receiveList = template.getReceiveList();
        for (DivisionSubject receive:receiveList) {
            receive.setTaskId(ext.getTaskId());
            receive.setMchNo(ext.getMchNo());
            receive.setType(DivisionSubject.RECEIVE_TYPE);
            checkDivNoInfo(receive);
        }
        List<DivisionSubject> expendList = template.getExpendList();
        for (DivisionSubject expend:expendList) {
            expend.setTaskId(ext.getTaskId());
            expend.setMchNo(ext.getMchNo());
            expend.setType(DivisionSubject.EXPEND_TYPE);
            checkDivNoInfo(expend);
        }
        receiveList.addAll(expendList);
        mchDivisionTemplateConfigService.saveOrUpdateBatch(receiveList);
    }

    /**
     * 校验分账方编号信息
     * @param config
     * @return
     */
    private void checkDivNoInfo(DivisionSubject config) {
        //如果是商户类型就查询商户数据是否正常
        if(DivisionSubject.USER_TYPE_MERCHANT == config.getUserType()){
            MchApplyment applyment = mchApplymentService.getById(config.getDivisionNo());
            if(applyment == null){
                throw new BizException("商户信息异常");
            }
            config.setChannelDivisionNo(applyment.getChannelMchNo());
        }
    }
}
