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

import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.base.dao.dict.DictIcd10Dao;
import com.yihu.jw.base.enums.SystemDictEnum;
import com.yihu.jw.base.service.dict.importManage.BasDrugUseExcelDO;
import com.yihu.jw.base.service.dict.importManage.BasIcd10ExcelDO;
import com.yihu.jw.dict.dao.BaseTemplateDictDao;
import com.yihu.jw.entity.base.dict.BaseDrugUseDictDO;
import com.yihu.jw.entity.base.dict.BaseFrequencyDictDO;
import com.yihu.jw.entity.base.dict.BaseTemplateDictDO;
import com.yihu.jw.exception.business.ManageException;
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.springframework.beans.BeanUtils;
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.DictIcd10DO;

import java.util.*;

import static com.yihu.jw.util.common.BeanUtils.getNullPropertyNames;

/**
 * 
 * ICD10字典服务service
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * litaohong    1.0  2018年08月31日 Created
 *
 * </pre>
 * @since 1.
 */
@Service
public class DictIcd10Service extends BaseJpaService<DictIcd10DO, DictIcd10Dao> {

    @Autowired
    private DictIcd10Dao dictIcd10Dao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private BaseTemplateDictDao baseTemplateDictDao;

    /**
     * 查询某一租户下的Icd10字典信息，如果saadId为空表示当前用户角色为超级管理员，超级管理员可以看到所有数据
     * @param saasId
     * @return
     */
    public JSONObject queryAll(String saasId, Pageable pageable){
        JSONObject jsonObject = new JSONObject();
        List<Map<String,Object>> list = new ArrayList<>();
        long count = 0;
        if(!StringUtils.isEmpty(saasId)){
           list = dictIcd10Dao.findCodeAndName(pageable);
           count = dictIcd10Dao.count();
        }else{
           list = dictIcd10Dao.findCodeAndNameSaasId(saasId,pageable);
            count = dictIcd10Dao.countBySaasId(saasId);
        }
        jsonObject.put("count",count);
        jsonObject.put(SystemDictEnum.Icd10Dict.toString(),list);
        return jsonObject;
    }
    public void deleteById(Integer id){
        dictIcd10Dao.delete(id);
    }


    public MixEnvelop findIcd10List(String name,String status,Integer page ,Integer pageSize){
        String sql="select t.id as \"id\"," +
                " t.code as \"code\"," +
                " t.name as \"name\"," +
                " t.description as \"description\"," +
                " t.create_time as \"create_time\"," +
                " t.disea_reason as \"disea_reason\"," +
                " t.death_reason as \"death_reason\"," +
                " t.py_code as \"py_code\"," +
                " t.d_code as \"d_code\"," +
                " t.flag as \"flag\"," +
                " t.is_del as \"is_del\"," +
                " t.status as \"status\" " +
                "from dict_icd10 t " +
                " where t.is_del='1'";
        String sqlCount =" select count(1) as \"count\" from dict_icd10 t where t.is_del='1'";
        if (StringUtils.isNoneBlank(name)){
            sql+=" and t.name like '%"+name+"%'";
            sqlCount+=" and t.name like '%"+name+"%'";
        }
        if (StringUtils.isNoneBlank(status)){
            sql+=" and t.status ='"+status+"'";
            sqlCount+=" and t.status ='"+status+"'";
        }
        List<Map<String,Object>> list=hibenateUtils.createSQLQuery(sql,page,pageSize);
        for (Map<String,Object> map:list){
            if (map.get("status")!=null&&"1".equalsIgnoreCase(map.get("status").toString())){
                map.put("statusName","生效中");
            }else {
                map.put("statusName","已失效");
            }
        }
        List<Map<String,Object>> countList=hibenateUtils.createSQLQuery(sqlCount);
        Integer count=0;
        if (countList!=null&&countList.size()>0) {
            count = Integer.valueOf(countList.get(0).get("count").toString());
        }
        MixEnvelop mixEnvelop = new MixEnvelop();
        mixEnvelop.setPageSize(pageSize);
        mixEnvelop.setCurrPage(page);
        mixEnvelop.setDetailModelList(list);
        mixEnvelop.setTotalCount(count);
        return mixEnvelop;
    }
    public void saveIcd10(DictIcd10DO icd10DO) throws Exception{
        DictIcd10DO icd10DO2=dictIcd10Dao.findByCode(icd10DO.getCode());
        if (icd10DO.getId()!=null){
            if (icd10DO2!=null){
                if (icd10DO2.getId()!=icd10DO.getId()){
                    throw  new Exception("该诊断已被使用");
                }
            }
            DictIcd10DO icd10DO1= dictIcd10Dao.findOne(icd10DO.getId());
            BeanUtils.copyProperties(icd10DO, icd10DO1, getNullPropertyNames(icd10DO));
            dictIcd10Dao.save(icd10DO1);
        }else {
            if (icd10DO2!=null){
                throw  new Exception("该诊断已存在");
            }
            icd10DO.setCreateTime(new Date());
            icd10DO.setIs_del("1");
            dictIcd10Dao.save(icd10DO);
        }
    }
    public DictIcd10DO findOneIcd10(Integer id){
        return dictIcd10Dao.findOne(id);
    }


