package cn.pluss.platform.service.agent.impl;

import cn.pluss.platform.MerchantRateRecordService;
import cn.pluss.platform.entity.MerchantRate;
import cn.pluss.platform.entity.MerchantRateRecord;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.MerchantRateMapper;
import cn.pluss.platform.service.agent.MerchantRateApiService;
import cn.pluss.platform.userApp.UserAppService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;

/**
 * @author DJH
 */
@Service
public class MerchantRateServiceApiImpl extends ServiceImpl<MerchantRateMapper, MerchantRate> implements MerchantRateApiService {

    @Setter(onMethod_ = {@Autowired})
    private UserAppService userAppService;
    @Setter(onMethod_ = {@Autowired})
    private MerchantRateRecordService merchantRateRecordService;

    @Override
    public MerchantRate getOne(Wrapper<MerchantRate> queryWrapper) {
        UserApp tokenUserApp = userAppService.queryUserAppByToken();

        String userId = queryWrapper.getEntity().getUserId();
        UserApp queryUserApp = new UserApp().setUserId(Long.parseLong(userId));
        queryUserApp = userAppService.queryUserApp(queryUserApp);

        // 身份校验
        // 查询用户是否为自身
        boolean isSelf = queryUserApp.getUserId().equals(tokenUserApp.getUserId());
        // 查询用户是否为下级代理
        boolean isRelation = tokenUserApp.getUserId().equals(queryUserApp.getParentId());
        MsgException.check(!isSelf && !isRelation, "拒绝访问");

        MerchantRate one = super.getOne(queryWrapper);
        // 结果校验
        MsgException.checkNull(one, "未查询到费率信息");

        return one;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void setSubAgentRate(MerchantRate merchantRate) {
        UserApp tokenUserApp = userAppService.queryUserAppByToken();

        String userId = merchantRate.getUserId();
        UserApp queryUserApp = new UserApp().setUserId(Long.parseLong(userId));
        queryUserApp = userAppService.getOne(new QueryWrapper<>(queryUserApp));
        // 当前接口这能修改代理商的费率
        if (!"agent".equals(queryUserApp.getUserType())) {
            throw new MsgException("拒绝访问");
        }

        // 查询用户是否为下级代理
        boolean isRelation = tokenUserApp.getUserId().equals(queryUserApp.getParentId());
        MsgException.check(!isRelation, "拒绝访问");

        // 非固定费率
        if (!"1".equals(tokenUserApp.getIsFixedRate())) {
            MsgException.check(merchantRate.getRate() <= MerchantRate.MAX_RATE, "下级代理商费率不得小于" + MerchantRate.MAX_RATE);
        }

        // 费率下限
        MerchantRate tokenUserRate = new MerchantRate().setUserId(tokenUserApp.getUserId() + "");
        tokenUserRate = baseMapper.selectOne(new QueryWrapper<>(tokenUserRate));
        MsgException.check(merchantRate.getRate() <= tokenUserRate.getRate(), "下级代理商费率必须高于自身费率");

        MerchantRate mr2 = new MerchantRate().setUserId(queryUserApp.getUserId() + "");
        if (merchantRate.getRate().equals(mr2.getRate())) {
            throw new MsgException("费率没有发生变化");
        }

        mr2 = baseMapper.selectOne(new QueryWrapper<>(mr2));
        if (merchantRate.getRate() > mr2.getRate()) {
            throw new MsgException("禁止上调费率");
        }


        // 修改费率
        MerchantRate exist = new MerchantRate().setUserId(merchantRate.getUserId());
        exist = baseMapper.selectOne(new QueryWrapper<>(exist));

        if (exist == null) {
            exist = new MerchantRate();
            exist.setPreviousRate(merchantRate.getRate());
            exist.setUserId(merchantRate.getUserId());
        } else {
            // 一天只能修改一次
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            if (exist.getUpdateTime().after(calendar.getTime())) {
                throw new MsgException("一天只能设置一次费率");
            }

            exist.setPreviousRate(exist.getRate());
        }

        exist.setUpdateTime(new Date());
        exist.setRate(merchantRate.getRate());
        exist.setPreviousRate(merchantRate.getRate());

        saveOrUpdate(exist);

        // 保存修改费率记录
        MerchantRateRecord merchantRateRecord = new MerchantRateRecord();
        merchantRateRecord.setCreateTime(new Date());
        merchantRateRecord.setRate(merchantRate.getRate());
        merchantRateRecord.setUserId(merchantRate.getUserId());
        merchantRateRecordService.save(merchantRateRecord);
    }
}
