package cn.iocoder.yudao.module.member.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.member.controller.admin.diningplates.vo.DiningPlatesStoreVO;
import cn.iocoder.yudao.module.member.dal.dataobject.customertraffic.CustomerTrafficDO;
import cn.iocoder.yudao.module.member.service.customertraffic.CustomerTrafficService;
import cn.iocoder.yudao.module.member.service.diningplates.DiningPlatesService;
import cn.iocoder.yudao.module.member.util.MemberConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zt
 * @description <description class purpose>
 * @since 2024/4/15
 */
@Slf4j
@Component
public class CustomerTrafficJob implements JobHandler {

    @Resource
    private DiningPlatesService platesService;
    @Resource
    private CustomerTrafficService trafficService;
    /**
     * 10分钟为1轮
     */
    private static final Integer ROUND_TIME = 10;

    @Override
    @TenantIgnore
    public String execute(String param) {
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(MemberConstants.HOUR_FORMAT);
        LocalDateTime localDateTime = LocalDateTime.now().withSecond(0);
        List<DiningPlatesStoreVO> diningPlatesNum = platesService.getDiningPlatesNum(localDateTime, ROUND_TIME);
        if(CollectionUtil.isNotEmpty(diningPlatesNum)){
            List<CustomerTrafficDO> addList = new ArrayList<>();
            diningPlatesNum.forEach(a -> {
                if(a.getStoreId()!=null){
                    CustomerTrafficDO customerTrafficDO = new CustomerTrafficDO();
                    customerTrafficDO.setCustomerNum(a.getNum())
                            .setTimePoint(localDateTime.format(dateFormatter))
                            .setStoreId(a.getStoreId()).setStoreName(a.getStoreName())
                            .setCreateTime(localDateTime.withNano(0));
                    addList.add(customerTrafficDO);
                }
            });
            trafficService.insertBatch(addList);
        }

        log.info("[execute][顾客统计任务顾客数量 ({}) 个]", diningPlatesNum);
        return String.format("顾客统计定时任务顾客数量 %s 个", diningPlatesNum);
    }

}
