package com.thinkgem.jeesite.modules.pay.service;

import com.thinkgem.jeesite.common.baseBean.Request;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.modules.pay.bean.OrderRequest;
import com.thinkgem.jeesite.modules.pay.dao.OrderApiDao;
import com.thinkgem.jeesite.modules.pay.dao.PayApiDao;
import com.thinkgem.jeesite.modules.pay.entity.BalanceEntity;
import com.thinkgem.jeesite.modules.pay.entity.BenefitEntity;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.user.bean.UserRequest;
import com.thinkgem.jeesite.modules.user.dao.UserApiDao;
import com.thinkgem.jeesite.modules.user.entity.UserEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

/**
 * @author niehh
 * @Description:分润相关
 * @date 2018年03月15日 10:30
 */
@Service
@Transactional(readOnly = true)
public class BenefitSevice {
    @Autowired
    private PayApiDao payDao;

    @Autowired
    private OrderApiDao orderApiDao;

    @Autowired
    private UserApiDao userDao;

    /**
     * 余额
     *
     * @param entity
     * @return
     */
    public BalanceEntity getBalance(BenefitEntity entity) {

        // 总收益
        entity.setBenefitType("A");
        BenefitEntity benefitEntityA = payDao.getBenefitSum(entity);

        // 总提现
        entity.setBenefitType("M");
        BenefitEntity benefitEntityM = payDao.getBenefitSum(entity);

        // 余额 = 总收益-总提现
        BalanceEntity balanceEntity = getLastBalance(benefitEntityA, benefitEntityM);

        // 今日收益
        entity.setBenefitType("A");
        Date date = new Date();
        String today = DateUtils.formatDate(date, "yyyy-MM-dd HH:mm:ss");
        String todayYMD = DateUtils.formatDate(date, "yyyy-MM-dd");
        entity.setEndTime(today);
        entity.setStartTime(todayYMD + " 00:00:00");
        BenefitEntity benefitEntityToday = payDao.getBenefitSum(entity);
        if (benefitEntityToday != null && StringUtils.isNotBlank(benefitEntityToday.getAmount())) {
            balanceEntity.setTodayIncome(benefitEntityToday.getAmount());
        } else {
            balanceEntity.setTodayIncome("0.00");
        }

        // 昨日收益
        entity.setEndTime(DateUtils.getYesterday(todayYMD, "yyyy-MM-dd") + " 23:59:59");
        entity.setStartTime(DateUtils.getYesterday(todayYMD, "yyyy-MM-dd") + " 00:00:00");

        BenefitEntity benefitEntityYesterday = payDao.getBenefitSum(entity);
        if (benefitEntityYesterday != null && StringUtils.isNotBlank(benefitEntityYesterday.getAmount())) {
            balanceEntity.setYesterdayIncome(benefitEntityYesterday.getAmount());
        } else {
            balanceEntity.setYesterdayIncome("0.00");
        }


        // 本月收益
        entity.setEndTime(today);
        entity.setStartTime(DateUtils.getFirstByMonth(todayYMD, "yyyy-MM-dd") + " 00:00:00");
        BenefitEntity benefitEntityMonth = payDao.getBenefitSum(entity);
        if (benefitEntityMonth != null && StringUtils.isNotBlank(benefitEntityMonth.getAmount())) {
            balanceEntity.setMonthIncome(benefitEntityMonth.getAmount());

        } else {
            balanceEntity.setMonthIncome("0.00");
        }

        // 本年收益
        entity.setEndTime(today);
        entity.setStartTime(DateUtils.getCurrYearFirst(todayYMD, "yyyy-MM-dd") + " 00:00:00");
        BenefitEntity benefitEntityYear = payDao.getBenefitSum(entity);
        if (benefitEntityYear != null && StringUtils.isNotBlank(benefitEntityYear.getAmount())) {
            balanceEntity.setYearIncome(benefitEntityYear.getAmount());
        } else {
            balanceEntity.setYearIncome("0.00");
        }

        return balanceEntity;
    }


