package com.bohuikeji.delivery.backstage.listener.settlement;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bohuikeji.delivery.backstage.entity.TCompanyFran;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.service.ITCompanyFranService;
import com.bohuikeji.delivery.backstage.service.ITOrderService;
import com.bohuikeji.frame.module.admin.base.MqListener;
import com.bohuikeji.frame.module.admin.entity.vo.AliReturnPayVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

/**
 * 加盟商结算
 * @author 孙劲辉
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class FranSettleListener extends MqListener<Integer> {

    final ITCompanyFranService franService;
    final ITOrderService orderService;

    @Override
    public boolean onReceive(Integer id) {
        TCompanyFran companyFran=franService.getById(id);
        if (companyFran==null){
            log.error("【加盟商结算核算失败】记录可能已撤销，ID={}",id);
            return true;
        }
        Page<TOrder> page=new Page<>(1,1000);
        QueryWrapper<TOrder> queryWrapper=new QueryWrapper<TOrder>()
                .select("order_id","order_fran_money")
                .eq("fran_id",companyFran.getFranName())
                .eq("is_third",0)
                .eq("fran_sett_status","未结算")
                .eq("order_status","已完成")
                .ge("order_end_time","2022-04-01 00:00:00");
        IPage<Map<String,Object>> res;
        //订单数量
        int count=0;
        //收益总额
        BigDecimal price=new BigDecimal("0");
        //订单号集合
        List<String> ids=new ArrayList<>(100);
        while (true){
            res=orderService.pageMaps(page,queryWrapper);
            List<Map<String,Object>> records=res.getRecords();
            if (records==null||records.size()<1){
                log.error("订单为空！");
                break;
            }
            count+=records.size();
            for (int i = 0; i < records.size(); i++) {
                price=price.add(new BigDecimal(String.valueOf(records.get(i).get("order_fran_money"))));
                ids.add(String.valueOf(records.get(i).get("order_id")));
            }
            System.out.println("订单量："+count);
            page.setCurrent(page.getCurrent()+1);
        }
        companyFran.setSettOrderDetail(ids.toArray(new String[0]));
        companyFran.setSettOrderNum(count);
        companyFran.setOrderPayAmount(price);
        companyFran.setSettStatus("审核中");
        franService.updateById(companyFran);
        return true;
    }

    @Override
    public void onError(Integer msg, Exception e) {
        log.error("消息队列出现错误：{}",msg);
    }
}
