package thyyxxk.webserver.scheduled;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import thyyxxk.webserver.dao.his.medicalinsurance.TransHospRcdDao;
import thyyxxk.webserver.dao.his.medicalinsurance.UpIdCollectionDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.querydata.SiSetlinfoTemp;
import thyyxxk.webserver.service.medicalinsurance.SetlListUpldService;
import thyyxxk.webserver.utils.DateUtil;
import thyyxxk.webserver.utils.ListUtil;

import java.util.Date;
import java.util.List;

/**
 * @author 肖蟾
 */
@Component
@Slf4j
public class UploadBillingList {
    private final SetlListUpldService service;
    private final UpIdCollectionDao dao;

    @Value("${execute-scheduled}")
    private Boolean executeScheduled;

    public UploadBillingList(SetlListUpldService service, UpIdCollectionDao dao) {
        this.service = service;
        this.dao = dao;
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public void uploadStatement() {
        if (!executeScheduled) {
            return;
        }
        List<SiSetlinfoTemp> list = dao.getBillingPatientsToday();
        log.info("结算单上传定时任务开启");
        String uploadDate = DateUtil.formatDatetime(DateUtil.timeAddOrMinusDays(new Date(), -1), DateUtil.DATE);
        if (ListUtil.notBlank(list)) {
            for (SiSetlinfoTemp item : list) {
                try {
                    log.info("正在上传 ==> 住院号:{},住院次数:{},账页号:{}", item.getPatNo(), item.getTimes(), item.getLedgerSn());
                    ResultVo<String> resultVo = service.upldSetlList(item.getPatNo(), item.getTimes(), item.getLedgerSn());
                    dao.insertAutoLongPassError(item.getPatNo(), item.getTimes(), item.getLedgerSn(), resultVo.getMessage(), uploadDate);
                } catch (Exception e) {
                    dao.insertAutoLongPassError(item.getPatNo(), item.getTimes(), item.getLedgerSn(), e.getMessage(), uploadDate);
                    log.info("上传错误", e);
                }
            }
        }
        log.info("上传结束");
    }
}