    public Map<String, Object> batchInsertDrugs(List<BasIcd10ExcelDO> drugs, String templateId) throws ManageException {
        Map<String, Object> result = new HashMap<>();
        //批量存储的集合
//        int correctCount = 0;
//        List<BasDrugExcelDO> corrects = new ArrayList<>();
        DictIcd10DO dictIcd10DO;
        //批量存储
        for(BasIcd10ExcelDO one:drugs) {
            dictIcd10DO = new DictIcd10DO();
            dictIcd10DO.setCreateTime(new Date());
            dictIcd10DO.setIs_del("1");
            dictIcd10DO.setCode(one.getCode());
            dictIcd10DO.setD_code(one.getD_code());
            dictIcd10DO.setName(one.getName());
            dictIcd10DO.setPy_code(one.getPy_code());
            dictIcd10DO.setDeath_reason(one.getDeath_reason());
            dictIcd10DO.setDescription(one.getDescription());
            dictIcd10DO.setDisea_reason(one.getDisea_reason());
            dictIcd10DO.setFlag(one.getFlag());
            dictIcd10DO.setStatus(one.getStatus());
            dictIcd10DO=dictIcd10Dao.save(dictIcd10DO);
            if (StringUtils.isNoneBlank(templateId)){
                BaseTemplateDictDO baseTemplateDictDO = new BaseTemplateDictDO();
                baseTemplateDictDO.setTemplateId(templateId);
                baseTemplateDictDO.setIsDel("1");
                baseTemplateDictDO.setDictId(dictIcd10DO.getId().toString());
                baseTemplateDictDO.setCreateTime(new Date());
                baseTemplateDictDao.save(baseTemplateDictDO);
            }
        }
        result.put("correctCount", drugs.size());
        return result;
    }
    public void updateIcd10Status(Integer id,String status,String del) throws Exception{
        DictIcd10DO dictIcd10DO = dictIcd10Dao.findOne(id);
        if (dictIcd10DO!=null){
            if (StringUtils.isNoneBlank(status)){
                dictIcd10DO.setStatus(status);
            }
            if (StringUtils.isNoneBlank(del)){
                dictIcd10DO.setIs_del(del);
                List<BaseTemplateDictDO> baseTemplateDictDO = baseTemplateDictDao.findByDictId(id.toString());
                if (baseTemplateDictDO!=null&&baseTemplateDictDO.size()>0){
                    throw  new Exception("该诊断已存在现有模板之中不允许删除");
                }
            }
            dictIcd10Dao.save(dictIcd10DO);
        }
    }
}
