package com.yihu.jw.patient.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.patient.PatientMedicareCardDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.prescription.WlyyInspectionDO;
import com.yihu.jw.entity.hospital.prescription.WlyyOutpatientDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionInfoDO;
import com.yihu.jw.healthCare.service.HealthCareService;
import com.yihu.jw.hospital.mapping.dao.PatientMappingDao;
import com.yihu.jw.hospital.prescription.dao.OutpatientDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionInfoDao;
import com.yihu.jw.hospital.prescription.dao.WlyyInspectionDao;
import com.yihu.jw.hospital.prescription.service.PrescriptionService;
import com.yihu.jw.hospital.ykyy.service.YkyyService;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.dao.BasePatientGroupDao;
import com.yihu.jw.patient.dao.BasePatientGroupDictDao;
import com.yihu.jw.patient.util.ConstantUtils;
import com.yihu.jw.restmodel.base.patient.BasePatientVO;
import com.yihu.jw.restmodel.hospital.prescription.WlyyInspectionVO;
import com.yihu.jw.restmodel.hospital.prescription.WlyyPrescriptionInfoVO;
import com.yihu.jw.restmodel.hospital.prescription.WlyyPrescriptionVO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.rm.iot.IotRequestMapping;
import com.yihu.jw.sms.dao.HospitalSysDictDao;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.utils.security.MD5;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.repository.CrudRepository;
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.CollectionUtils;

import java.io.IOException;
import java.util.*;

/**
 * 
 * 居民基础信息服务service
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * litaohong    1.0  2018年08月31日 Created
 *
 * </pre>
 * @since 1.
 */
@Service
public class BasePatientService<T, R extends CrudRepository> extends BaseJpaService<BasePatientDO, BasePatientDao> {
    private static final Logger logger = LoggerFactory.getLogger(BasePatientService.class);

    @Autowired
    private BasePatientDao basePatientDao;

    @Autowired
    private BasePatientMedicardCardService basePatientMedicardCardService;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private YkyyService ykyyService;
    @Value("${wechat.id}")
    private String wxId;
    @Autowired
    private OutpatientDao outpatientDao;
    @Value("${demo.flag}")
    private boolean demoFlag;
    @Value("${wechat.flag}")
    private boolean flag;
    @Autowired
    private WlyyInspectionDao wlyyInspectionDao;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private PrescriptionInfoDao prescriptionInfoDao;
    @Autowired
    private BasePatientGroupDao basePatientGroupDao;
    @Autowired
    private BasePatientGroupDictDao basePatientGroupDictDao;
    @Autowired
    private HospitalSysDictDao hospitalSysDictDao;
    @Autowired
    private HealthCareService healthCareService;
    /**
     * 居民id
     * @param patientId
     * @return
     */
    public BasePatientDO findPatientById(String patientId) throws Exception{
        return basePatientDao.findById(patientId);
    }

    public boolean findByIdCard(String idcard){
        BasePatientDO patientDO = basePatientDao.findByIdcardAndDel(idcard,"1");
        if (patientDO != null) {
            return true;
        }
        return false;
    }

    /**
     * 居民id
     * @param patientId
     * @return
     */
    public Map getPatientById(String patientId) throws Exception{
        Map result = new HashMap();
        if(StringUtils.isEmpty(patientId)){
            result.put("result","parameter patientId is null");
            return result;
        }
        BasePatientDO basePatientDO = basePatientDao.findById(patientId);
        /*List<BasePatientDO> patientDOList = this.findByField("id",patientId);
        if(CollectionUtils.isEmpty(patientDOList)){
            result.put("result","not exist patient for id:"+patientId);
            return result.toString();
        }*/

        result.put("patient", basePatientDO);
        List<PatientMedicareCardDO> cards = basePatientMedicardCardService.findPatientCardByCode(patientId);
        if (cards==null||cards.size()==0){
            System.out.println("new一个list");
            PatientMedicareCardDO patientMedicareCardDO = new PatientMedicareCardDO();
            cards.add(patientMedicareCardDO);
        }
        result.put("medicareCard",cards);
        return result;
    }