    /**
     * 余额（高级别用户）
     *
     * @param entity
     * @return
     */
    public BalanceEntity getBalanceHighLevel(BenefitEntity entity, UserEntity userEntity) {

        //高级用户是否存在推荐用户，存在继续，不存在，则直接返回
        UserEntity recomUserEntity = checkRecommend(userEntity.getMobile());
        UserEntity upgradeUserInfo = userDao.getUpgradeUserInfo(userEntity.getMobile());
        if (recomUserEntity == null) {
            BalanceEntity balanceEntity = new BalanceEntity();
            balanceEntity.setBalance("0.00");
            balanceEntity.setTodayIncome("0.00");
            balanceEntity.setYesterdayIncome("0.00");
            balanceEntity.setMonthIncome("0.00");
            balanceEntity.setYearIncome("0.00");
            return balanceEntity;
        }

        String levelRate = getRateByLevel(userEntity.getLevel());
        // 总收益
        entity.setBenefitType(levelRate);
        entity.setCreateDate(userEntity.getCreated());
        entity.setCardCode(upgradeUserInfo.getMobile());
        BenefitEntity benefitEntityA = payDao.getBenefitSumHighLevel(entity);

        // 总提现
        BenefitEntity benefitEntityM = payDao.getBenefitSumHighLevelM(entity);

        // 余额 = 总收益-总提现
        BalanceEntity balanceEntity = getLastBalance(benefitEntityA, benefitEntityM);

        // 今日收益
        Date date = new Date();
        String today = DateUtils.formatDate(date, "yyyy-MM-dd HH:mm:ss");
        String todayYMD = DateUtils.formatDate(date, "yyyy-MM-dd");
        entity.setEndTime(today);
        entity.setStartTime(todayYMD + " 00:00:00");
        BenefitEntity benefitEntityToday = payDao.getBenefitSumHighLevel(entity);
        if (benefitEntityToday != null && StringUtils.isNotBlank(benefitEntityToday.getAmount())) {
            balanceEntity.setTodayIncome(benefitEntityToday.getAmount());
        } else {
            balanceEntity.setTodayIncome("0.00");
        }

        // 昨日收益
        entity.setEndTime(DateUtils.getYesterday(todayYMD, "yyyy-MM-dd") + " 23:59:59");
        entity.setStartTime(DateUtils.getYesterday(todayYMD, "yyyy-MM-dd") + " 00:00:00");

        BenefitEntity benefitEntityYesterday = payDao.getBenefitSumHighLevel(entity);
        if (benefitEntityYesterday != null && StringUtils.isNotBlank(benefitEntityYesterday.getAmount())) {
            balanceEntity.setYesterdayIncome(benefitEntityYesterday.getAmount());
        } else {
            balanceEntity.setYesterdayIncome("0.00");
        }


        // 本月收益
        entity.setEndTime(today);
        entity.setStartTime(DateUtils.getFirstByMonth(todayYMD, "yyyy-MM-dd") + " 00:00:00");
        BenefitEntity benefitEntityMonth = payDao.getBenefitSumHighLevel(entity);
        if (benefitEntityMonth != null && StringUtils.isNotBlank(benefitEntityMonth.getAmount())) {
            balanceEntity.setMonthIncome(benefitEntityMonth.getAmount());

        } else {
            balanceEntity.setMonthIncome("0.00");
        }

        // 本年收益
        entity.setEndTime(today);
        entity.setStartTime(DateUtils.getCurrYearFirst(todayYMD, "yyyy-MM-dd") + " 00:00:00");
        BenefitEntity benefitEntityYear = payDao.getBenefitSumHighLevel(entity);
        if (benefitEntityYear != null && StringUtils.isNotBlank(benefitEntityYear.getAmount())) {
            balanceEntity.setYearIncome(benefitEntityYear.getAmount());
        } else {
            balanceEntity.setYearIncome("0.00");
        }

        return balanceEntity;
    }

