package com.docus.server.archive.service.impl;

import com.docus.core.util.Func;
import com.docus.core.util.ObjectUtil;
import com.docus.infrastructure.redis.service.IdService;
import com.docus.server.archive.constans.SyncConstant;
import com.docus.server.archive.converter.MzsyPatientInfoConverter;
import com.docus.server.archive.entity.PowerUser;
import com.docus.server.archive.entity.TBasic;
import com.docus.server.archive.entity.TBasicZkInfo;
import com.docus.server.archive.mapper.PowerUserMapper;
import com.docus.server.archive.mapper.TBasicMapper;
import com.docus.server.archive.service.PatientInfoSyncService;
import com.docus.server.mzsy.entity.MzsyPatientInfoView;
import com.docus.server.mzsy.mapper.MzsyPatientInfoViewMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service("Mzsy" + SyncConstant.PATIENT_INFO_SYNC_SERVICE_SUFFIX)
@Slf4j
public class MzsyPatientInfoSyncServiceImpl implements PatientInfoSyncService {
    @Resource
    private TBasicMapper tBasicMapper;
    @Resource
    private MzsyPatientInfoViewMapper mzsyPatientInfoViewMapper;
    @Resource
    private IdService idService;
    @Resource
    private PowerUserMapper powerUserMapper;

    @Override
    public void syncByDisDateRange(LocalDate start, LocalDate end) {
        log.error("梅州三院未开发按照出院时间同步患者基础数据！");
    }

