package com.yihu.jw.base.service.dict;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.base.enums.SystemDictEnum;
import com.yihu.jw.base.service.org.BaseOrgService;
import com.yihu.jw.dict.dao.DictHospitalDeptDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.org.BaseOrgDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.utils.StringUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.yihu.jw.entity.base.dict.DictHospitalDeptDO;

import javax.sound.sampled.Mixer;
import java.io.IOException;
import java.lang.management.MemoryMXBean;
import java.util.*;

/**
 * 
 * 医院科室字典服务service
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * litaohong    1.0  2018年08月31日 Created
 *
 * </pre>
 * @since 1.
 */
@Service
public class DictHospitalDeptService extends BaseJpaService<DictHospitalDeptDO, DictHospitalDeptDao> {

    @Autowired
    private DictHospitalDeptDao dictHospitalDeptDao;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private BaseOrgService baseOrgService;
    @Autowired
    private BaseOrgDao baseOrgDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private BaseDoctorHospitalDao baseDoctorHospitalDao;
    @Autowired
    private WlyyHospitalSysDictDao wlyyHospitalSysDictDao;
    /**
     * 查询某一租户下的医院科室字典信息，如果saadId为空表示当前用户角色为超级管理员，超级管理员可以看到所有数据
     * @param saasId
     * @return
     */
    public JSONObject queryAll(String saasId, Pageable pageable) throws Exception{
        JSONObject jsonObject = new JSONObject();
        List<Map<String,Object>> list = new ArrayList<>();
        long count = 0;
        if(StringUtils.isEmpty(saasId)){
            list = dictHospitalDeptDao.findCodeAndName(pageable);
            count = dictHospitalDeptDao.count();
        }else{
            List orgCodeList = baseOrgService.findOrgCodeListBySaasId(saasId);
            list = dictHospitalDeptDao.findByOrgCodeIn(objectMapper.writeValueAsString(orgCodeList),pageable);
            count = dictHospitalDeptDao.countByCodeIn(saasId);
        }
        jsonObject.put("count",count);
        jsonObject.put(SystemDictEnum.HospitalDeptDict.toString(),list);
        return jsonObject;
    }

