package cn.pluss.platform.app.impl;

import cn.pluss.platform.api.PageInfo;
import cn.pluss.platform.app.AccountBalanceService;
import cn.pluss.platform.channel.MakeMoneyService;
import cn.pluss.platform.entity.MakeMoney;
import cn.pluss.platform.entity.MerchantChannelStatus;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.MerchantOrderMapper;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.PageUtils;
import cn.pluss.platform.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class AccountBalanceServiceImpl implements AccountBalanceService {

    private final MerchantOrderMapper merchantOrderMapper;
    private final MakeMoneyService sxfMakeMoneyService;

    private final UserAppService userAppService;
    private final MerchantChannelStatusService merchantChannelStatusService;

    @Override
    public PageInfo<MakeMoney> queryBills(Page<MakeMoney> pageInfo) {
        UserApp userApp = userAppService.queryUserAppByToken();
        if (StringUtils.isEmpty(userApp.getMerchantCode())) {
            throw new MsgException("请先进行商户认证");
        }

        QueryWrapper<MerchantChannelStatus> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userApp.getMerchantCode());
        MerchantChannelStatus merchantChannelStatus = merchantChannelStatusService.getOne(queryWrapper);
        if (!(merchantChannelStatus.getStatus().equals("3") || merchantChannelStatus.getStatus().equals("4"))) {
            throw new MsgException("请先进行商户认证");
        }

        QueryWrapper<MakeMoney> qw2 = new QueryWrapper<>();
        qw2.eq("merchantId", merchantChannelStatus.getMerchantId());
        qw2.orderByDesc("createTime");
        Page<MakeMoney> page = sxfMakeMoneyService.page(pageInfo, qw2);
        for (MakeMoney l : page.getRecords()) {
            l.setRealAmount(StringUtil.bigDecimal(l.getRealAmount() * 0.01));
            l.setSuspendAmount(StringUtil.bigDecimal(l.getSuspendAmount() * 0.01));
            l.setPlanAmount(StringUtil.bigDecimal(l.getPlanAmount() * 0.01));
        }

        if (page.getRecords().size() == 0) {
            return PageUtils.page(page);
        }
        String start = page.getRecords().get(page.getRecords().size() - 1).getCreateTime();
        String end = page.getRecords().get(0).getCreateTime();

        try {
            FastDateFormat dateFormat = FastDateFormat.getInstance("yyyy-MM-dd", Locale.CHINA);
            Date startTime = dateFormat.parse(start);
            startTime = DateUtils.addDays(startTime, -1);
            Date endTime = dateFormat.parse(end);
            setDailyCount(startTime, endTime, userApp.getMerchantCode(), page.getRecords());
        } catch (Exception e) {
            return PageUtils.page(page);
        }
        return PageUtils.page(page);
    }

    /**
     * 查询每日的总流水，并放入结果集中
     *
     * @param start        开始时间
     * @param end          截止时间
     * @param merchantCode 店铺code
     * @param targetList   结算信息
     */
    private void setDailyCount(Date start, Date end, String merchantCode, List<MakeMoney> targetList) {
        List<Map<String, Object>> dailyCountList = merchantOrderMapper.queryDailyCount(merchantCode, start, end);

        for (MakeMoney makeMoney : targetList) {
            for (Map<String, Object> dailyCount : dailyCountList) {
                java.lang.String billDate = makeMoney.getCreateTime().substring(0, 10);
                String dailyDate;
                if (dailyCount.get("date") instanceof byte[]) {
                    dailyDate = new String((byte[]) dailyCount.get("date"));
                } else {
                    dailyDate = dailyCount.get("date").toString();
                }

                if (billDate.equals(dailyDate)) {
                    makeMoney.setConsumeFeeSum(BigDecimal.valueOf((double) dailyCount.get("consumeFeeSum")));
                    dailyCountList.remove(dailyCount);
                    break;
                }
            }
        }
    }
}