    /**
     * 获取用户基础信息，参数为空查全部
     * @param nameOrIdcard
     * @param page
     * @param size
     * @param sorts
     * @return
     */
    public MixEnvelop queryPatientBaseInfo(String nameOrIdcard, int page, int size, String sorts)throws Exception{
        List<Map<String, Object>> result = new ArrayList<>();
        String param = null == nameOrIdcard ? "": nameOrIdcard;
        String sql = "SELECT\n" +
                "\tID AS \"id\",\n" +
                "\tidcard AS \"idcard\",\n" +
                "\tNAME AS \"name\",\n" +
                "\tCASE\n" +
                "WHEN sex = 1 THEN\n" +
                "\t'男'\n" +
                "WHEN sex = 2 THEN\n" +
                "\t'女'\n" +
                "ELSE\n" +
                "\t'未知'\n" +
                "END AS \"sex\",\n" +
                " mobile AS \"phone\",\n" +
                " ykt_id AS \"yktId\",\n" +
                " committee_name AS \"committeeName\",\n" +
                " province_name AS \"provinceName\"," +
                " city_name AS \"cityName\", " +
                "town_name AS \"townName\"," +
                " street_name \"streetName\"," +
                " address AS \"address\"\n" +
                "FROM\n" +
                "\tbase_patient\n";
        if (StringUtils.isNotEmpty(nameOrIdcard)){
            sql+="WHERE\n" +
                    "\tNAME LIKE '%"+nameOrIdcard+"%'\n" +
                    "OR idcard LIKE '%"+nameOrIdcard+"%'\n";
        }
        sql+="ORDER BY\n" +
                "\tcreate_time DESC";
        String countSql = "select count(id) from base_patient where name like '%" + param + "%' or idcard like '%" + param + "%'";
        Long count  = jdbcTemplate.queryForObject(countSql,Long.class);
        if(count <= 0){
            return null;
        }
        MixEnvelop envelop = new MixEnvelop();
        result = hibenateUtils.createSQLQuery(sql,page,size);
        envelop.setDetailModelList(result);
        envelop.setTotalCount(count.intValue());
        envelop.setCurrPage(page);
        envelop.setPageSize(size);
        return envelop;
    }