    /**
     * 获取租户的所有机构科室
     * @param saasId
     * @return
     */
    public List<DictHospitalDeptDO> findBySaasId(String saasId){
        List<DictHospitalDeptDO>  list = new ArrayList<>();
        if(StringUtils.isEmpty(saasId)){
            list = (List<DictHospitalDeptDO>)dictHospitalDeptDao.findAll();
            return list;
        }
        List orgCodeList = baseOrgService.findOrgCodeListBySaasId(saasId);
        try {
            list = dictHospitalDeptDao.findByOrgCodeIn(objectMapper.writeValueAsString(orgCodeList));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 根据机构标识获取科室
     * @param orgCode
     * @return
     */
    public List<DictHospitalDeptDO> findDeptByOrgCode(String orgCode){
        List<DictHospitalDeptDO>  list = new ArrayList<>();
       if(StringUtils.isEmpty(orgCode)){
           return list;
       }
       return dictHospitalDeptDao.findByOrgCode(orgCode);
    }

    /**
     * 批量保存
     * @return
     */
    public void saveBatch(List<DictHospitalDeptDO> dictHospitalDeptDOS)throws Exception{
        dictHospitalDeptDao.save(dictHospitalDeptDOS);
    }
    /**
     * 查询单个科室信息 带医生
     * @return
     */
    public Map findDept(Integer id,Integer page,Integer pageSize){
        Map<String ,Object> returnMap = new HashMap<>();
        DictHospitalDeptDO dictHospitalDeptDO = dictHospitalDeptDao.findOne(id);
        if (StringUtils.isNoneBlank(dictHospitalDeptDO.getFatherDeptCode())){
            DictHospitalDeptDO fatherDeptDO =  dictHospitalDeptDao.findOne(Integer.parseInt(dictHospitalDeptDO.getFatherDeptCode()));
            if(fatherDeptDO!=null){
                dictHospitalDeptDO.setFatherDeptName(fatherDeptDO.getName());
            }
        }
        if (dictHospitalDeptDO!=null){
            String sql = "select b.name as \"name\",b.id as \"id\"," +
                    " b.sex as \"sex\"," +
                    " b.idcard as \"idcard\"," +
                    " b.mobile as \"mobile\"," +
                    " d.dept_code as \"deptCode\"," +
                    " d.dept_name as \"deptName\"," +
                    " b.job_title_code as \"jobTitleCode\"," +
                    " b.job_title_name as \"jobTitleName\"" +
                    " from base_doctor_hospital d " +
                    " left join dict_hospital_dept p on d.dept_code = p.code" +
                    " left join base_doctor b on d.doctor_code = b.id" +
                    " where d.del='1' and d.dept_code = '"+dictHospitalDeptDO.getCode()+"'";
            System.out.println(sql);
            List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,page,pageSize);
            List<Map<String,Object>> listCount = hibenateUtils.createSQLQuery(sql);
            for (Map<String,Object> map:list){
                if (map.get("idcard")!=null){
                    map.put("age", IdCardUtil.getAgeForIdcard(map.get("idcard").toString()));
                }
            }
            returnMap.put("doctorList",list);
            if (listCount!=null){
                returnMap.put("doctorListCount",listCount.size());
            }else {
                returnMap.put("doctorListCount",0);
            }

        }
        returnMap.put("dept",dictHospitalDeptDO);
        return returnMap;
    }
    /**
     * 新增科室
     * @return
     */
    public DictHospitalDeptDO addDept(String jsonData,String doctorIds) throws IOException {
        DictHospitalDeptDO dictHospitalDeptDO = objectMapper.readValue(jsonData,DictHospitalDeptDO.class);
        if (dictHospitalDeptDO.getId()!=null){
            dictHospitalDeptDO.setDeptTypeCode("6");
            if (StringUtils.isNoneBlank(dictHospitalDeptDO.getFatherDeptCode())){
                DictHospitalDeptDO father  =dictHospitalDeptDao.findOne(Integer.parseInt(dictHospitalDeptDO.getFatherDeptCode()));
                if (father!=null){
                    dictHospitalDeptDO.setFatherDeptName(father.getName());
                }
            }
            BaseOrgDO baseOrgDO = baseOrgDao.findByCode(dictHospitalDeptDO.getOrgCode());
            dictHospitalDeptDO.setOrgCode(dictHospitalDeptDO.getOrgCode());
            if (baseOrgDO!=null){
                dictHospitalDeptDO.setOrgName(baseOrgDO.getName());
            }
            dictHospitalDeptDao.save(dictHospitalDeptDO);
            if (StringUtils.isNoneBlank(doctorIds)){
                if (doctorIds.contains(",")){
                    String[] doctorId = doctorIds.split(",");
                    List<BaseDoctorHospitalDO> depts = baseDoctorHospitalDao.findByOrgCodeAndDeptCodeAndDel(dictHospitalDeptDO.getOrgCode(),dictHospitalDeptDO.getCode(),"1");
                    for (int i=0;i<doctorId.length;i++){
                        List<BaseDoctorHospitalDO> doctors=  baseDoctorHospitalDao.findByOrgCodeAndDeptCodeAndDoctorCode(dictHospitalDeptDO.getOrgCode(),dictHospitalDeptDO.getCode(),doctorId[i]);
                        if (doctors!=null&&doctors.size()>0){

                        }else {
                            BaseDoctorHospitalDO baseDoctorHospitalDO = new BaseDoctorHospitalDO();
                            baseDoctorHospitalDO.setOrgCode(dictHospitalDeptDO.getOrgCode());
                            if (baseOrgDO!=null){
                                baseDoctorHospitalDO.setOrgName(baseOrgDO.getName());
                            }
                            baseDoctorHospitalDO.setDoctorCode(doctorId[i]);
                            baseDoctorHospitalDO.setDeptName(dictHospitalDeptDO.getName());
                            baseDoctorHospitalDO.setDeptCode(dictHospitalDeptDO.getCode());
                            baseDoctorHospitalDO.setDel("1");
                            baseDoctorHospitalDO.setCreateTime(new Date());
                            baseDoctorHospitalDao.save(baseDoctorHospitalDO);
                        }
                        if (depts!=null&&depts.size()>0){
                            for (int j=0;j<depts.size();j++){
                                if (depts.get(j).getDoctorCode().equalsIgnoreCase(doctorId[i])){
                                    depts.remove(j);
                                }
                            }
                        }
                    }
                    if (depts!=null&&depts.size()>0){
                       for (BaseDoctorHospitalDO baseDoctorHospitalDO:depts){
                           baseDoctorHospitalDO.setDel("0");
                           baseDoctorHospitalDao.save(baseDoctorHospitalDO);
                       }
                    }
                }else {
                    List<BaseDoctorHospitalDO> depts = baseDoctorHospitalDao.findByOrgCodeAndDeptCodeAndDel(dictHospitalDeptDO.getOrgCode(),dictHospitalDeptDO.getCode(),"1");
                    List<BaseDoctorHospitalDO> doctors=  baseDoctorHospitalDao.findByOrgCodeAndDeptCodeAndDoctorCode(dictHospitalDeptDO.getOrgCode(),dictHospitalDeptDO.getCode(),doctorIds);
                    if (doctors!=null&&doctors.size()>0){

                    }else {
                        BaseDoctorHospitalDO baseDoctorHospitalDO = new BaseDoctorHospitalDO();
                        baseDoctorHospitalDO.setOrgCode(dictHospitalDeptDO.getOrgCode());
                        if (baseOrgDO!=null){
                            baseDoctorHospitalDO.setOrgName(baseOrgDO.getName());
                        }
                        baseDoctorHospitalDO.setDoctorCode(doctorIds);
                        baseDoctorHospitalDO.setDeptName(dictHospitalDeptDO.getName());
                        baseDoctorHospitalDO.setDeptCode(dictHospitalDeptDO.getCode());
                        baseDoctorHospitalDO.setDel("1");
                        baseDoctorHospitalDO.setCreateTime(new Date());
                        baseDoctorHospitalDao.save(baseDoctorHospitalDO);
                    }
                    if (depts!=null&&depts.size()>0){
                        for (int j=0;j<depts.size();j++){
                            if (depts.get(j).getDoctorCode().equalsIgnoreCase(doctorIds)){
                                depts.remove(j);
                            }
                        }
                    }
                    if (depts!=null&&depts.size()>0){
                        for (BaseDoctorHospitalDO baseDoctorHospitalDO:depts){
                            baseDoctorHospitalDO.setDel("0");
                            baseDoctorHospitalDao.save(baseDoctorHospitalDO);
                        }
                    }
                }
            }else {
                List<BaseDoctorHospitalDO> depts = baseDoctorHospitalDao.findByOrgCodeAndDeptCode(dictHospitalDeptDO.getOrgCode(),dictHospitalDeptDO.getCode());
                if (depts!=null&&depts.size()>0){
                    for (BaseDoctorHospitalDO baseDoctorHospitalDO:depts){
                        baseDoctorHospitalDO.setDel("0");
                        baseDoctorHospitalDao.save(baseDoctorHospitalDO);
                    }
                }
            }
        }else {
            if (StringUtils.isNoneBlank(dictHospitalDeptDO.getFatherDeptCode())){
                DictHospitalDeptDO father  = dictHospitalDeptDao.findOne(Integer.parseInt(dictHospitalDeptDO.getFatherDeptCode()));
                if (father!=null){
                    dictHospitalDeptDO.setFatherDeptName(father.getName());
                }
            }
            BaseOrgDO baseOrgDO = baseOrgDao.findByCode(dictHospitalDeptDO.getOrgCode());
            dictHospitalDeptDO.setOrgCode(dictHospitalDeptDO.getOrgCode());
            if (baseOrgDO!=null){
                dictHospitalDeptDO.setOrgName(baseOrgDO.getName());
            }
            dictHospitalDeptDO.setCreateTime(new Date());
            dictHospitalDeptDO.setDeptTypeCode("6");
            dictHospitalDeptDO = dictHospitalDeptDao.save(dictHospitalDeptDO);
            if (StringUtils.isNotBlank(doctorIds)){
                if (doctorIds.contains(",")){
                    String[] doctorId = doctorIds.split(",");
                    for (int i = 0;i<doctorId.length;i++){
                        BaseDoctorHospitalDO baseDoctorHospitalDO = new BaseDoctorHospitalDO();
                        baseDoctorHospitalDO.setDoctorCode(doctorId[i]);
                        baseDoctorHospitalDO.setDeptName(dictHospitalDeptDO.getName());
                        baseDoctorHospitalDO.setDeptCode(dictHospitalDeptDO.getCode());
                        baseDoctorHospitalDO.setOrgCode(dictHospitalDeptDO.getOrgCode());
                        baseDoctorHospitalDO.setOrgName(dictHospitalDeptDO.getOrgName());
                        baseDoctorHospitalDO.setDel("1");
                        baseDoctorHospitalDO.setCreateTime(new Date());
                        baseDoctorHospitalDao.save(baseDoctorHospitalDO);
                    }
                }else {
                    BaseDoctorHospitalDO baseDoctorHospitalDO = new BaseDoctorHospitalDO();
                    baseDoctorHospitalDO.setDoctorCode(doctorIds);
                    baseDoctorHospitalDO.setDeptName(dictHospitalDeptDO.getName());
                    baseDoctorHospitalDO.setDeptCode(dictHospitalDeptDO.getCode());
                    baseDoctorHospitalDO.setOrgCode(dictHospitalDeptDO.getOrgCode());
                    baseDoctorHospitalDO.setOrgName(dictHospitalDeptDO.getOrgName());
                    baseDoctorHospitalDO.setDel("1");
                    baseDoctorHospitalDO.setCreateTime(new Date());
                    baseDoctorHospitalDao.save(baseDoctorHospitalDO);
                }
            }
        }
        return dictHospitalDeptDO;

    }
   public Map saveDeptDoctor(String doctorIds ,String deptCode,String orgCode){
       DictHospitalDeptDO dictHospitalDeptDO = dictHospitalDeptDao.findByOrgCodedeptCode(orgCode,deptCode);
       Map returnMap = new HashMap();
       if (dictHospitalDeptDO!=null){
           if (StringUtils.isNoneBlank(doctorIds)){
               if (doctorIds.contains(",")){
                   String[] doctorId = doctorIds.split(",");
                   List<BaseDoctorHospitalDO> depts = baseDoctorHospitalDao.findByOrgCodeAndDeptCode(dictHospitalDeptDO.getOrgCode(),dictHospitalDeptDO.getCode());
                   for (int i=0;i<doctorId.length;i++){
                       List<BaseDoctorHospitalDO> doctors=  baseDoctorHospitalDao.findByOrgCodeAndDeptCodeAndDoctorCode(dictHospitalDeptDO.getOrgCode(),dictHospitalDeptDO.getCode(),doctorId[i]);
                       if (doctors!=null&&doctors.size()>0){

                       }else {
                           BaseDoctorHospitalDO baseDoctorHospitalDO = new BaseDoctorHospitalDO();
                           baseDoctorHospitalDO.setDoctorCode(doctorId[i]);
                           baseDoctorHospitalDO.setDeptName(dictHospitalDeptDO.getName());
                           baseDoctorHospitalDO.setDeptCode(dictHospitalDeptDO.getCode());
                           baseDoctorHospitalDO.setOrgCode(dictHospitalDeptDO.getOrgCode());
                           baseDoctorHospitalDO.setOrgName(dictHospitalDeptDO.getOrgName());
                           baseDoctorHospitalDO.setDel("1");
                           baseDoctorHospitalDO.setCreateTime(new Date());
                           baseDoctorHospitalDao.save(baseDoctorHospitalDO);
                       }
                       if (depts!=null&&depts.size()>0){
                           for (int j=0;j<depts.size();j++){
                               if (depts.get(j).getDoctorCode().equalsIgnoreCase(doctorId[i])){
                                   depts.remove(j);
                               }
                           }
                       }
                   }
                   if (depts!=null&&depts.size()>0){
                       for (BaseDoctorHospitalDO baseDoctorHospitalDO:depts){
                           baseDoctorHospitalDO.setDel("0");
                           baseDoctorHospitalDao.save(baseDoctorHospitalDO);
                       }
                   }
               }
           }else {
               List<BaseDoctorHospitalDO> depts = baseDoctorHospitalDao.findByOrgCodeAndDeptCode(dictHospitalDeptDO.getOrgCode(),dictHospitalDeptDO.getCode());
               if (depts!=null&&depts.size()>0){
                   for (BaseDoctorHospitalDO baseDoctorHospitalDO:depts){
                       baseDoctorHospitalDO.setDel("0");
                       baseDoctorHospitalDao.save(baseDoctorHospitalDO);
                   }
               }
           }
           returnMap.put("status",200);
           returnMap.put("msg","保存成功");
       }else {
           returnMap.put("status",-1);
           returnMap.put("msg","保存失败");
       }
       return returnMap;
   }
   public List<Map<String,Object>> findDoctors(String deptCode,String deptName,String doctorCode,String doctorName,String orgid){
        String sql = "select t.code as \"code\",t.name as \"name\" from base_org t where 1=1 ";
        if (StringUtils.isNoneBlank(orgid)){
            sql+=" and t.code = '"+orgid+"'";
        }
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
        if (list!=null&&list.size()>0){
            for (Map<String,Object> orgMap:list){
                String orgCode = orgMap.get("code").toString();
                String doctorDeptSql = "select t.code as \"code\",t.name as \"name\" from dict_hospital_dept t where t.org_code ='"+orgCode+"'";
                if (StringUtils.isNoneBlank(deptCode)){
                    doctorDeptSql+=" and t.code !='"+deptCode+"'";
                }
                if (StringUtils.isNoneBlank(deptName)){
                    doctorDeptSql+=" and t.name like '%"+deptName+"%'";
                }
                List<Map<String,Object>> listdept = hibenateUtils.createSQLQuery(doctorDeptSql);
                if (listdept!=null&&listdept.size()>0){
                    for (Map<String,Object> deptMap:listdept){
                        String dept = deptMap.get("code").toString();
                        String doctorSql = "select b.name as \"name\",b.id as \"code\",t.dept_name as \"deptName\",b.mobile as \"mobile\",b.job_title_name as \"jobTitleName\" from base_doctor_hospital t left join base_doctor b on t.doctor_code = b.id" +
                                " left join base_doctor_mapping m on t.doctor_code = m.doctor  " +
                                " where t.dept_code = '"+dept+"' and t.org_code = '"+orgCode+"'";
                        if (StringUtils.isNoneBlank(doctorCode)){
                            doctorSql+=" and m.mapping_code = '"+doctorCode+"'";
                        }
                        if (StringUtils.isNoneBlank(doctorName)){
                            doctorSql+=" and b.name like '%"+doctorName+"%'";
                        }
                        List<Map<String,Object>> listDoctor = hibenateUtils.createSQLQuery(doctorSql);
                        deptMap.put("childList",listDoctor);
                    }
                    orgMap.put("childList",listdept);
                }
            }
        }
        return list;
   }
   public MixEnvelop queryDept(String orgCode,String consultDeptFlag,String fatherDeptCode,String deptName,String deptCode,String fatherDeptName,Integer page ,Integer size){
        String sql = "select t.id as \"id\"," +
                " t.org_code as \"orgCode\"," +
                " t.code as \"code\"," +
                " t.name as \"name\"," +
                " t.create_time as \"createTime\"," +
                " t.dept_type_code as \"deptTypeCode\"," +
                " t.father_dept_code as \"fatherDeptCode\"," +
                " t.father_dept_name as \"fatherDeptName\"," +
                " t.dept_type as \"deptType\"," +
                " t.dept_position as \"deptPosition\"," +
                " t.consult_dept_flag as \"consultDeptFlag\"," +
                " t.org_name as \"orgName\"," +
                " t.dept_logo as \"deptLogo\"," +
                " t.dept_img as \"deptImg\"," +
                " t.dept_description as \"deptDescription\","+
                " t.usual_name as \"usualName\" " +
                " from dict_hospital_dept t where 1=1";
        if (StringUtils.isNoneBlank(orgCode)){
            sql+=" and t.org_code ='"+orgCode+"'";
        }
       if (StringUtils.isNoneBlank(consultDeptFlag)){
           sql+=" and t.consult_dept_flag ='"+consultDeptFlag+"'";
       }
       if (StringUtils.isNoneBlank(deptCode)){
           sql+=" and t.code ='"+deptCode+"'";
       }
       if (StringUtils.isNoneBlank(fatherDeptCode)){
           sql+=" and t.father_dept_code ='"+fatherDeptCode+"'";
       }
       if (StringUtils.isNoneBlank(deptName)){
           sql+=" and t.name like '%"+deptName+"%'";
       }
       if (StringUtils.isNoneBlank(fatherDeptName)){
           sql+=" and t.father_dept_name like '%"+fatherDeptName+"%'";
       }
       List<WlyyHospitalSysDictDO> sysDictDOS=wlyyHospitalSysDictDao.findByDictName("drugStoreStatus");
       List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,page,size);
       List<Map<String,Object>> listCount = hibenateUtils.createSQLQuery(sql);
       if (sysDictDOS!=null&&list.size()>0){
           for (Map<String,Object> map:list){
               for (WlyyHospitalSysDictDO sysDictDO:sysDictDOS){
                   if (map.get("consultDeptFlag").toString().equalsIgnoreCase(sysDictDO.getDictCode())){
                       map.put("consultDeptFlagName",sysDictDO.getDictValue());
                   }
               }
           }
       }
       MixEnvelop mixEnvelop = new MixEnvelop();
       mixEnvelop.setDetailModelList(list);
       mixEnvelop.setCurrPage(page);
       mixEnvelop.setPageSize(size);
       mixEnvelop.setTotalCount(listCount==null?0:listCount.size());
       return mixEnvelop;
   }
    public DictHospitalDeptDO unUsed(Integer id,String consultFlag){
        DictHospitalDeptDO dictHospitalDeptDO= dictHospitalDeptDao.findOne(id);
        if (dictHospitalDeptDO!=null){
            dictHospitalDeptDO.setConsultDeptFlag(consultFlag);
            dictHospitalDeptDao.save(dictHospitalDeptDO);
        }
        return dictHospitalDeptDO;
    }

}