    @Override
    public void syncByModifyTimeRange(LocalDateTime start, LocalDateTime end) {
        log.error("梅州三院未开发按照修改时间同步患者基础数据！");
    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public void syncByModifyTimeAndCyrq(String cyrqStart, String startTime) {
        int size = 1000;
        int pageNumber = 1;
        log.info("参数" + cyrqStart + startTime);
        while (true) {
            List<MzsyPatientInfoView> patientInfoViews = mzsyPatientInfoViewMapper.pageByViwe(cyrqStart, startTime, pageNumber, size);
            if (Func.isNotEmpty(patientInfoViews)) {
                List<TBasic> basicList = patientInfoViews.stream()
                        .map(MzsyPatientInfoConverter::convertPatientInfo)
                        .collect(Collectors.toList());
                List<String> collect = basicList.stream().map(TBasic::getAttending).collect(Collectors.toList());
                List<PowerUser> byUserNames = powerUserMapper.findByUserNames(collect);
                if (ObjectUtil.isNotEmpty(byUserNames)) {
                    Map<String, String> map = byUserNames.stream().collect(Collectors.toMap(PowerUser::getUserName, PowerUser::getName));
                    for (TBasic tBasic : basicList) {
                        String attending = tBasic.getAttending();
                        if (ObjectUtil.isNotEmpty(attending)) {
                            tBasic.setAttendingName(map.get(attending));
                        }
                    }
                }
                saveOrUpdate(basicList);
            }
            if (Func.isEmpty(patientInfoViews) || patientInfoViews.size() < size) {
                break;
            }
            pageNumber++;
        }
    }

    /**
     *
     * @param iuBasicList 修改的患者基础信息
     */
    private void saveOrUpdate(List<TBasic> iuBasicList) {
        Date nowDate = new Date();
        List<String> iuJzhList1 = iuBasicList.stream()
                .map(TBasic::getJzh)
                .collect(Collectors.toList());
        List<String> iuJzhList = new ArrayList<>();
        iuJzhList.addAll(iuJzhList1);
        List<TBasic> existsBasicList = tBasicMapper.getByJzh(iuJzhList);
        Map<String, TBasic> existsJzhBasicMap = existsBasicList.stream().collect(Collectors.toMap(TBasic::getJzh, Function.identity()));
        List<TBasic> insertBasicList = new ArrayList<>();
        List<TBasic> updateBasicList = new ArrayList<>();
        List<String> deleteList = new ArrayList<>();
        List<TBasic> leaveMethodList = new ArrayList<>();
        for (TBasic iuBasic : iuBasicList) {
            if (existsJzhBasicMap.containsKey(iuBasic.getJzh())) {
                if (ObjectUtil.isEmpty(iuBasic.getDisDate())) {
                    deleteList.add(iuBasic.getJzh());
                    continue;
                }
                TBasic tBasic = existsJzhBasicMap.get(iuBasic.getJzh());
                tBasic.setName(iuBasic.getName());
                tBasic.setInpatientNo(iuBasic.getInpatientNo());
                tBasic.setAdmissTimes(iuBasic.getAdmissTimes());
                tBasic.setSex(iuBasic.getSex());
                tBasic.setSexName(iuBasic.getSexName());
                tBasic.setNameSpell(iuBasic.getNameSpell());
                tBasic.setJzh(iuBasic.getJzh());
                tBasic.setAdmissDate(iuBasic.getAdmissDate());
                tBasic.setAdmissDept(iuBasic.getAdmissDept());
                tBasic.setAdmissDeptName(iuBasic.getAdmissDeptName());
                tBasic.setBedNo(iuBasic.getBedNo());
                tBasic.setAttending(iuBasic.getAttending());
                tBasic.setAttendingName(iuBasic.getAttendingName());
                tBasic.setAge(iuBasic.getAge());
                tBasic.setAgeMonth(iuBasic.getAgeMonth());
                tBasic.setAgeDay(iuBasic.getAgeDay());
                tBasic.setIdCard(iuBasic.getIdCard());
                tBasic.setTelphone(iuBasic.getTelphone());
                tBasic.setDisDate(iuBasic.getDisDate());
                tBasic.setDisDept(iuBasic.getDisDept());
                tBasic.setDisDeptName(iuBasic.getDisDeptName());
                tBasic.setIsDead(iuBasic.getIsDead());
                tBasic.setTotalCost(iuBasic.getTotalCost());
                tBasic.setFileSource(iuBasic.getFileSource());
                tBasic.setUpdateTime(nowDate);
                updateBasicList.add(tBasic);
                if (ObjectUtil.isNotEmpty(iuBasic.getLeaveMethod())) {
                    tBasic.setLeaveMethod(iuBasic.getLeaveMethod());
                    leaveMethodList.add(tBasic);
                }
                continue;
            }
            iuBasic.setPatientId(String.valueOf(idService.getDateSeq()));
            iuBasic.setCreateTime(nowDate);
            iuBasic.setUpdateTime(nowDate);
            iuBasic.setIsArchive(0);
            iuBasic.setIsOther(0);
            if (ObjectUtil.isNotEmpty(iuBasic.getLeaveMethod())) {
                leaveMethodList.add(iuBasic);
            }
            insertBasicList.add(iuBasic);
        }
        if (Func.isNotEmpty(deleteList)) {
            tBasicMapper.deleteBatch(deleteList);
            syncZkInfo(insertBasicList);
        }
        if (Func.isNotEmpty(insertBasicList)) {
            tBasicMapper.insertBatch(insertBasicList);
            syncZkInfo(insertBasicList);
        }
        if (Func.isNotEmpty(updateBasicList)) {
            tBasicMapper.updateBatch(updateBasicList);
            syncZkInfo(updateBasicList);
        }
        if (Func.isNotEmpty(leaveMethodList)) {
            tBasicMapper.updateExtend(leaveMethodList);
        }
    }

    /**
     * 同步转科信息
     */
    private void syncZkInfo(List<TBasic> tBasicList) {
        try {
            for (TBasic tBasic : tBasicList) {
                List<TBasicZkInfo> tBasicZkInfoList = mzsyPatientInfoViewMapper.listZkInfo(tBasic.getJzh());
                if (Func.isNotEmpty(tBasicZkInfoList)) {
                    tBasicMapper.delZkInfo(tBasic.getPatientId());
                    for (TBasicZkInfo tBasicZkInfo : tBasicZkInfoList) {
                        tBasicZkInfo.setId(idService.getDateSeq());
                        tBasicZkInfo.setPatientId(tBasic.getPatientId());
                        tBasicZkInfo.setCreateTime(new Date());
                    }
                    tBasicMapper.addZkInfo(tBasicZkInfoList);
                }
            }
        } catch (Exception e) {
            log.error("添加转科信息出错了：" + e.getMessage(), e);
        }

    }

}