    /**
     * 新增居民
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String createPatient(String jsonData) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        JSONObject patient = jsonObject.getJSONObject("patient");
        JSONArray patientMedicareCards = jsonObject.getJSONArray("medicareCard");
        if(null == patient || CollectionUtils.isEmpty(patientMedicareCards)){
            return ConstantUtils.FAIL;
        }
        BasePatientDO basePatientDO = objectMapper.readValue(patient.toJSONString(),BasePatientDO.class);
        List<PatientMedicareCardDO> list = new ArrayList<>();
        patientMedicareCards.forEach((card)->{
            try {
                list.add(objectMapper.readValue(card.toString(),PatientMedicareCardDO.class));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        this.save(basePatientDO);
        basePatientMedicardCardService.batchInsert(list);
        return ConstantUtils.SUCCESS;
    }

    /**
     * 新增档案
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String createArchive(String jsonData) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        JSONObject patient = jsonObject.getJSONObject("patient");
        if(null == patient){
            return ConstantUtils.FAIL;
        }
        BasePatientDO patientDO = objectMapper.readValue(patient.toJSONString(),BasePatientDO.class);
        this.save(patientDO);
        return ConstantUtils.SUCCESS;
    }

    /**
     * 修改档案
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String updateArchive(String jsonData) throws Exception {
        BasePatientDO basePatientDO = objectMapper.readValue(jsonData,BasePatientDO.class);
        if(StringUtils.isEmpty(basePatientDO.getId())){
            return ConstantUtils.FAIL;
        }
        BasePatientDO basePatientDO1 = basePatientDao.findById(basePatientDO.getId());
        if (null!=basePatientDO1){

            basePatientDO1.setName(basePatientDO.getName());
            basePatientDO1.setMobile(basePatientDO.getMobile());
            basePatientDO1.setIdcard(basePatientDO.getIdcard());
            basePatientDO1.setSex(basePatientDO.getSex());
            basePatientDO1.setBirthday(basePatientDO.getBirthday());
            basePatientDO1.setNational(basePatientDO.getNational());
            basePatientDO1.setNationalName(basePatientDO.getNationalName());
            basePatientDO1.setMarriage(basePatientDO.getMarriage());
            basePatientDO1.setProvinceCode(basePatientDO.getProvinceCode());
            basePatientDO1.setCityCode(basePatientDO.getCityCode());
            basePatientDO1.setTownCode(basePatientDO.getTownCode());
            basePatientDO1.setProvinceName(basePatientDO.getProvinceName());
            basePatientDO1.setTownName(basePatientDO.getTownName());
            basePatientDO1.setCityName(basePatientDO.getCityName());
            basePatientDO1.setMedicareNumber(basePatientDO.getMedicareNumber());
            basePatientDO1.setMobileRemarks(basePatientDO.getMobileRemarks());
            basePatientDO1.setBlood(basePatientDO.getBlood());
            basePatientDO1.setSsc(basePatientDO.getSsc());
            basePatientDO1.setCommitteeCode(basePatientDO.getCommitteeCode());
            basePatientDO1.setCommitteeName(basePatientDO.getCommitteeName());
            basePatientDO1.setArchiveType(basePatientDO.getArchiveType());
            basePatientDO1.setAddress(basePatientDO.getAddress());
            basePatientDO1.setPhoto(basePatientDO.getPhoto());
            basePatientDO1.setArchiveStatus(basePatientDO.getArchiveStatus());

            // 保存修改的居民信息
            this.save(basePatientDO1);
        }
        return ConstantUtils.SUCCESS;
    }

    /**
     * 修改居民
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String updatePatient(String jsonData) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        JSONObject patient = jsonObject.getJSONObject("patient");
        JSONArray patientMedicareCards = jsonObject.getJSONArray("medicareCard");
        if(null == patient || CollectionUtils.isEmpty(patientMedicareCards)){
            return ConstantUtils.FAIL;
        }
        BasePatientDO basePatientDO = objectMapper.readValue(patient.toJSONString(),BasePatientDO.class);
        if(StringUtils.isEmpty(basePatientDO.getId())){
            return ConstantUtils.FAIL;
        }
        BasePatientDO basePatientDO1 = basePatientDao.findById(basePatientDO.getId());
        if (null!=basePatientDO1){
            basePatientDO1.setName(basePatientDO.getName());
            basePatientDO1.setSex(basePatientDO.getSex());
            basePatientDO1.setIdcard(basePatientDO.getIdcard());
            basePatientDO1.setPhone(basePatientDO.getPhone());
            basePatientDO1.setProvinceCode(basePatientDO.getProvinceCode());
            basePatientDO1.setCityCode(basePatientDO.getCityCode());
            basePatientDO1.setTownCode(basePatientDO.getTownCode());
            basePatientDO1.setProvinceName(basePatientDO.getProvinceName());
            basePatientDO1.setTownName(basePatientDO.getTownName());
            basePatientDO1.setCityName(basePatientDO.getCityName());
            basePatientDO1.setMobile(basePatientDO.getMobile());
            basePatientDO1.setRemark(basePatientDO.getRemark());
            basePatientDO1.setLiveCityCode(basePatientDO.getLiveCityCode());
            basePatientDO1.setLiveCityName(basePatientDO.getLiveCityName());
            basePatientDO1.setLiveProvinceCode(basePatientDO.getLiveProvinceCode());
            basePatientDO1.setLiveProvinceName(basePatientDO.getLiveProvinceName());
            basePatientDO1.setLiveStreetCode(basePatientDO.getLiveStreetCode());
            basePatientDO1.setLiveStreetName(basePatientDO.getLiveStreetName());
            basePatientDO1.setLiveTownCode(basePatientDO.getLiveTownCode());
            basePatientDO1.setLiveTownName(basePatientDO.getLiveTownName());
            basePatientDO1.setAddress(basePatientDO.getAddress());
            basePatientDO1.setResidentialArea(basePatientDO.getResidentialArea());
            basePatientDO1.setCommitteeCode(basePatientDO.getCommitteeCode());
            basePatientDO1.setCommitteeName(basePatientDO.getCommitteeName());
            if(StringUtils.isNotBlank(basePatientDO.getYktId())){
                basePatientDO1.setYktId(basePatientDO.getYktId());
            }
            // 保存修改的居民信息
            basePatientDao.save(basePatientDO1);
        }

        Set<Object> cardIdList = basePatientMedicardCardService.findIdListByPatientCode(basePatientDO.getId());
        // 有些卡可能是新增或修改的，一条一条修改居民相关的卡的信息
        for (Object obj : patientMedicareCards) {
            PatientMedicareCardDO card = objectMapper.readValue(obj.toString(), PatientMedicareCardDO.class);
            card.setPatientCode(basePatientDO.getId());
            card.setDel("1");
            if(cardIdList.contains(card.getId())){
                cardIdList.remove(card.getId());
            }
            basePatientMedicardCardService.save(card);
        }
        // 有些卡可能是删除的
        if(cardIdList.size() > 0){
            basePatientMedicardCardService.delete(cardIdList.toArray());
        }
        return ConstantUtils.SUCCESS;
    }

    /**
     * 根据patient的id获取居民信息
     * @param patient
     * @return
     */
    public BasePatientDO findByIdAndDel(String patient) throws Exception{
        BasePatientDO basePatientDO = basePatientDao.findById(patient);
        if(basePatientDO==null){
            throw new Exception("用户不存在");
        }
        Boolean flag = healthCareService.isHospitalFlag();
        if (flag){
            String result = healthCareService.authorizedToEntrace(basePatientDO.getId());
            JSONObject object = JSONObject.parseObject(result);
            if (object.getString("flag").equalsIgnoreCase("1")){
                JSONObject encryptData = object.getJSONObject("encrypt_data");
                String state = encryptData.getString("state");
                String auth_date = encryptData.getString("auth_date");
                basePatientDO.setMedicalState(state);
                basePatientDO = basePatientDao.save(basePatientDO);
            }

        }
        return basePatientDO;
    }

