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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.family.BasePatientMemberDictDO;
import com.yihu.jw.entity.hospital.mapping.DoctorMappingDO;
import com.yihu.jw.entity.hospital.message.BaseBannerDO;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.family.dao.BasePatientMemberDictDao;
import com.yihu.jw.hospital.mapping.dao.DoctorMappingDao;
import com.yihu.jw.restmodel.iot.common.UploadVO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.eval.MissingArgEval;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class WlyyHospitalSysDictService extends BaseJpaService<WlyyHospitalSysDictDO, WlyyHospitalSysDictDao> {
    @Autowired
    private  WlyyHospitalSysDictDao wlyyHospitalSysDictDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private DoctorMappingDao doctorMappingDao;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Value("${wechat.id}")
    private String wechatId;
    @Autowired
    private StringRedisTemplate redisTemplate;
    //查字典
    public MixEnvelop findDictsByNameCode(String modelName,String name,String code,String value,Integer page ,Integer pageSize){
        String  sql = "select t.id as \"id\"," +
                " t.dict_name  as \"dictName\","+
                " t.model_name  as \"modelName\","+
                " t.dict_code  as \"dictCode\","+
                " t.dict_value   as \"dictValue\","+
                " t.sort   as \"sort\","+
                " t.py_code  as \"pyCode\","+
                " t.hospital  as \"hospital\","+
                " t.img_url  as \"imgUrl\","+
                " t.create_time as \"createTime\""+
                " from wlyy_hospital_sys_dict t where 1=1  ";
        if (StringUtils.isNoneBlank(name)){
            sql+=" and t.dict_name = '"+name+"'";
        }
        if (StringUtils.isNoneBlank(modelName)){
            sql+=" and t.model_name like '%"+modelName+"%'";
        }
        if (StringUtils.isNoneBlank(code)){
            sql+=" and t.dict_code like '%"+code+"%'";
        }
        if (StringUtils.isNoneBlank(value)){
            sql+=" and t.dict_value like '%"+value+"%'";
        }
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
            sql+=" and t.dict_code is not null";
        }else {
            sql+=" and t.dict_code is not null and  t.dict_code != ''";
        }
        if (page==null||page==null){
            List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
            MixEnvelop mixEnvelop = new MixEnvelop();
            mixEnvelop.setTotalCount(list==null?0:list.size());
            mixEnvelop.setDetailModelList(list);
            return  mixEnvelop;
        }else {
            List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,page,pageSize);
            List<Map<String,Object>> listCount = hibenateUtils.createSQLQuery(sql);
            MixEnvelop mixEnvelop = new MixEnvelop();
            mixEnvelop.setTotalCount(listCount==null?0:listCount.size());
            mixEnvelop.setCurrPage(page);
            mixEnvelop.setPageSize(pageSize);
            mixEnvelop.setDetailModelList(list);
            return  mixEnvelop;
        }

    }
    //根据id修改或新增字典
    public WlyyHospitalSysDictDO updateOrCreateDict(String json) throws  Exception{
        WlyyHospitalSysDictDO  wlyyHospitalSysDictDO = objectMapper.readValue(json, WlyyHospitalSysDictDO.class);
        String modelName = "";
        if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictName())){
            List<WlyyHospitalSysDictDO> modelNameList=wlyyHospitalSysDictDao.findByDictName(wlyyHospitalSysDictDO.getDictName());
            if (modelNameList!=null&&modelNameList.size()>0){
                modelName= modelNameList.get(0).getModelName();
            }

        }
        wlyyHospitalSysDictDO.setModelName(modelName);
        if(StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getId())){
            WlyyHospitalSysDictDO wlyyHospitalSysDictDO1 = wlyyHospitalSysDictDao.findById(wlyyHospitalSysDictDO.getId());
            if (wlyyHospitalSysDictDO1!=null){
                wlyyHospitalSysDictDO1.setDictValue(wlyyHospitalSysDictDO.getDictValue());
                wlyyHospitalSysDictDO1.setDictCode(wlyyHospitalSysDictDO.getDictCode());
                wlyyHospitalSysDictDO1.setDictName(wlyyHospitalSysDictDO.getDictName());
                wlyyHospitalSysDictDO1.setHospital(wlyyHospitalSysDictDO.getHospital());
                wlyyHospitalSysDictDO1.setPyCode(wlyyHospitalSysDictDO.getPyCode());
                wlyyHospitalSysDictDO1.setImgUrl(wlyyHospitalSysDictDO.getImgUrl());
                wlyyHospitalSysDictDO1.setSort(wlyyHospitalSysDictDO.getSort());
                wlyyHospitalSysDictDO1.setModelName(modelName);
            }else {
                wlyyHospitalSysDictDO1 = new WlyyHospitalSysDictDO();
                wlyyHospitalSysDictDO1.setDictValue(wlyyHospitalSysDictDO.getDictValue());
                wlyyHospitalSysDictDO1.setDictCode(wlyyHospitalSysDictDO.getDictCode());
                wlyyHospitalSysDictDO1.setDictName(wlyyHospitalSysDictDO.getDictName());
                wlyyHospitalSysDictDO1.setHospital(wlyyHospitalSysDictDO.getHospital());
                wlyyHospitalSysDictDO1.setPyCode(wlyyHospitalSysDictDO.getPyCode());
                wlyyHospitalSysDictDO1.setImgUrl(wlyyHospitalSysDictDO.getImgUrl());
                wlyyHospitalSysDictDO1.setSort(wlyyHospitalSysDictDO.getSort());
                wlyyHospitalSysDictDO1.setModelName(modelName);
            }

            return wlyyHospitalSysDictDao.save(wlyyHospitalSysDictDO1);
        }
        return wlyyHospitalSysDictDao.save(wlyyHospitalSysDictDO);
    }
    //根据id删除字典
    public String  deleteDictById(String id){
        String msg = "";
        if (StringUtils.isNoneBlank(id)){
           WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById(id);
           if (wlyyHospitalSysDictDO!=null) {
               wlyyHospitalSysDictDao.delete(id);
               msg = "删除成功";
           }else {
               msg = "没有这条记录";
           }
        }else{
            msg = "id为空";
        }
        return msg;
    }
    public  String findByDoctorMappingCode(String code){
        String doctorId = "";
        if (StringUtils.isNoneBlank(code)){
            List<BaseDoctorDO> list = baseDoctorDao.findByIdcard(code);
            if (list!=null&&list.size()>0){
                doctorId=list.get(0).getId();
            }
        }
        return doctorId;
    }
    public WlyyHospitalSysDictDO findOne(String id){
        return  wlyyHospitalSysDictDao.findById(id);
    }

    //查字典
    public MixEnvelop findModel(String modelName, String name, Integer page , Integer pageSize){
        MixEnvelop mixEnvelop = new MixEnvelop();
        String  sql = "select " +
                " t.dict_name  as \"dictName\","+
                " t.model_name  as \"modelName\""+
                " from wlyy_hospital_sys_dict t where 1=1 ";
        if (StringUtils.isNoneBlank(name)){
            sql+=" and t.dict_name like '%"+name+"%'";
        }
        if (StringUtils.isNoneBlank(modelName)){
            sql+=" and t.model_name like '%"+modelName+"%'";
        }
        sql+=" group by t.dict_name,t.model_name ";
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,page,pageSize);
        List<Map<String,Object>> listCount = hibenateUtils.createSQLQuery(sql);

        if (listCount!=null){
            mixEnvelop.setTotalCount(listCount.size());
        }else {
            mixEnvelop.setTotalCount(0);
        }
        mixEnvelop.setDetailModelList(list);
        mixEnvelop.setCurrPage(page);
        mixEnvelop.setPageSize(pageSize);
        return  mixEnvelop;
    }
    public Envelop updateByModelName(String jsonData) throws Exception{
        Envelop envelop = new Envelop();
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        if (StringUtils.isNoneBlank(jsonObject.getString("preDictName"))){
            String preDictName = jsonObject.get("preDictName").toString();
            List<WlyyHospitalSysDictDO> list  =  wlyyHospitalSysDictDao.findByDictName(preDictName);
            for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:list){
                if (jsonObject.get("dictName")!=null){
                    wlyyHospitalSysDictDO.setDictName(jsonObject.get("dictName").toString());
                }
                if (jsonObject.get("modelName")!=null){
                    wlyyHospitalSysDictDO.setModelName(jsonObject.get("modelName").toString());
                }
            }
            wlyyHospitalSysDictDao.save(list);
            envelop.setMessage("操作成功");
            envelop.setStatus(200);
        }else {
            if (jsonObject.get("dictName")!=null){
                List<WlyyHospitalSysDictDO> list  =  wlyyHospitalSysDictDao.findByDictName(jsonObject.get("dictName").toString());
                if (list!=null&&list.size()>0){
                    throw new Exception("该dictName已经存在");
                }else {
                    WlyyHospitalSysDictDO wlyyHospitalSysDictDO=new WlyyHospitalSysDictDO();
                    wlyyHospitalSysDictDO.setDictName(jsonObject.get("dictName").toString());
                    if (jsonObject.get("modelName")!=null){
                        wlyyHospitalSysDictDO.setModelName(jsonObject.get("modelName").toString());
                    }
                    wlyyHospitalSysDictDao.save(wlyyHospitalSysDictDO);
                }
                envelop.setMessage("操作成功");
                envelop.setStatus(200);

            }else {
                envelop.setMessage("dictName为空");
                envelop.setStatus(-1);
            }

        }
        return envelop;
    }

    public Envelop deleteByModelName(String preDictName){
        Envelop envelop = new Envelop();
        if (StringUtils.isNoneBlank(preDictName)){
            List<WlyyHospitalSysDictDO> list  =  wlyyHospitalSysDictDao.findByDictName(preDictName);
            for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:list){
                wlyyHospitalSysDictDao.delete(wlyyHospitalSysDictDO);
            }
            envelop.setMessage("操作成功");
            envelop.setStatus(200);
        }else {
            envelop.setMessage("preDictName为空");
            envelop.setStatus(-1);
        }
        return envelop;
    }
    public WlyyHospitalSysDictDO downDoctor(String id) throws Exception{
        WlyyHospitalSysDictDO sysDictDO = wlyyHospitalSysDictDao.findOne(id);
        List<WlyyHospitalSysDictDO> maxSortList =  wlyyHospitalSysDictDao.getMaxSort(sysDictDO.getDictName(),sysDictDO.getHospital());
        int maxSort =0;
        if (maxSortList!=null&&maxSortList.size()>0){
            maxSort = maxSortList.get(0).getSort();
        }

        int sort = 0;
        if(null!=sysDictDO){
            sort = sysDictDO.getSort();
        }
        if (maxSort==sort){
            throw new Exception("不能下移");
        }
        String sql = "select t.id AS \"id\" from wlyy_hospital_sys_dict t where t.dict_name='"+sysDictDO.getDictName()+"' and t.hospital='"+sysDictDO.getHospital()+"' and t.sort > "+sort+" order by t.sort asc ";
        System.out.println(sql);
        List<Map<String,Object>> list=hibenateUtils.createSQLQuery(sql,1,1);
        WlyyHospitalSysDictDO upPrevious = new WlyyHospitalSysDictDO();
        if (list.size()>0){
            String prviousId = list.get(0).get("id").toString();
            upPrevious =wlyyHospitalSysDictDao.findOne(prviousId);
        }
        //BaseBannerDO upPrevious = baseBannerDao.upBanner(sort);

        //交换sort值
        sysDictDO.setSort(upPrevious.getSort());
        upPrevious.setSort(sort);
        wlyyHospitalSysDictDao.save(sysDictDO);
        wlyyHospitalSysDictDao.save(upPrevious);
        return sysDictDO;
    }


    public WlyyHospitalSysDictDO upDoctor(String id) throws Exception{
        WlyyHospitalSysDictDO sysDictDO = wlyyHospitalSysDictDao.findOne(id);
        List<WlyyHospitalSysDictDO> minSortList =  wlyyHospitalSysDictDao.getMinSort(sysDictDO.getDictName(),sysDictDO.getHospital());
        int minSort =0;
        if (minSortList!=null&&minSortList.size()>0){
            minSort = minSortList.get(0).getSort();
        }
        int sort = 0;
        if(null!=sysDictDO){
            sort = sysDictDO.getSort();
        }
        if (minSort==sort){
            throw new Exception("不能上移");
        }
        String sql = "select t.id AS \"id\" from wlyy_hospital_sys_dict t where t.dict_name='"+sysDictDO.getDictName()+"' and t.hospital ='"+sysDictDO.getHospital()+"' and t.sort < "+sort+" order by t.sort asc ";
        System.out.println(sql);
        List<Map<String,Object>> list=hibenateUtils.createSQLQuery(sql,1,1);
        WlyyHospitalSysDictDO downPrevious = new WlyyHospitalSysDictDO();
        if (list.size()>0){
            String prviousId = list.get(0).get("id").toString();
            downPrevious =wlyyHospitalSysDictDao.findOne(prviousId);
        }
        //BaseBannerDO upPrevious = baseBannerDao.upBanner(sort);

        //交换sort值
        sysDictDO.setSort(downPrevious.getSort());
        downPrevious.setSort(sort);
        wlyyHospitalSysDictDao.save(sysDictDO);
        wlyyHospitalSysDictDao.save(downPrevious);
        return sysDictDO;
    }
    public void insertSort(String id,Integer sort){
        WlyyHospitalSysDictDO sysDictDO = wlyyHospitalSysDictDao.findOne(id);
        if (sysDictDO!=null){
            Integer  max= 0;
            List<WlyyHospitalSysDictDO> maxList = wlyyHospitalSysDictDao.getMaxSort("doctorFrontList",sysDictDO.getHospital());
            if (maxList!=null&&maxList.size()>0){
                max= maxList.get(0).getSort();
            }
            if (sort!=null&&sort<max){
                List<WlyyHospitalSysDictDO> list = wlyyHospitalSysDictDao.findByDictNameSortOrderBySort(sysDictDO.getDictName(),sysDictDO.getHospital(),sort);
                for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:list){
                    wlyyHospitalSysDictDO.setSort(wlyyHospitalSysDictDO.getSort()+1);
                    wlyyHospitalSysDictDao.save(wlyyHospitalSysDictDO);
                }
                sysDictDO.setSort(sort);
                wlyyHospitalSysDictDao.save(sysDictDO);
            }else if (sort!=null&&sort>=max){
                sysDictDO.setSort(max+1);
                wlyyHospitalSysDictDao.save(sysDictDO);
            }

        }
    }
    public void saveDictDoctor(String json) throws Exception{
        JSONArray jsonArray = JSONArray.parseArray(json);
        if (jsonArray!=null&&jsonArray.size()>0){
            for (int i=0;i<jsonArray.size();i++){
               JSONObject jsonObject = jsonArray.getJSONObject(i);
               String orgCode = jsonObject.getString("hosptial");
               JSONArray dictArray = jsonObject.getJSONArray("dictList");
               Integer  max= 0;
               List<WlyyHospitalSysDictDO> maxList = wlyyHospitalSysDictDao.getMaxSort("doctorFrontList",orgCode);
               if (maxList!=null&&maxList.size()>0){
                   max= maxList.get(0).getSort();
               }
               if (max==null){
                   max = 0;
               }
               for (int j=0;j<dictArray.size();j++){
                   JSONObject jsonObject1 = dictArray.getJSONObject(j);
                   WlyyHospitalSysDictDO wlyyHospitalSysDictDO = jsonObject1.toJavaObject(WlyyHospitalSysDictDO.class);
                   wlyyHospitalSysDictDO.setHospital(orgCode);
                   wlyyHospitalSysDictDO.setSort(max+1);
                   max++;
                   wlyyHospitalSysDictDao.save(wlyyHospitalSysDictDO);
               }
            }
        }
    }

    public MixEnvelop findSortDoctors(String orgCode,String del,String doctorName,Integer page ,Integer pageSize){
        String sql =" select DISTINCT t.id as \"id\"," +
                " t.dict_value as \"dict_value\"," +
                " t.dict_code as \"dict_code\"," +
                " t.sort as \"sort\"," +
                " t.hospital as \"hospital\"," +
                " b.idcard as \"idcard\"," +
                " b.del as \"del\"," +
                " case when b.sex =1 then '男' when b.sex =2 then '女' else '未知' end sex," +
                " b.mobile as \"mobile\"," +
                " b.job_title_name as \"jobTitleName\"," +
                " d.org_name as \"orgName\"" +
                "  from wlyy_hospital_sys_dict t left join base_doctor b on t.dict_code = b.id " +
                " left join base_doctor_hospital d on t.dict_code = d.doctor_code where 1=1 and dict_name ='doctorFrontList' ";
        if (StringUtils.isNoneBlank(orgCode)){
            sql+=" and t.hospital = '"+orgCode+"'";
        }
        if (StringUtils.isNoneBlank(del)){
            sql+=" and b.del = '"+del+"'";
        }
        if (StringUtils.isNoneBlank(doctorName)){
            sql+=" and b.name like '%"+doctorName+"%'";
        }
        sql+=" order by t.sort asc";
        System.out.println("sql++++++"+sql);
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,page,pageSize);
        List<Map<String,Object>> listCount = hibenateUtils.createSQLQuery(sql);
        List<WlyyHospitalSysDictDO> sysDictDOS=wlyyHospitalSysDictDao.findByDictName("drugStoreStatus");
        if (sysDictDOS!=null&&list.size()>0){
            for (Map<String,Object> map:list){
                for (WlyyHospitalSysDictDO sysDictDO:sysDictDOS){
                    if (map.get("del").toString().equalsIgnoreCase(sysDictDO.getDictCode())){
                        map.put("delName",sysDictDO.getDictValue());
                    }
                }
            }
        }
        MixEnvelop mixEnvelop= new MixEnvelop();
        mixEnvelop.setDetailModelList(list);
        mixEnvelop.setPageSize(pageSize);
        mixEnvelop.setCurrPage(page);
        mixEnvelop.setTotalCount(listCount==null?0:list.size());
        return mixEnvelop;
    }

    /**
     * 字典转译
     *
     * @param dictName
     * @param code
     * @return
     */
    public String getDictValue(String dictName, String code) {
        String re = "";
        /*try {
            if (!StringUtils.isEmpty(code)) {
                //判断该字典redis是否存在
                String exit = redisTemplate.opsForValue().get("systemDict:" + dictName);
                if (!StringUtils.isEmpty(exit)) {
                    re = redisTemplate.opsForValue().get("systemDict:" + dictName + ":" + code);
                    if(StringUtils.isEmpty(re)){
                        WlyyHospitalSysDictDO wlyyHospitalSysDictDO= wlyyHospitalSysDictDao.findOneByDictNameAndDictCode(dictName,code);
                        if (wlyyHospitalSysDictDO!=null){
                            re =wlyyHospitalSysDictDO.getDictValue();
                        }

//                        if (!StringUtils.isEmpty(re)) {
//                            redisTemplate.opsForValue().set("systemDict:" + dictName + ":" + code, re);
//                        }
                    }
                } else {
                    List<WlyyHospitalSysDictDO> list = wlyyHospitalSysDictDao.findByDictName(dictName);
                    if (list != null && list.size() > 0) {
                        redisTemplate.opsForValue().set("systemDict:" + dictName, "1");
                        for (WlyyHospitalSysDictDO item : list) {
                            redisTemplate.opsForValue().set("systemDict:" + dictName + ":" + item.getDictCode(), item.getDictValue());
                            if (code.equals(item.getDictCode())) {
                                re = item.getDictValue();
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();

        }*/
        if (StringUtils.isNoneBlank(code)){
            WlyyHospitalSysDictDO wlyyHospitalSysDictDO= wlyyHospitalSysDictDao.findOneByDictNameAndDictCode(dictName,code);
            if (wlyyHospitalSysDictDO!=null){
                re =wlyyHospitalSysDictDO.getDictValue();
                System.out.println("re"+re);
            }
        }
        return re;
    }

}
