package com.yihu.wlyy.statistics.task;

import com.yihu.wlyy.statistics.Application;
import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.model.doctor.DoctorPatientGroupInfo;
import com.yihu.wlyy.statistics.model.label.SignPatientLabel;
import com.yihu.wlyy.statistics.model.label.SignPatientLabelInfo;
import com.yihu.wlyy.statistics.model.patient.Patient;
import com.yihu.wlyy.statistics.util.SpringUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lyr-pc on 2016/10/12.
 */
public class PatientGroupToLabelRunnable implements Runnable {

    long start = 0;
    long end = 0;

    DoctorPatientGroupInfoDao groupInfoDao;
    SignPatientLabelInfoDao labelInfoDao;
    JpaTransactionManager transactionManager;

    public PatientGroupToLabelRunnable(Long start, Long end) {
        this.start = start;
        this.end = end;
        this.groupInfoDao = SpringUtil.getApplicationContext().getBean(DoctorPatientGroupInfoDao.class);
        this.labelInfoDao = SpringUtil.getApplicationContext().getBean(SignPatientLabelInfoDao.class);
        this.transactionManager = SpringUtil.getApplicationContext().getBean(JpaTransactionManager.class);
    }

    @Override
    public void run() {
        boolean flag = true;

        while (flag) {

            PageRequest pageRequest = new PageRequest(0, 100);
            Page<DoctorPatientGroupInfo> groups = groupInfoDao.findByIdRange(start, end, pageRequest);

            if (groups != null && groups.getContent().size() < 100) {
                flag = false;
            }

            start = groups.getContent().get(groups.getContent().size() - 1).getId() + 1;

            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别，开启新事务
            TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态
            try {
                groupToLabel(groups);
                //事物提交
                transactionManager.commit(status);
            } catch (Exception e) {
                transactionManager.rollback(status);
            }
        }
    }

    void groupToLabel(Page<DoctorPatientGroupInfo> groups) {
        System.out.println("sign-patient-group-team:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        Map<String, SignPatientLabelInfo> normalLabel = new HashMap<>();
        Map<String, SignPatientLabelInfo> healthMap = new HashMap<>();

        List<DoctorPatientGroupInfo> groupInfos = groups.getContent();

        for (DoctorPatientGroupInfo groupInfo : groupInfos) {
            SignPatientLabelInfo labelInfo = new SignPatientLabelInfo();

            labelInfo.setPatient(groupInfo.getPatient());
            labelInfo.setPname(groupInfo.getPname());
            if (groupInfo.getGroup().equals("1")) {
                labelInfo.setLabel("1");
                labelInfo.setLabelName("普通人群");
            } else if (groupInfo.getGroup().equals("2")) {
                labelInfo.setLabel("2");
                labelInfo.setLabelName("慢病人群");
            } else if (groupInfo.equals(3)) {
                labelInfo.setLabel("3");
                labelInfo.setLabelName("65岁以上人群");
            } else {
                continue;
            }
            labelInfo.setLabelType("1");
            labelInfo.setStatus(1);
            labelInfo.setCzrq(new Date());

            List<SignPatientLabelInfo> patientLabels = labelInfoDao.findByPatientAndStatus(labelInfo.getPatient(), 1);

            SignPatientLabelInfo healthLabel = null;
            SignPatientLabelInfo wjwGroup = null;
            String typeTwo = "1";

            for (SignPatientLabelInfo patientLabel : patientLabels) {
                if (patientLabel.getLabelType().equals("3")) {
                    typeTwo = "2";
                }
                if (patientLabel.getLabelType().equals("1")) {
                    wjwGroup = patientLabel;
                }
                if (patientLabel.getLabelType().equals("2")) {
                    healthLabel = patientLabel;
                }
            }

            if (healthLabel == null) {
                healthLabel = new SignPatientLabelInfo();

                healthLabel.setPatient(groupInfo.getPatient());
                healthLabel.setPname(groupInfo.getPname());
                healthLabel.setLabelType("2");
                healthLabel.setStatus(1);
                healthLabel.setCzrq(new Date());
            }

            if (typeTwo.equals("1")) {
                healthLabel.setLabel("1");
                healthLabel.setLabelName("健康人群");
            } else {
                healthLabel.setLabel("2");
                healthLabel.setLabelName("患病人群");
            }

            healthMap.put(groupInfo.getPatient(), healthLabel);

            if (wjwGroup != null) {
                wjwGroup.setLabel(labelInfo.getLabel());
                wjwGroup.setLabelName(labelInfo.getLabelName());
                wjwGroup.setCzrq(new Date());
                normalLabel.put(groupInfo.getPatient(), wjwGroup);
            } else {
                normalLabel.put(groupInfo.getPatient(), labelInfo);
            }
        }

        if (normalLabel.size() > 0) {
            labelInfoDao.save(normalLabel.values());
        }
        if (healthMap.size() > 0) {
            labelInfoDao.save(healthMap.values());
        }

        groupInfoDao.save(groups);

        System.out.println("sign-patient-group-team:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }
}
