package com.yihu.figure.service;

import com.yihu.figure.dao.patient.PatientInfoDao;
import com.yihu.figure.dao.patient.portrait.UserPortraitDao;
import com.yihu.figure.model.disease.Visit;
import com.yihu.figure.model.patient.PatientInfo;
import com.yihu.figure.model.patient.portrait.UserPortrait;
import com.yihu.figure.util.DateUtil;
import com.yihu.figure.util.IdCardUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Created by chenweida on 2017/3/8.
 */
@Service
public class PortraitService {
    @Autowired
    private UserPortraitDao userPortraitDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PatientInfoDao patientDao;

    public List<UserPortrait> getPatientInfo(String category, String subCategory, String value) {
        StringBuffer sql = new StringBuffer("select * from figure_user_portrait f where 1=1");
        List params = new ArrayList<>();

        if (!StringUtils.isEmpty(category)) {
            sql.append(" and f.category = ? ");
            params.add(category);
        }
        if (!StringUtils.isEmpty(subCategory)) {
            sql.append(" and f.sub_category = ? ");
            params.add(subCategory);
        }
        if (!StringUtils.isEmpty(value)) {
            sql.append(" and f.value like ? ");
            params.add("%" + value + "%");
        }
        List<UserPortrait> userPortraits = jdbcTemplate.query(sql.toString(), params.toArray(), new BeanPropertyRowMapper(UserPortrait.class));

        return userPortraits;
    }

    @Transactional
    public void newPortrait(String category, String subCategory) {
        List<PatientInfo> patient = patientDao.findAllPatient();
        List<UserPortrait> ups = new ArrayList<>();
        patient.stream().forEach(p -> {
            UserPortrait u = new UserPortrait();
            u.setCategory(category);
            u.setSubCategory(subCategory);
            u.setCzrq(new Date());
            u.setUserCode(p.getCode());
            //年龄
            //ups.add(age(DateUtil.getAgeByBirthday(p.getBirthday()),u));
            //市
            //ups.add(city("厦门市",u));
            //区
            //ups.add(town(p.getTownName(),u));
            //性别标签
            //ups.add(sex(p.getSex(),u));
            //疾病标签
            // ups.add(jibing(p,u));
            //健康分布
            ups.add(jkfb(p, u));
        });
        userPortraitDao.save(ups);
    }

    private UserPortrait jkfb(PatientInfo p, UserPortrait u) {
        Integer age = DateUtil.getAgeByBirthday(p.getBirthday());
        if (age > 25)
            u.setValue("患病人群");
        return u;
    }

    private UserPortrait jibing(PatientInfo p, UserPortrait u) {
        Integer age = DateUtil.getAgeByBirthday(p.getBirthday());
        if (age > 25)
            u.setValue("糖尿病");
        return u;
    }

    private UserPortrait city(String townName, UserPortrait u) {
        u.setValue(townName);
        return u;
    }


    private UserPortrait sex(Integer sex, UserPortrait u) {
        if (sex != null && sex == 2) {
            u.setValue("女");
        } else {
            u.setValue("男");
        }
        return u;
    }

    private UserPortrait town(String townName, UserPortrait u) {
        u.setValue(townName);
        return u;
    }

    private UserPortrait age(int age, UserPortrait u) {
        if (age <= 20) {
            u.setValue("20岁以下");
        } else if (age > 20 && age <= 40) {
            u.setValue("20-40岁");
        } else if (age > 40 && age <= 65) {
            u.setValue("40-65岁");
        } else {
            u.setValue("65岁以上");
        }
        return u;
    }

    /**
     * 根据疾病获取病人区域分布
     *
     * @param subcategory 二级指标的维度
     * @param value       疾病名称 糖尿病 高血压
     * @return
     */
    public Map<String, Integer> getPortraits(String subcategory, String value) {
        //查找除子类别是1002001中的其他类别 例如 查找高血压下的各个年龄段的患者
        String sql = " select * from " +
                " (select DISTINCT(u.user_code) user_code from figure_user_portrait u where u.sub_category='1002001' and u.`value` like ? ) jb," +
                " (select DISTINCT(u.user_code) user_code,u.`value` from figure_user_portrait u where u.sub_category= ?  ) q " +
                " where jb.user_code=q.user_code ";
        List params = new ArrayList<>();
        params.add("%" + value + "%");
        params.add(subcategory);
        List<UserPortrait> userPortraits = jdbcTemplate.query(sql, params.toArray(), new BeanPropertyRowMapper(UserPortrait.class));
        Map<String, Integer> data = new HashMap<>();
        userPortraits.stream().forEach(u -> {
            Integer sum = 1;
            if (data.containsKey(u.getValue())) {
                sum = data.get(u.getValue()) + 1;
            }
            data.put(u.getValue(), sum);
        });
        //总数 用于控制层计算
        data.put("allSize", userPortraits.size());
        return data;
    }

    public List<UserPortrait> findPortraits(String userCode) {
        return userPortraitDao.findByPatientCode(userCode);
    }
    /**
     * @param key 1 疾病 2 健康分布
     * @return
     */
    public Map<String, Integer> getPortraitsLevel1(String key) {
        //找出对应的子类别代码
        String subCategory = getSubCategory(key);
        //根据子类别找出所有的用户标签
        List<UserPortrait> ups = userPortraitDao.findBySubCategory(subCategory);
        Map<String, Integer> returnMap = new HashMap<>();
        ups.stream().forEach(up -> {
            Integer sum = 1;
            if (returnMap.containsKey(up.getValue())) {
                sum = returnMap.get(up.getValue()) + 1;
            }
            returnMap.put(up.getValue(), sum);
        });
        //总数 用于控制层计算
        returnMap.put("allSize", ups.size());
        return returnMap;
    }

    private String getSubCategory(String key) {
        switch (key) {
            case "1": {
                return "1002001";
            }
            case "2": {
                return "1002006";
            }
        }
        return "";
    }

    public UserPortrait findPortraitById(Long id) {

        return userPortraitDao.findOne(id);
    }

}
