package com.emr.service;

import com.emr.dao.CommomMapper;
import com.emr.dao.Emr_DictionaryMapper;
import com.emr.dao.Zd_Icd_CodeMapper;
import com.emr.dao.emrCode.T_OperateMapper;
import com.emr.dao.tCheck.TCheckMapper;
import com.emr.entity.Emr_Dictionary;
import com.emr.entity.Zd_Icd_Code;
import com.emr.entity.emrCode.T_Operate;
import com.emr.entity.tCheck.TCheck;
import com.emr.vo.Msg;
import com.emr.vo.commomSearch.CommomVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @ProjectName:
 * @Description:
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/9/18 11:54
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/9/18 11:54
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Service
@Transactional
public class FontService {
    @Autowired
    private CommomMapper commomMapper;
    @Autowired
    private Emr_DictionaryMapper dictionaryMapper;
    @Autowired
    private T_OperateMapper operateMapper;
    @Autowired
    private Zd_Icd_CodeMapper icdCodeMapper;
    @Autowired
    private TCheckMapper tCheckMapper;
    public Msg updateTableCommom(CommomVo commom){
        String patientId = commom.getPatientId();
        if(StringUtils.isBlank(patientId)){
            return Msg.fail("主键patientId不能为空!");
        }
        //处理数据
        //需要转换字典的处理
        ConvertOper(commom);
        //admiss_days 实际住院天数
        if(StringUtils.isNotBlank(commom.getAdmissDate()) && StringUtils.isNotBlank(commom.getDisDate())){
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date startDate = fmt.parse(commom.getAdmissDate());
                Date endDate = fmt.parse(commom.getDisDate());
                int days = getDistanceTime(startDate, endDate);
                commom.setAdmissDays(days);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        //is_oper	是否手术处理
        List<T_Operate> t_operates = operateMapper.selectAllByPatientId(patientId, null);
        if(null != t_operates && !t_operates.isEmpty()){
            commom.setIsOper("有");
        }else{
            commom.setIsOper("无");
        }
        //is_medicine	是否药物过敏
        List<TCheck> tChecks = tCheckMapper.selectIsMedicineByPatientId(patientId);
        if(null != tChecks && !tChecks.isEmpty()){
            commom.setIsMedicine("有");
        }else{
            commom.setIsMedicine("无");
        }
        //操作commomtable表
        CommomVo commomVo = commomMapper.selectByPrimaryKey(patientId);
        if(null == commomVo){
            //新增
            commomMapper.insertSelective(commom);
        }else{
            //修改
            BeanUtils.copyProperties(commom,commomVo);
            commomMapper.updateByPrimaryKeySelective(commomVo);
        }

        //操作commomtable1表
        CommomVo commomVo1 = commomMapper.selectByPrimaryKey1(patientId);
        if(null == commomVo1){
            //新增
            commomMapper.insertSelective1(commom);
        }else{
            //修改
            BeanUtils.copyProperties(commom,commomVo1);
            commomMapper.updateByPrimaryKeySelective1(commomVo1);
        }
        return Msg.success();
    }
    //需要转换字典的处理
    private void ConvertOper(CommomVo commom){
        //性别
        if(StringUtils.isNotBlank(commom.getSex())){
            ConvertDictionary("sex_code",commom,"sex");
        }
        //出院科室
        if(StringUtils.isNotBlank(commom.getDisDept())){
            ConvertDictionary("dept_code",commom,"disDept");
        }
        //main_dis_thing 主要诊断转归情况
        if(StringUtils.isNotBlank(commom.getMainDisThing())){
            ConvertDictionary("dis_diag_status",commom,"mainDisThing");
        }
        //country	国籍
        if(StringUtils.isNotBlank(commom.getCountry())){
            ConvertDictionary("country",commom,"country");
        }
        //birth_addr	出生地
        if(StringUtils.isNotBlank(commom.getBirthAddr())){
            ConvertDictionary("district_code",commom,"birthAddr");
        }
        //job 职业
        if(StringUtils.isNotBlank(commom.getJob())){
            ConvertDictionary("job",commom,"job");
        }
        //marriage	婚况
        if(StringUtils.isNotBlank(commom.getMarriage())){
            ConvertDictionary("marital_status",commom,"marriage");
        }
        //relation	联系人关系
        if(StringUtils.isNotBlank(commom.getRelation())){
            ConvertDictionary("relation",commom,"relation");
        }
        //pay_type	医疗付费方式
        if(StringUtils.isNotBlank(commom.getPayType())){
            ConvertDictionary("pay_type",commom,"payType");
        }
        //admiss_type	入院途径
        if(StringUtils.isNotBlank(commom.getAdmissType())){
            ConvertDictionary("admiss_type",commom,"admissType");
        }
        //admiss_dept	入院科别
        if(StringUtils.isNotBlank(commom.getAdmissDept())){
            ConvertDictionary("dept_code",commom,"admissDept");
        }
        //admiss_ward	入院病房
        if(StringUtils.isNotBlank(commom.getAdmissWard())){
            ConvertDictionary("dept_code",commom,"admissWard");
        }
        //change_dept	转科科别
        if(StringUtils.isNotBlank(commom.getChangeDept())){
            ConvertDictionary("dept_code",commom,"changeDept");
        }
        //dis_ward	出院病房
        if(StringUtils.isNotBlank(commom.getDisWard())){
            ConvertDictionary("dept_code",commom,"disWard");
        }
        //admiss_thing	入院病情
        if(StringUtils.isNotBlank(commom.getAdmissThing())){
            ConvertDictionary("admiss_thing",commom,"admissThing");
        }
        //emit_pathology	是否死亡患者尸检
        if(StringUtils.isNotBlank(commom.getEmitPathology())){
            ConvertDictionary("diag_conform",commom,"emitPathology");
        }
        //quality	病案质量
        if(StringUtils.isNotBlank(commom.getQuality())){
            ConvertDictionary("quality_level",commom,"quality");
        }
        //blood_type	血型
        if(StringUtils.isNotBlank(commom.getBloodType())){
            ConvertDictionary("blood_type",commom,"bloodType");
        }

        //RH	Rh
        if(StringUtils.isNotBlank(commom.getRh())){
            ConvertDictionary("rh_code",commom,"rh");
        }
        //clinic_name 门((急)诊诊断
        if(StringUtils.isNotBlank(commom.getClinicName())){
            List<Zd_Icd_Code> zd_icd_codes = icdCodeMapper.selectAll(commom.getClinicName(),null);
            if(null != zd_icd_codes && !zd_icd_codes.isEmpty()){
                commom.setClinicName(zd_icd_codes.get(0).getName());
            }else{
                commom.setClinicName(null);
            }
        }
    }
    //转换字典公共方法
    private void ConvertDictionary(String typeCode, CommomVo commom, String field){
        List<Emr_Dictionary> list = dictionaryMapper.selectDictionaryByTypeCode(typeCode);
        Class<? extends CommomVo> aClass = commom.getClass();
        try {
            Field f = aClass.getDeclaredField(field);
            if(null != list && !list.isEmpty()){
                f.setAccessible(true);
                for (Emr_Dictionary dictionary : list) {
                    if (dictionary.getCode().equals(f.get(commom).toString())) {
                        f.set(commom, dictionary.getName());
                        break;
                    }
                }
            }else{
                f.set(commom,null);
            }
        }catch (Exception e){
           e.printStackTrace();
        }
    }
    //计算时间差，以天数为单位。如：2018-08-08 和 2018-08-05 相差3天
    public static int getDistanceTime(Date startTime, Date endTime) {
        int days = 0;
        long time1 = startTime.getTime();
        long time2 = endTime.getTime();

        long diff;
        if (time1 < time2) {
            diff = time2 - time1;
        } else {
            diff = time1 - time2;
        }
        days = (int) (diff / (24 * 60 * 60 * 1000));
        return days;
    }
}
