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

import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.leshua.ExpandDto;
import cn.pluss.platform.mapper.SpreadMapper;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.merchantGuide.MerchantGuideService;
import cn.pluss.platform.merchantQrcode.MerchantQrcodeService;
import cn.pluss.platform.service.common.SpreadService;
import cn.pluss.platform.systemConfig.SystemConfigService;
import cn.pluss.platform.user.UserProfitService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.vo.SpreadData;
import cn.pluss.platform.vo.UserNumVO;
import cn.pluss.platform.vo.UserTeamAchieVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author DJH
 */
@Service
public class SpreadServiceImpl implements SpreadService {

    @Setter(onMethod_ = @Autowired)
    private UserAppService userAppService;

    @Setter(onMethod_ = @Autowired)
    private SystemConfigService configService;

    @Setter(onMethod_ = @Autowired)
    private MerchantQrcodeService merchantQrcodeService;

    @Setter(onMethod_ = @Autowired)
    private MerchantGuideService merchantGuideService;

    @Resource
    private SpreadMapper spreadMapper;

    @Resource
    private MerchantChannelStatusService merchantChannelStatusService;


    @Autowired
    private UserProfitService userProfitService;

    @Override
    public Page<UserApp> expandPageData(ExpandDto dto) {
        UserApp userApp = userAppService.queryUserAppByToken();
        dto.setUserId(userApp.getUserId() + "");

        MsgException.checkNull(dto.getPage(), "页码不能为空");
        MsgException.checkNull(dto.getSize(), "页长不能为空");

        Page<UserApp> page = new Page<>();
        page.setCurrent(dto.getPage());
        page.setSize(dto.getSize());

        if ("1".equals(dto.getRecommend())) {
            // 查直推
            return spreadMapper.selectDirectUser(dto, page);
        } else if ("promoter".equals(userApp.getUserType())) {
            // 查普通服务商下的商户，只查三级
            return spreadMapper.selectPmtSubUser(dto, page);
        } else {
            // 查超级服务商/代理商下的商户
            return spreadMapper.selectAgentSubUser(dto, page);
        }
    }

    @Override
    public String getUpgradeImage() {
        UserApp userApp = userAppService.queryUserAppByToken();
        if (userApp.getLevel() == 3) {
            return null;
        }

        SystemConfig systemConfig = new SystemConfig();
        systemConfig.setPropertyKey("upgradeImg" + userApp.getLevel());
        systemConfig = configService.querySystemConfig(systemConfig);

        return systemConfig.getPropertyValue();
    }

    @Override
    public Map<String, Object> appPaySuccessPageData() {
        Map<String, Object> result = new HashMap<>();

        UserApp userApp = userAppService.queryUserAppByToken();

        MerchantQrcode merchantQrcode = new MerchantQrcode();
        merchantQrcode.setMerchantCode(userApp.getMerchantCode());
        merchantQrcode = merchantQrcodeService.getOne(new QueryWrapper<>(merchantQrcode));

        if (merchantQrcode == null) {
            merchantQrcode = new MerchantQrcode();
        }

        result.put("wxInfo", merchantQrcode);

        List<MerchantGuide> merchantGuideList = merchantGuideService.appList();

        result.put("dict", merchantGuideList);

        return result;
    }

