package cn.pluss.platform.openAccount.impl;

import cn.pluss.platform.DeviceGoodsService;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.device.DeviceOrderInfoService;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.OpenAccountRecordMapper;
import cn.pluss.platform.openAccount.OpenAccountConfigService;
import cn.pluss.platform.openAccount.OpenAccountRecordService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.DateUtils;
import cn.pluss.platform.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>
 * 用户开户奖励明细 服务实现类
 * </p>
 *
 * @author crystal
 * @since 2022-06-14
 */
@Service
@Slf4j
public class OpenAccountRecordServiceImpl extends ServiceImpl<OpenAccountRecordMapper, OpenAccountRecord> implements OpenAccountRecordService {

    @Resource
    private OpenAccountConfigService openAccountConfigService;
    
    @Resource
    private UserAppService userAppService;

    @Resource
    private DeviceGoodsService deviceGoodsService;

    /**
     * 兼容旧版设备订单开户奖操作
     * @param order
     * @param merchant
     */
    @Override
    public void operatAccountOpen(DeviceMerchantBuy order, MerchantBaseInfo merchant,DeviceOrderInfo info) {
        DeviceGoods goods =  deviceGoodsService.getByCode(info.getCode());
        if(goods != null){
            order.setName(goods.getName());
        }
        order.setCode(info.getCode());
        execute(order,merchant);
    }

    /**
     * 新版设备订单开户奖操作
     * @param order
     * @param merchant
     */
    @Override
    public void operatAccountOpen(MercOrderDetail order, MerchantBaseInfo merchant) {
        execute(order,merchant);
    }

    /**
     * 通用方法
     * @param order
     * @param merchant
     */
    private void execute(Object order, MerchantBaseInfo merchant) {
        UserApp userApp = userAppService.getUserAppByUserId(merchant.getUserId());
        if(userApp == null){
            log.error("【创建开户奖励】失败，用户信息异常");
            return;
        }
        if(userApp.getParentId() == null){
            log.error("【创建开户奖励】当前交易商户上级为空，开户奖创建失败");
            return;
        }
        UserApp pUserApp = userAppService.getUserAppByUserId(userApp.getParentId());
        if(pUserApp == null){
            log.error("【创建开户奖励】当前交易商户上级用户信息为空，开户奖创建失败");
            return;
        }
        BigDecimal rewardAmt = openAccountConfigService.getOpendAccountReward(merchant,pUserApp);
        if(rewardAmt.compareTo(BigDecimal.ZERO) == 0){
            log.info("【创建开户奖励】未获取到配置奖励参数信息");
            return;
        }
        OpenAccountRecord record = OpenAccountRecord.build(order,rewardAmt,merchant,pUserApp);
        save(record);
    }

    @Override
    public <E extends IPage<OpenAccountRecord>> E page(E page, Wrapper<OpenAccountRecord> queryWrapper) {
        OpenAccountRecord entity = queryWrapper.getEntity();
        if(StringUtil.isNotEmpty(entity.getStartTime())){
            ((QueryWrapper)queryWrapper).ge("createDate",entity.getStartTime());
        }
        if(StringUtil.isNotEmpty(entity.getEndTime())){
            ((QueryWrapper)queryWrapper).le("createDate",entity.getEndTime());
        }
        return super.page(page, queryWrapper);
    }

    /**
     * 删除开户奖励
     * @param orderNo
     */
    @Override
    public void removeOpenAccount(String orderNo) {
        OpenAccountRecord record = baseMapper.getByOrderNumberAndType(orderNo,OpenAccountRecord.TYPE_PAY);
        if(record == null){
            return;
        }
        record.setId(null);
        record.setCreateTime(DateUtils.currentDate());
        record.setRewardAmt(record.getRewardAmt().negate());
        record.setType(OpenAccountRecord.REFUND_PAY);
        record.setCreateDate(null);
        save(record);
    }

    @Override
    public Result refund(String orderNumber) {
        OpenAccountRecord record = baseMapper.getByOrderNumberAndType(orderNumber,OpenAccountRecord.REFUND_PAY);
        if(record != null){
            return ResultGenerator.genFailResult("存在一笔已经标记退款的数据，请勿重复操作！");
        }
        removeOpenAccount(orderNumber);
        return ResultGenerator.genSuccessResult("处理成功！",null);
    }

    /**
     * 数据统计
     * @param condition
     * @return
     */
    @Override
    public Result countData(OpenAccountRecord condition) {
        Map<String, BigDecimal> result = baseMapper.countData(condition);
        return ResultGenerator.genSuccessResult("获取成功",result);
    }
}
