package thyyxxk.webserver.service.medicalinsurance;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.constants.sidicts.MedType;
import thyyxxk.webserver.dao.his.medicalinsurance.AutoUploadBillDao;
import thyyxxk.webserver.entity.querydata.AutoUploadBill;
import thyyxxk.webserver.service.hutoolcache.RegionCache;
import thyyxxk.webserver.utils.ListUtil;
import thyyxxk.webserver.utils.StringUtil;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author:lihong
 * @Date: 2023/1/4
 */
@Service
public class AutoUploadBillService extends ServiceImpl<AutoUploadBillDao,AutoUploadBill> {

    @Resource
    private RegionCache regionCache;

    @Async
    public void asyncSaveData(List<AutoUploadBill> list){
        if(CollUtil.isNotEmpty(list)){
            List<List<AutoUploadBill>> limitList = CollUtil.split(list, 50);
            for(List<AutoUploadBill> temp :limitList){
                baseMapper.batchSaveData(temp);
            }
        }
    }
    @Async
    public void asynDeleteAndbatchSaveData(List<AutoUploadBill> list){
        if(CollUtil.isEmpty(list)) return;
        List<String> visitIds = list.stream().map(obj -> obj.getPatNo() + obj.getTimes() + obj.getLedgerSn()).collect(Collectors.toList());
        baseMapper.deleteVisitId(visitIds);
        baseMapper.batchSaveData(list);
    }
    /**
     * @description:查询病人的最新的上传时间
     * @author: lihong
     * @date: 2023/1/6 16:56
     * @param: patNo
     * @param: times
     * @param: ledgerSn
     * @return: java.util.Date
     **/
   public Date getLastUpdateTime(String patNo, Integer times, Integer ledgerSn){
    return baseMapper.getLastUpdateTime(patNo,times,ledgerSn);
   }

    public IPage<AutoUploadBill> queryPage(AutoUploadBill autoUploadBill){
        IPage<AutoUploadBill> page = new Page(autoUploadBill.getCurrentPage(),autoUploadBill.getPageSize());
        QueryWrapper<AutoUploadBill> query = getAutoUploadBillQueryWrapper(autoUploadBill);
        String condition = "";
        if("1".equals(autoUploadBill.getDistinctFlag())){
            condition =" join  (select pat_no,times,ledger_sn ,max(created_date) created_date from t_auto_upload_bill group by pat_no,times,ledger_sn)t3 on t1.pat_no=t3.pat_no and t1.times=t3.times and t1.ledger_sn=t3.ledger_sn and t1.created_date=t3.created_date ";
        }
        List<AutoUploadBill> records = baseMapper.listPage(query, autoUploadBill.getCurrentPage(), autoUploadBill.getPageSize(),condition);
        for(AutoUploadBill item : records){
            item.setInsuplcAdmdvsName(regionCache.get(item.getInsuplcAdmdvs()));
            if(item.getClrOptinsName() == null){
                if("439900".equals(item.getClrOptins())){
                    item.setClrOptinsName("省本级");
                }else if("430199".equals(item.getClrOptins())){
                    item.setClrOptinsName("市本级");
                }
            }
            MedType medType = MedType.get(item.getMedType());
            if (null != medType) {
                item.setMedTypeName(medType.getName());
            }
        }
        page.setRecords(records);
        Integer total = baseMapper.pageTotal(query,condition);
        page.setTotal(total);
        if(ListUtil.notBlank(page.getRecords()) ){
            for(AutoUploadBill item:page.getRecords()){
                item.setFlagName("上传成功".equals(item.getLogText())?AutoUploadBill.FLAG.UPLOAD_SUCCESS.getName():AutoUploadBill.FLAG.UPLOAD_FAIL.getName());
                item.setTypeFlagName(item.getTypeFlag()==null || AutoUploadBill.TypeFlag.AUTO_UPLOAD.getCode()==item.getTypeFlag()?AutoUploadBill.TypeFlag.AUTO_UPLOAD.getName():AutoUploadBill.TypeFlag.SD_UPLOAD.getName());
            }
        }
        return page;
    }

    public QueryWrapper<AutoUploadBill> getAutoUploadBillQueryWrapper(AutoUploadBill autoUploadBill) {
        QueryWrapper<AutoUploadBill> query = new QueryWrapper<>();
        query.eq(StringUtil.notBlank(autoUploadBill.getPatNo()), "t1.pat_no", autoUploadBill.getPatNo());
        //0 查询全部
        query.eq(autoUploadBill.getTypeFlag() !=0, "t1.type_flag", autoUploadBill.getTypeFlag());
        query.eq(autoUploadBill.getTimes() !=null, "t1.times", autoUploadBill.getTimes());
        query.eq(autoUploadBill.getLedgerSn() !=null, "t1.ledger_sn", autoUploadBill.getLedgerSn());
        query.eq(autoUploadBill.getFlag() != 0, "t1.flag", autoUploadBill.getFlag());
        query.ne("0".equals(autoUploadBill.getZhuYuanFlag()),"t1.ledger_sn","0");
        query.eq("1".equals(autoUploadBill.getZhuYuanFlag()),"t1.ledger_sn","0");
        query.ge(StringUtil.notBlank(autoUploadBill.getUpdateStartTime()), "t1.created_date", autoUploadBill.getUpdateStartTime());
        query.le(StringUtil.notBlank(autoUploadBill.getUpdateEndTime()), "t1.created_date", autoUploadBill.getUpdateEndTime());
        query.ge(StringUtil.notBlank(autoUploadBill.getSetlStartTime()), "t1.setl_time", autoUploadBill.getSetlStartTime());
        query.le(StringUtil.notBlank(autoUploadBill.getSetlEndTime()), "t1.setl_time", autoUploadBill.getSetlEndTime());
        query.in(CollUtil.isNotEmpty(autoUploadBill.getOutDeptList()), "isnull(t2.zk_ward, t2.small_dept)", autoUploadBill.getOutDeptList());
        return query;
    }

}