    @Override
    public SpreadData apiTodaySpreadData() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -1);
        Date time = cal.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

        String lastDay = sdf.format(time);

        MathContext mathContext = new MathContext(2, RoundingMode.DOWN);

        UserApp userApp = userAppService.queryUserAppByToken();
        // 此处只能获取直属商户今日数据
        SpreadData result = todaySpreadData(userApp.getUserId() + "");

        // 获取直属商户以及团队昨日的数据
        QueryWrapper<UserProfit> qWrapper = new QueryWrapper<>();
        qWrapper.eq("userId", userApp.getUserId());
        qWrapper.eq("profitDate", lastDay);
        UserProfit one = userProfitService.getOne(qWrapper);

        if (one == null) {
            result.setTeamActiveCount(0L);
            result.setTeamBillCount(0L);
            result.setTeamAmt(BigDecimal.ZERO);

            result.setOwnAmtPreCompare(BigDecimal.valueOf(1));
            result.setOwnBillCountPreCompare(BigDecimal.valueOf(1));
            result.setOwnActiveCountPreCompare(BigDecimal.valueOf(1));

            result.setTeamAmtPreCompare(BigDecimal.valueOf(1));
            result.setTeamBillCountPreCompare(BigDecimal.valueOf(1));
            result.setTeamActiveCountPreCompare(BigDecimal.valueOf(1));

            return result;
        } else {
            result.setTeamBillCount(one.getTransNum().longValue());
            result.setTeamAmt(one.getTeamTransFlow().add(one.getOwnTransFlow()));
        }

        if (one.getDirectTransFlow().stripTrailingZeros().equals(BigDecimal.ZERO)) {
            result.setOwnAmtPreCompare(BigDecimal.valueOf(1));
        } else {
            result.setOwnAmtPreCompare(result.getOwnAmt().divide(one.getDirectTransFlow(), RoundingMode.HALF_EVEN).round(mathContext));
        }

        // 直推的交易笔数占比暂无法计算
        // if (one.getTransNum() == 0) {
        //     result.setOwnBillCountPreCompare(BigDecimal.valueOf(1));
        // } else {
        //     result.setOwnBillCountPreCompare(BigDecimal.valueOf(1));
        // }

        UserNumVO userNumVO = new UserNumVO();
        userNumVO.setUserId(userApp.getUserId());
        userNumVO.setDateType(UserNumVO.DATE_TYPE_DAY);
        userNumVO.setDate(lastDay);
        userNumVO = getUserDirectNumInfo(userNumVO, UserNumVO.DATA_TYPE_MERCHANT);

        result.setTeamActiveCount(userNumVO.getTotalNum().longValue());
        if (userNumVO.getTotalNum() == 0) {
            result.setOwnActiveCountPreCompare(BigDecimal.valueOf(1));
        } else {
            result.setOwnActiveCountPreCompare(BigDecimal.valueOf(result.getOwnBillCount()).divide(BigDecimal.valueOf(userNumVO.getTotalNum()), RoundingMode.HALF_EVEN).round(mathContext));
        }

        // result.setOwnActiveCountPreCompare();

        // 获取团队前天数据
        cal.add(Calendar.DAY_OF_MONTH, -1);
        time = cal.getTime();
        String beforeYesterdayStr  = sdf.format(time);

        qWrapper = new QueryWrapper<>();
        qWrapper.eq("userId", userApp.getUserId());
        qWrapper.eq("profitDate", beforeYesterdayStr);
        UserProfit beforeYesterdayUserProfit = userProfitService.getOne(qWrapper);

        if (beforeYesterdayUserProfit == null) {
            result.setTeamAmtPreCompare(BigDecimal.valueOf(1));
            result.setTeamBillCountPreCompare(BigDecimal.valueOf(1));
            result.setTeamActiveCountPreCompare(BigDecimal.valueOf(1));

            return result;
        }

        if (beforeYesterdayUserProfit.getTeamTransFlow().stripTrailingZeros().equals(BigDecimal.ZERO)) {
            result.setTeamAmtPreCompare(BigDecimal.valueOf(1));
        } else {
            result.setTeamAmtPreCompare(one.getTeamTransFlow().divide(beforeYesterdayUserProfit.getTeamTransFlow(), RoundingMode.DOWN).round(mathContext));
        }

        if (beforeYesterdayUserProfit.getTransNum() == 0) {
            result.setTeamBillCountPreCompare(BigDecimal.valueOf(1));
        } else {
            result.setTeamBillCountPreCompare(BigDecimal.valueOf(result.getTeamBillCount()).divide(BigDecimal.valueOf(beforeYesterdayUserProfit.getTransNum()), RoundingMode.DOWN).round(mathContext));
        }

        userNumVO = new UserNumVO();
        userNumVO.setUserId(userApp.getUserId());
        userNumVO.setDateType(UserNumVO.DATE_TYPE_DAY);
        userNumVO.setDate(beforeYesterdayStr);
        userNumVO = getUserDirectNumInfo(userNumVO, UserNumVO.DATA_TYPE_MERCHANT);

        if (userNumVO.getTotalNum() == 0) {
            result.setTeamActiveCountPreCompare(BigDecimal.valueOf(1));
        } else {
            result.setTeamActiveCountPreCompare(BigDecimal.valueOf(result.getTeamActiveCount()).divide(BigDecimal.valueOf(userNumVO.getTotalNum()), RoundingMode.DOWN).round(mathContext));
        }

        return result;
    }

    @Override
    public SpreadData todaySpreadData(String userId) {
        return spreadMapper.selectTodaySpreadData(userId);
    }

    @Override
    public Page<SpreadData> apiHistorySpreadPageData(Page<SpreadData> page, String type, String target) {
        UserApp userApp = userAppService.queryUserAppByToken();
        return historySpreadPageData(userApp.getUserId() + "", page, type, target);
    }

    @Override
    public Page<SpreadData> historySpreadPageData(String userId, Page<SpreadData> page, String type, String target) {
        if (Objects.equals(type, "1")) {
            if (Objects.equals(target, "1")) {
                page = spreadMapper.pageDaySpreadPageData(page, userId);
            } else {
                page = spreadMapper.pageTeamDaySpreadPageData(page, userId);
            }
        }

        if (Objects.equals(type, "2")) {
            if (Objects.equals(target, "1")) {
                page = spreadMapper.pageMonthSpreadPageData(page, userId);
            } else {
                page = spreadMapper.pageTeamMonthSpreadPageData(page, userId);
            }
        }

        if (Objects.equals(type, "3")) {
            if (Objects.equals(target, "1")) {
                page = spreadMapper.pageYearSpreadPageData(page, userId);
            } else {
                page = spreadMapper.pageTeamYearSpreadPageData(page, userId);
            }
        }

        return page;
    }

    /**
     * 查询团队交易数据
     * @date: 2022/1/24 14:25
     * @param condition:
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<cn.pluss.platform.vo.UserTeamAchieVO>
     */
    @Override
    public Page<UserTeamAchieVO> userTeamAchiePage(Page<UserTeamAchieVO> page, UserTeamAchieVO condition) {
        UserApp userApp = userAppService.queryUserAppByToken();
        MsgException.checkNull(userApp,"请求异常");
        MsgException.checkNull(condition.getUserId(),"缺失用户ID");
        condition.setDateType(condition.getDateType() == null ? UserTeamAchieVO.DATE_TYPE_DAY : condition.getDateType());
        condition.setDataType(condition.getDataType() == null ? UserTeamAchieVO.DATA_TYPE_DIRET : condition.getDataType());
        Page<UserTeamAchieVO> result = spreadMapper.userTemaAchiePage(page, condition);
        List<UserTeamAchieVO> records = result.getRecords();
        if(!records.isEmpty()){
            for (UserTeamAchieVO vo:records) {
                UserNumVO data = merchantChannelStatusService.getUserNumInfo(vo.getUserId(),vo.getDate(),condition.getDateType());
                if(data != null){
                    vo.setTotalNum(data.getTotalNum());
                    vo.setAddNum(data.getAddNum());
                }else{
                    vo.setTotalNum(0);
                    vo.setAddNum(0);
                }
            }
        }
        return result;
    }

    @Override
    public UserNumVO getUserDirectNumInfo(UserNumVO vo,int type) {
        MsgException.checkNull(vo.getUserId(),"缺失用户ID");
        if(type == UserNumVO.DATA_TYPE_MERCHANT){
            return merchantChannelStatusService.getUserNumInfo(vo.getUserId(), vo.getDate(), vo.getDateType());
        }else{
            return userAppService.getUserNumInfo(vo.getUserId(), vo.getDate(), vo.getDateType());
        }
    }


    /**
     * 获取团队交易流水
     * @date: 2022/1/25 23:53
     * @param vo:
     * @return cn.pluss.platform.vo.UserTeamAchieVO
     */
    @Override
    public UserTeamAchieVO getAppUserTeanFlow(UserTeamAchieVO vo) {
        UserApp userApp = userAppService.queryUserAppByToken();
        MsgException.checkNull(userApp,"未知请求");
        MsgException.checkNull(vo.getUserId(),"缺失用户ID");
        MsgException.checkNull(vo.getDate(),"缺失日期参数！");
        vo.setDateType(vo.getDateType() == null ? UserTeamAchieVO.DATE_TYPE_DAY : vo.getDateType());
        vo.setDataType(vo.getDataType() == null ? UserTeamAchieVO.DATA_TYPE_DIRET : vo.getDataType());
        UserTeamAchieVO result = spreadMapper.getAppUserTeanFlow(vo);
        if(result == null){
            result = new UserTeamAchieVO();
            result.setTradeAmt(BigDecimal.ZERO);
            result.setTradeNum(0);
        }
        return result;
    }
}
