package vip.xiaonuo.biz.modular.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import vip.xiaonuo.biz.modular.bizappointmentrecord.entity.BizAppointmentRecord;
import vip.xiaonuo.biz.modular.bizappointmentrecord.mapper.BizAppointmentRecordMapper;
import vip.xiaonuo.biz.modular.bizappointmentrecord.service.BizAppointmentRecordService;
import vip.xiaonuo.biz.modular.bizappointmenttime.entity.BizAppointmentTime;
import vip.xiaonuo.biz.modular.bizappointmenttime.service.BizAppointmentTimeService;
import vip.xiaonuo.biz.modular.bizconfig.entity.BizConfig;
import vip.xiaonuo.biz.modular.bizconfig.service.BizConfigService;
import vip.xiaonuo.common.timer.CommonTimerTaskRunner;

import java.util.List;

@Slf4j
@Component
public class AppointmentCallTask implements CommonTimerTaskRunner {

    @Resource
    private BizAppointmentTimeService bizAppointmentTimeService;
    @Resource
    private BizAppointmentRecordService bizAppointmentRecordService;
    @Resource
    private BizAppointmentRecordMapper bizAppointmentRecordMapper;
    @Resource
    private BizConfigService bizConfigService;

    @Override
    public void action(String extJson) {
        String format = DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss");
        //根据时间段查询排队中的预约记录
        QueryWrapper<BizAppointmentRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("bgc.CONF_START_TIME",format)
                .gt("bgc.CONF_END_TIME",format)
                .eq("bar.STATUS","3")
                .eq("bar.delete_flag","NOT_DELETE")
                .orderByAsc("bar.create_time")
                .last("limit 1");
        List<BizAppointmentRecord> list = bizAppointmentRecordMapper.getRecord(queryWrapper);
        BizConfig bizConfig = bizConfigService.getOne(new QueryWrapper<BizConfig>().lambda().last("limit 1"));
        if(ObjectUtil.isNotEmpty(list)){
            for(BizAppointmentRecord record : list){
                if(StringUtils.equals(bizConfig.getAccessControlSwitch(),"1")){
                    //开启门禁校验
                    record.setStatus("4");
                }else{
                    record.setStatus("5");
                }
                bizAppointmentRecordService.updateById(record);
                log.info("车牌号："+record.getLicenseNumber()+"在("+record.getBeginTime()+"~"+record.getEndTime()+")时间段内叫号成功！");

                if(StringUtils.equals(bizConfig.getLineNoticeSwitch(),"1")){
                    bizAppointmentRecordService.sendAccount(record);
                }

            }
        }

    }
}