    /**
     * 分润
     *
     * @param request
     * @return
     */
    public List<BenefitEntity> getBenefitList(OrderRequest request) {
        if (request.getStartDate() != null && request.getStartDate() != 0) {
            request.setStartTime(DateUtils.formatDate(new Date(request.getStartDate()), "yyyy-MM-dd") + " 00:00:00");
        }
        if (request.getEndDate() != null && request.getEndDate() != 0) {
            request.setEndTime(DateUtils.formatDate(new Date(request.getEndDate()), "yyyy-MM-dd") + " 23:59:59");
        }
        List<BenefitEntity> benefitList = null;
        Request re = new Request();
        re.setSubMerchantCode(request.getSubMerchantCode());
        UserEntity userInfo = userDao.getUserInfo(re);
        if (userInfo.getLevel().equals("A") || userInfo.getLevel().equals("B")) {
            //高级用户是否存在推荐用户，存在继续，不存在，则直接返回
            UserEntity recomUserEntity = checkRecommend(userInfo.getMobile());
            if (recomUserEntity == null) {
                return benefitList;
            }
            //升级前用户信息
            UserEntity upgradeUserInfo = userDao.getUpgradeUserInfo(userInfo.getMobile());
            request.setSubMerchantCode(upgradeUserInfo.getMobile());
            request.setSign(getRateByLevel(userInfo.getLevel()));
            benefitList = orderApiDao.getBenefitListHighLevel(request);
        } else {
            benefitList = orderApiDao.getBenefitList(request);
        }

        return benefitList;

    }

    /**
     * 分润 分页
     *
     * @param request
     * @return
     */
    public Page<BenefitEntity> getBenefitPage(OrderRequest request) {
        if (request.getStartDate() != null && request.getStartDate() != 0) {
            request.setStartTime(DateUtils.formatDate(new Date(request.getStartDate()), "yyyy-MM-dd") + " 00:00:00");
        }
        if (request.getEndDate() != null && request.getEndDate() != 0) {
            request.setEndTime(DateUtils.formatDate(new Date(request.getEndDate()), "yyyy-MM-dd") + " 23:59:59");
        }
        Page<BenefitEntity> page = new Page<>();
        page.setPageNo(request.getPageNum());
        page.setPageSize(request.getPageSize());
        request.setPage(page);
        List<BenefitEntity> list = orderApiDao.getBenefitList(request);
        page.setList(list);
        page.setTotalPage(page.getLast());
        return page;

    }


    /**
     * 可以提现的金额
     *
     * @param entity
     * @return
     */
    public BalanceEntity getBalanceM(BenefitEntity entity) {


        // 总共可以提现的金额
        entity.setBenefitType("A");
        entity.setBenefitStatus("1");
        BenefitEntity benefitEntityA = payDao.getBenefitSum(entity);

        // 总提现金额
        entity.setBenefitType("M");
        BenefitEntity benefitEntityM = payDao.getBenefitSum(entity);

        // 可以提现的余额 = 总共可以提现的金额-总提现金额
        BalanceEntity balanceEntity = getLastBalance(benefitEntityA, benefitEntityM);

        return balanceEntity;

    }

    public BalanceEntity getLastBalance(BenefitEntity benefitEntityA, BenefitEntity benefitEntityM) {
        BalanceEntity balanceEntity = new BalanceEntity();
        if (benefitEntityA == null) {
            balanceEntity.setBalance("0.00");
        } else {
            if (benefitEntityA.getAmount() == null) {
                benefitEntityA.setAmount("0.00");
            }
            if (benefitEntityM == null) {
                balanceEntity.setBalance(benefitEntityA.getAmount());
            } else {
                if (benefitEntityM.getAmount() == null) {
                    benefitEntityM.setAmount("0.00");
                }
                DecimalFormat df = new DecimalFormat("######0.00");
                balanceEntity.setBalance(df.format(Double.valueOf(benefitEntityA.getAmount()) - Double.valueOf(benefitEntityM.getAmount())));
            }
        }
        return balanceEntity;
    }

    /**
     * 判断高级用户是否已经推荐过用户
     *
     * @param mobile
     * @return
     */
    public UserEntity checkRecommend(String mobile) {
        UserEntity upgradeUserInfo = userDao.getUpgradeUserInfo(mobile);
        UserRequest userRequest = new UserRequest();
        userRequest.setRecommendedMobile(upgradeUserInfo.getMobile());
        UserEntity recomUserEntity = userDao.checkRecommend(userRequest);
        return recomUserEntity;
    }

    /**
     * 根据高级别用户等级获取分润比例
     *
     * @param level
     * @return
     */
    public String getRateByLevel(String level) {
        List<Dict> list = DictUtils.getDictList("benefit_rate_" + level);
        String rate = "0";
        if (list != null && list.size() > 0) {
            rate = list.get(0).getValue();
        }
        return rate;
    }

}
