package com.xhpc.system.task;

import cn.hutool.core.date.DateUtil;
import com.xhpc.common.api.SmsService;
import com.xhpc.common.core.utils.StringUtils;
import com.xhpc.system.domain.XhpcTenantDomain;
import com.xhpc.system.mapper.XhpcTenantMapper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component
public class XhpcTenantTask {

    @Resource
    XhpcTenantMapper tenantMapper;

    @Resource
    SmsService smsService;

    /**
     * 每天一点自动清理过期租户
     */
    @Scheduled(cron = "0 0 1 * * ? ")
    private void ExpiredTenantStatusTask(){

        List<XhpcTenantDomain> expireDomainList = tenantMapper.selectExpiredList();
        for(XhpcTenantDomain domain: expireDomainList){
            domain.setStatus(2);
            tenantMapper.updateStatusByPrimaryKey(domain);
        }
    }


    /**
     * 提前15、7、3、1天通知即将到期的租户
     */
    @Scheduled(cron = "0 0 14 * * ? ")
    private void ExpiringTenantSmsTask(){
        extracted(15);
        extracted(7);
        extracted(3);
        extracted(1);
    }

    private void extracted(int time) {
        String expireTime = DateUtil.formatDate(com.xhpc.common.util.DateUtil.addDay(new Date(), time));
        List<XhpcTenantDomain> expireDomainList = tenantMapper.selectExpiringList(expireTime);
        for(XhpcTenantDomain domain: expireDomainList){
            if (StringUtils.isEmpty(domain.getContactNumber())){
                continue;
            }
            HashMap<String, String> paramMap = new HashMap<>();
            paramMap.put("phone", domain.getContactNumber());
            paramMap.put("tenantName", domain.getTenantName());
            paramMap.put("content", "【翔桦充电】尊敬的租户，您申请的租户(租户名称: " + domain.getTenantName() + ")还有15天到期，请联系业务人员进行续费。");
            smsService.sendNotice(paramMap);
        }
    }

}