    /**
     * 根据patient的id获取居民信息
     * @param mobile
     * @return
     */
    public BasePatientDO findByMobileAndDel(String mobile) throws Exception{
        List<BasePatientDO> list = basePatientDao.findByMobileAndDel(mobile,"1");
        if(list.size()<=0){
            return null;
        }
        return list.get(0);
    }

    public Boolean updatePatientPw(String id,String pw,String orgPw){
        BasePatientDO patientDO = basePatientDao.findOne(id);
        if (!"xm_ykyy_wx".equalsIgnoreCase(wxId)){
            String orgPwMd5 = MD5.md5Hex(orgPw + "{" + patientDO.getSalt() + "}");
            if(!orgPwMd5.equals(patientDO.getPassword())){
                return false;
            }
        }
        //认证信息设置
        if ("xm_ykyy_wx".equalsIgnoreCase(wxId)){
            String response =ykyyService.updatePatientPassword(patientDO.getMobile(),pw,"");
            if (StringUtils.isNoneBlank(response)&&response.contains("10000")){
                String salt = randomString(5);
                patientDO.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                patientDO.setSalt(salt);

                basePatientDao.save(patientDO);

                /*//设置更新时间
                saveDoctorPwlimitDate(id);*/
                return true;
            }
        }
        String salt = randomString(5);
        patientDO.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
        patientDO.setSalt(salt);

        basePatientDao.save(patientDO);

        /*//设置更新时间
        saveDoctorPwlimitDate(id);*/
        return true;
    }
    public Map<String,Object> getPatientCountByDoctor(String doctor,String patient) throws  Exception{
        List<WlyyOutpatientDO> fzList = outpatientDao.findByDoctorAndOutpatientType(doctor,"1",patient);
        List<WlyyOutpatientDO> xtList = outpatientDao.findByDoctorAndOutpatientType(doctor,"2",patient);
        List<WlyyOutpatientDO> zxList = outpatientDao.findByDoctorAndOutpatientType(doctor,"3",patient);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("fzNum",fzList==null?0:fzList.size());
        resultMap.put("xtNum",xtList==null?0:xtList.size());
        resultMap.put("zxNum",zxList==null?0:zxList.size());
        return resultMap;
    }
    //查询电子病历
        public MixEnvelop findEmrByPatientId(String patient,String doctor,Integer page ,Integer pageSize){
        String sql ="select e.id as \"id\"," +
                " e.prescription_id as \"prescriptionId\"," +
                " e.complaint as \"complaint\"," +
                " e.medical_history as \"medicalHistory\"," +
                " e.past_history as \"pastHistory\"," +
                " e.physical_examination as \"physicalExamination\"," +
                " e.assist_examination as \"assistExamination\"," +
                " p.doctor_name as \"doctorName\"," +
                " p.doctor as \"doctor\"," +
                " e.popular_history as \"popularHistory\"," +
                " e.special_history as \"specialHistory\"," +
                " e.create_time as \"createTime\"," +
                " e.allergic_history as \"allergicHistory\"" +
                " from wlyy_prescription_emr e " +
                " left join  wlyy_prescription p on e.prescription_id = p.id" +
                " where p.status >= 20";
        if (StringUtils.isNoneBlank(patient)){
            sql+=" and p.patient_code ='"+patient+"'";
        }
        if (StringUtils.isNoneBlank(doctor)){
            sql+=" and p.doctor ='"+doctor+"'";
        }
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql,page,pageSize);
        MixEnvelop mixEnvelop = new MixEnvelop();
        mixEnvelop.setTotalCount(list==null?0:list.size());
        mixEnvelop.setPageSize(pageSize);
        mixEnvelop.setCurrPage(page);
        mixEnvelop.setDetailModelList(list);
        return mixEnvelop;
    }
    //查询电子病历
   /* public MixEnvelop findPrescriptionByPatientAndDoctor(String patient,String doctor,Integer page ,Integer pageSize){
        String sql ="select p.id as \"id\"," +
                " p.outpatient_id as \"outpatient_id\"," +
                " p.real_order as \"real_order\"," +
                " p.origin_real_order as \"origin_real_order\"," +
                " p.adm_no as \"adm_no\"," +
                " p.origin_adm_no as \"origin_adm_no\"," +
                " p.serial_no as \"serial_no\"," +
                " p.origin_serial_no as \"origin_serial_no\"," +
                " p.type as \"type\"," +
                " p.patient_code as \"patient_code\"," +
                " p.patient_name as \"patient_name\"," +
                " p.status as \"status\"," +
                " p.mk_fail_reason as \"mk_fail_reason\"," +
                " p.idcard as \"idcard\"," +
                " p.idcard as \"idcard\"," +
                " p.idcard as \"idcard\"," +
                " p.idcard as \"idcard\"," +
                " p.idcard as \"idcard\"," +
                " p.idcard as \"idcard\"," +
                " p.idcard as \"idcard\"," +
                " p.idcard as \"idcard\"," +
                " p.idcard as \"idcard\"," +
                " p.idcard as \"idcard\"," +
                " p.ssc as \"ssc\"" +
                " from wlyy_prescription p " +
                " where p.status >= 20";
        if (StringUtils.isNoneBlank(patient)){
            sql+=" and p.patient_code ='"+patient+"'";
        }
        if (StringUtils.isNoneBlank(doctor)){
            sql+=" and p.doctor ='"+doctor+"'";
        }
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql,page,pageSize);
        MixEnvelop mixEnvelop = new MixEnvelop();
        mixEnvelop.setTotalCount(list==null?0:list.size());
        mixEnvelop.setPageSize(pageSize);
        mixEnvelop.setCurrPage(page);
        mixEnvelop.setDetailModelList(list);
        return mixEnvelop;
    }*/
    /**
     * 查询患者所有处方信息
     *
     * @param page
     * @param size
     * @return
     */
    public PageEnvelop findPatientAllPrescription(String doctor,String keyName, String status, Integer page, Integer size,String patient,String isSelectDrug) {
        BasePatientDO patientDO = basePatientDao.findById(patient);
        if (patientDO==null){
            return PageEnvelop.getError("找不到该患者",-1);
        }
        StringBuffer sql = new StringBuffer(" SELECT DISTINCT b.*, c.oneself_pickup_flg,f.job_title_code,f.job_title_name  FROM (SELECT a.* FROM wlyy_prescription a left join wlyy_outpatient o ON o.id=a.outpatient_id  WHERE o.consumer = '");
        StringBuffer countSql = new StringBuffer("select COUNT(DISTINCT b.id) count FROM (SELECT a.* FROM wlyy_prescription a left join wlyy_outpatient o ON o.id=a.outpatient_id  WHERE o.consumer = '");
        sql.append(patient).append("') b  LEFT JOIN wlyy_prescription_expressage c ON c.outpatient_id = b.outpatient_id LEFT JOIN base_doctor f ON b.doctor=f.id  ");
        countSql.append(patient).append("') b  LEFT JOIN wlyy_prescription_expressage c ON c.outpatient_id = b.outpatient_id LEFT JOIN base_doctor f ON b.doctor=f.id  ");
        if (StringUtils.isNoneBlank(isSelectDrug)){
            if("0".equalsIgnoreCase(isSelectDrug)){
                sql.append(" left join wlyy_inspection m on b.outpatient_id =m.outpatient_id");
                countSql.append(" left join wlyy_inspection m on b.outpatient_id =m.outpatient_id");
            }
            if ("1".equalsIgnoreCase(isSelectDrug)){
                sql.append(" left join wlyy_prescription_info m on b.id =m.prescription_id");
                countSql.append(" left join wlyy_prescription_info m on b.id =m.prescription_id");
            }
        }
        if (StringUtils.isNotEmpty(status)) {
            status = status.substring(1, status.length() - 1);
            if (StringUtils.isNoneBlank(isSelectDrug)){
                if("0".equalsIgnoreCase(isSelectDrug)){
                    sql.append(" where b.status IN( 9,").append(status).append(")");
                    countSql.append(" where b.status IN( 9,").append(status).append(")");
                }else {
                    sql.append(" where b.status IN(").append(status).append(")");
                    countSql.append(" where b.status IN(").append(status).append(")");
                }
            }else{
                sql.append(" where b.status IN(").append(status).append(")");
                countSql.append(" where b.status IN(").append(status).append(")");
            }
        } else {
            sql.append("  where b.status IN(20,21,30,31,32,100,101)");
            countSql.append(" where b.status IN(20,21,30,31,32,100,101) ");
        }
        if (StringUtils.isNoneBlank(isSelectDrug)){
            if("0".equalsIgnoreCase(isSelectDrug)){
                sql.append(" and m.del =1 ");
                countSql.append(" and m.del =1 ");
            }
            if ("1".equalsIgnoreCase(isSelectDrug)){
                sql.append(" and m.del =1");
                countSql.append(" and m.del =1");
            }
        }

        if (StringUtils.isNotEmpty(keyName)) {
            sql.append(" and (" +
                    " b.doctor_name LIKE '%" + keyName + "%' " +
                    " OR b.dept_name LIKE'%" + keyName + "%' " +
                    " OR b.hospital_name LIKE '%" + keyName + "%' " +
                    " OR m.drug_name LIKE '%" + keyName + "%' " +
                    " OR b.real_order LIKE '%" + keyName + "%' " +
                    ")");
            countSql.append(" and (" +
                    " b.doctor_name LIKE '%" + keyName + "%' " +
                    " OR b.dept_name LIKE'%" + keyName + "%' " +
                    " OR b.hospital_name LIKE '%" + keyName + "%' " +
                    " OR m.drug_name LIKE '%" + keyName + "%' " +
                    " OR b.real_order LIKE '%" + keyName + "%' " +
                    ")");
        }
        if (StringUtils.isNotEmpty(doctor)) {
            sql.append(" and  b.doctor ='" +doctor+"'");
            countSql.append(" and  b.doctor ='" +doctor+"'");
        }

        sql.append(" order by b.prescribe_time DESC ");

        List<WlyyPrescriptionVO> list = null;
        if ("xm_ykyy_wx".equalsIgnoreCase(wxId)) {
            String oracleSql = "SELECT\n" +
                    "\t*\n" +
                    "FROM\n" +
                    "\t(\n" +
                    "\t\tSELECT\n" +
                    "\t\t\tA .*\n" +
                    "\t\tFROM\n" +
                    "\t\t\t(";

            oracleSql += sql.toString();

            oracleSql += "\t\t\t) A\n" +
                    "\t\tWHERE\n" +
                    "  ROWNUM <=" + page * size +
                    "\t) \n" +
                    "WHERE\n" +
                    "\tROWNUM >= " + (page - 1) * size;
            if (flag){
                sql.append("  limit ").append((page - 1) * size).append(",").append(size);
                logger.info("MySql=" + sql.toString());
                list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(WlyyPrescriptionVO.class));
            }else {
                logger.info("oracleSql=" + oracleSql);
                list = jdbcTemplate.query(oracleSql, new BeanPropertyRowMapper<>(WlyyPrescriptionVO.class));
            }
        } else {
//            sql+=" LIMIT  " + (page - 1) * size + "," + size + "";
            sql.append("  limit ").append((page - 1) * size).append(",").append(size);
            logger.info("MySql=" + sql.toString());
            list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(WlyyPrescriptionVO.class));
        }
        for (WlyyPrescriptionVO singlePre:list){
            List<WlyyPrescriptionInfoDO> infoDOs = prescriptionInfoDao.findByPrescriptionId(singlePre.getId(),1);
            logger.info("singlePreId===="+singlePre.getId());
            logger.info("infoDOs"+infoDOs);
            List<WlyyPrescriptionInfoVO> infoVOS = new ArrayList<>();
            convertToModels(infoDOs, infoVOS, WlyyPrescriptionInfoVO.class);
            logger.info("infoVOS"+infoVOS);
            singlePre.setInfoVOs(infoVOS);
            List<WlyyInspectionDO> inspectionDOS = wlyyInspectionDao.findByPrescriptionId(singlePre.getId(),1);
            List<WlyyInspectionVO> inspectionVOS = new ArrayList<>();
            convertToModels(inspectionDOS, inspectionVOS, WlyyInspectionVO.class);
            //BeanUtils.copyProperties(inspectionDOS,inspectionVOS);
            singlePre.setInspectionVOs(inspectionVOS);
        }
