package thyyxxk.webserver.service.medicalinsurance;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.dao.his.medicalinsurance.UpIdCollectionDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.querydata.AutoUploadBill;
import thyyxxk.webserver.entity.querydata.SiSetlinfoTemp;
import thyyxxk.webserver.utils.ListUtil;
import thyyxxk.webserver.utils.StringUtil;

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

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

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

    public void uploadStatement() {
        String autoUpload = dao.getDictValueByDictName("1.2", "auto_upload");
        int offset = StringUtil.isBlank(autoUpload) ? -1 : -Integer.parseInt(autoUpload);
        String firstDate = DateUtil.formatDate(DateUtil.offsetMonth(new Date(), offset));
        //审核通过的数据
        log.info("结算单上传定时任务开启");
        List<SiSetlinfoTemp> qualityPassData = dao.getQualityPass(firstDate);
        log.info("本次自动上传审核通过的数据有{}条", qualityPassData.size());
        uploadSetLData(qualityPassData);
        //上传大于6天的数据
        List<SiSetlinfoTemp> list = dao.getBillingPatientsToday(firstDate);
        log.info("本次自动上传大于6天的数据数据有{}条", list.size());
        uploadSetLData(list);
        List<SiSetlinfoTemp> unQualityUpload = dao.selectUnQualityUpload();
        log.info("本次自动上传15天内未审核已上传成功的数据数据有{}条", unQualityUpload.size());
        uploadSetLData(unQualityUpload);
        log.info("上传结束");
    }

    public void uploadSetLData(List<SiSetlinfoTemp> list) {
        String uploadDate = DateUtil.formatDate(new Date());
        if (ListUtil.isBlank(list)) return;
        for (SiSetlinfoTemp item : list) {
            try {
                log.info("正在上传 ==> 住院号:{},住院次数:{},账页号:{}", item.getPatNo(), item.getTimes(), item.getLedgerSn());
                ResultVo<String> resultVo = service.upldSetlList(item.getPatNo(), item.getTimes(), item.getLedgerSn(), false);
                Integer flag = resultVo.getCode() == 200 ? AutoUploadBill.FLAG.UPLOAD_SUCCESS.getCode() : AutoUploadBill.FLAG.UPLOAD_FAIL.getCode();
                dao.insertAutoLongPassError(item.getPatNo(), item.getTimes(), item.getLedgerSn(), resultVo.getMessage() == null ? "" : resultVo.getMessage(), AutoUploadBill.TypeFlag.AUTO_UPLOAD.getCode(), flag, uploadDate, item.getSetlTime());
            } catch (Exception e) {
                dao.insertAutoLongPassError(item.getPatNo(), item.getTimes(), item.getLedgerSn(), e.getMessage() == null ? "" : e.getMessage(), AutoUploadBill.TypeFlag.AUTO_UPLOAD.getCode(), AutoUploadBill.FLAG.UPLOAD_FAIL.getCode(), uploadDate, item.getSetlTime());
                log.info("上传错误", e);
            }
        }
    }
}