//        List<WlyyPrescriptionVO> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(WlyyPrescriptionVO.class));
        logger.info("countSql=" + countSql.toString());
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(countSql.toString());
        long count = Long.parseLong(mapList.get(0).get("count").toString());
        return PageEnvelop.getSuccessListWithPage(IotRequestMapping.Common.message_success_find, list, page, size, count);
    }
    public Map<String,Object>  findPatientInfoById(String patientId,String doctor){
        String sql = "select b.id as \"id\"," +
                "  b.group_code as \"groupCode\"," +
                "  b.group_name as \"groupName\"" +
                "  from base_patient_group t " +
                " left join base_patient_group_dict b on t.group_id = b.id" +
                " where b.del = '1' and t.patient ='"+patientId+"' and t.doctor ='"+doctor+"'";
        sql+=" group by b.id,b.group_code,b.group_name";
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
        String patientSql= "select t.id as \"id\"," +
                " t.name as \"name\"," +
                " t.idcard as \"idcard\"," +
                " t.disease as \"disease\"" +
                "  from base_patient t where t.del = '1' and t.id='"+patientId+"'";
        List<Map<String,Object>> patientInfo = hibenateUtils.createSQLQuery(patientSql);
        if (patientInfo!=null&&patientInfo.size()>0){
            Map<String,Object> patient = patientInfo.get(0);
            String sex = IdCardUtil.getSexForIdcard_new(patient.get("idcard").toString());
            Integer age = IdCardUtil.getAgeForIdcard(patient.get("idcard").toString());
            patient.put("sex",sex);
            patient.put("age",age);
            patient.put("groupList",list);
            return patient;
        }
        return null;
    }

    public PageEnvelop pageByCondition(String name, Integer archiveType, Integer archiveStatus,int page,int size){
        List<Map<String ,Object>> list = new ArrayList<>();
        if (page>0){
            page--;
        }else{
            page=0;
        }
        String sqlCount = "select count(*) as \"total\" from base_patient where 1=1 ";
        String sql = "select * from base_patient where 1=1 ";
        String sqlCondition = "";
        if (StringUtils.isNotBlank(name)){
            sqlCondition += " and (name like '%"+name+"%' or idcard like '%"+name+"%' or mobile like '%"+name+"%') ";
        }
        if (archiveType!=null){
            sqlCondition += " and archive_type ="+archiveType;
        }
        if (archiveStatus!=null){
            sqlCondition += " and archive_status ="+archiveStatus;
        }
        List<Map<String ,Object>> count = hibenateUtils.createSQLQuery(sqlCount+sqlCondition);
        Long cou=0l;
        if (count!=null&&count.size()>0){
            cou= Long.valueOf(count.get(0).get("total").toString());
        }
        list = hibenateUtils.createSQLQuery(sql+sqlCondition,page,size);
        return PageEnvelop.getSuccessListWithPage("success",list,page,size,cou);
    }


}
