//package com.yihu.jw.doctor.service;
//
//import com.alibaba.fastjson.JSON;
//import com.yihu.jw.doctor.dict.BaseDoctorDao;
//import com.yihu.jw.doctor.dict.DoctorSpecialDiseaseDao;
//import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
//import com.yihu.jw.entity.base.doctor.DoctorSpecialDiseaseDo;
//import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
//import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
//import com.yihu.jw.restmodel.web.Envelop;
//import com.yihu.jw.restmodel.web.MixEnvelop;
//import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
//import com.yihu.jw.util.date.DateUtil;
//import com.yihu.jw.utils.hibernate.HibenateUtils;
//import com.yihu.mysql.query.BaseJpaService;
//import com.yihu.utils.security.MD5;
//import net.sf.json.JSONArray;
//import net.sf.json.JSONObject;
//import org.apache.commons.collections.map.HashedMap;
//import org.apache.commons.lang3.StringUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.core.StringRedisTemplate;
//import org.springframework.jdbc.core.JdbcTemplate;
//import org.springframework.stereotype.Service;
//
//import java.util.Date;
//import java.util.List;
//import java.util.Map;
//import java.util.Random;
//
//@Service
//public class BaseDoctorService extends BaseJpaService<BaseDoctorDO, BaseDoctorDao> {
//
//    private static Logger logger = LoggerFactory.getLogger(BaseDoctorService.class);
//
//
//    @Autowired
//    private BaseDoctorDao baseDoctorDao;
//    @Autowired
//    private DoctorSpecialDiseaseDao specialDiseaseDao;
//    @Autowired
//    private JdbcTemplate jdbcTemplate;
//    @Autowired
//    private HibenateUtils hibenateUtils;
//    @Autowired
//    private StringRedisTemplate redisTemplate;
//    @Autowired
//    private WlyyHospitalSysDictDao wlyyHospitalSysDictDao;
//
//
//    /**
//     * 查询医生信息分页列表.
//     * @param city
//     * @param hospital
//     * @param status
//     * @param name
//     * @param page
//     * @param pageSize
//     */
//    public Envelop queryList(String city, String hospital, String status, String name, String type,String typeCode,String dept, int page, int pageSize){
//        Map<String,Object> params = new HashedMap();
//        String sqlTotal ="SELECT " +
//                " COUNT(1) AS \"total\" " +
//                " FROM " +
//                " base_doctor a " +
//                " JOIN base_doctor_hospital b ON a.id = b.doctor_code " +
//                " LEFT JOIN (SELECT * FROM wlyy_charge_dict t WHERE t.dept_type_code ='6') e ON a.charge_type = e.charge_type " +
//                " LEFT JOIN base_doctor_mapping c ON a.id = c.doctor " +
//                " WHERE " +
//                " 1 = 1";
//        if (StringUtils.isNotBlank(city)){
//            sqlTotal += " AND a.city_name =:city";
//            params.put("city",city);
//        }
//        if (StringUtils.isNotBlank(hospital)){
//            sqlTotal += " AND b.org_code =:hospital";
//            params.put("hospital",hospital);
//        }
//        if (StringUtils.isNotBlank(status)){
//            sqlTotal += " AND a.del =:status";
//            params.put("status",status);
//        }
//        if (StringUtils.isNotBlank(name)){
//            name = "%"+name+"%";
//            sqlTotal += " AND (a.name like:name or b.dept_name like:name)";
//            params.put("name",name);
//        }
//        if (StringUtils.isNotBlank(type)){
//            type = "%"+type+"%";
//            sqlTotal += " AND a.outpatient_type like:type";
//            params.put("type",type);
//        }
//        if(StringUtils.isNotBlank(typeCode)){
//            sqlTotal += " AND e.dept_type_code =:typeCode";
//            params.put("typeCode",typeCode);
//        }
//        if(StringUtils.isNotBlank(dept)){
//            sqlTotal += " AND b.dept_code =:dept";
//            params.put("dept",dept);
//        }
//
//        Long count = 0L;
//        List<Map<String,Object>> total = hibenateUtils.createSQLQuery(sqlTotal,params);
//        if(count!=null){
//            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
//            count = hibenateUtils.objTransformLong(total.get(0).get("total"));
//        }
//        String sql ="SELECT " +
//                " a.id AS \"id\", " +
//                " a.NAME AS \"name\", " +
//                " a.introduce AS \"introduce\", " +
//                " a.expertise AS \"expertise\", " +
//                " a.outpatient_type AS \"outpatientType\", " +
//                " a.del AS \"del\", " +
//                " b.dept_name AS \"deptName\", " +
//                " e.req_fee AS \"money\" " +
//                " FROM " +
//                " base_doctor a " +
//                " JOIN base_doctor_hospital b ON a.id = b.doctor_code " +
//                " LEFT JOIN (SELECT * FROM wlyy_charge_dict t WHERE t.dept_type_code ='6') e ON a.charge_type = e.charge_type " +
//                " LEFT JOIN base_doctor_mapping c ON a.id = c.doctor " +
//                " WHERE 1=1";
//        if (StringUtils.isNotBlank(city)){
//            sql += " AND a.city_name =:city";
//        }
//        if (StringUtils.isNotBlank(hospital)){
//            sql += " AND b.org_code =:hospital";
//        }
//        if (StringUtils.isNotBlank(status)){
//            sql += " AND a.del =:status";
//        }
//        if (StringUtils.isNotBlank(name)){
//            sql += " AND (a.name like:name or b.dept_name like:name)";
//        }
//        if (StringUtils.isNotBlank(type)){
//            sql += " AND a.outpatient_type like:type";
//        }
//        if(StringUtils.isNotBlank(typeCode)){
//            sql += " AND e.dept_type_code =:typeCode";
//        }
//        if(StringUtils.isNotBlank(dept)){
//            sql += " AND b.dept_code =:dept";
//        }
//
//        logger.info("queryList sql:"+sql);
//
//        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,params,page,pageSize);
//
//        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, pageSize, count);
//    }
//
//    /**
//     * 根据医生ID，获取医生基础信息
//     * @param doctorId
//     * @return
//     */
//    public Object queryById(String doctorId,String typeCode) {
//        Map<String,Object> params = new HashedMap();
//        String sql ="SELECT " +
//                " a.NAME AS \"name\", " +
//                " a.job_title_name AS \"jobTitleName\", " +
//                " a.introduce AS \"introduce\", " +
//                " a.expertise AS \"expertise\", " +
//                " a.photo AS \"photo\", " +
//                " a.outpatient_type AS \"outpatientType\", " +
//                " b.dept_name AS \"deptName\", " +
//                " b.org_name AS \"orgName\", " +
//                " c.mapping_code AS \"jobNumber\", " +
//                " d.disease_name AS \"diseaseName\", " +
//                " d.disease_code AS \"diseaseCode\", " +
//                " e.req_fee AS \"money\" " +
//                " FROM " +
//                " base_doctor a " +
//                " LEFT JOIN base_doctor_hospital b ON a.id = b.doctor_code " +
//                " LEFT JOIN base_doctor_mapping c ON a.id = c.doctor " +
//                " LEFT JOIN wlyy_doctor_special_disease d ON a.id = d.doctor_code " +
//                " LEFT JOIN wlyy_charge_dict e ON a.charge_type = e.charge_type " +
//                " WHERE 1=1 ";
//        if(StringUtils.isNotBlank(doctorId)){
//            sql+=" AND a.id =:id";
//            params.put("id",doctorId);
//        }
//        if(StringUtils.isNotBlank(typeCode)){
//            sql+=" AND e.dept_type_code =:typeCode";
//            params.put("typeCode",typeCode);
//        }
//
//        logger.info("queryById sql:"+sql);
//
//        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql, params);
//        StringBuilder disease = new StringBuilder();
//        StringBuilder code = new StringBuilder();
//        if (null != list && list.size() > 0){
//            if (list.size() == 1){
//                return  list.get(0);
//            }else {
//                for (int i=0;i<list.size();i++){
//                    if (i == 0 ){
//                        disease.append(list.get(i).get("diseaseName"));
//                        code.append(list.get(i).get("diseaseCode"));
//                    }else {
//                        disease.append(","+list.get(i).get("diseaseName"));
//                        code.append(","+list.get(i).get("diseaseCode"));
//                    }
//                }
//                list.get(0).put("diseaseName",disease);
//                list.get(0).put("diseaseCode",code);
//                return  list.get(0);
//            }
//        }
//
//        return null;
//    }
//
//    public Boolean updateList(JSONArray jsonArray){
//        if(jsonArray!=null&&jsonArray.size()>0){
//            for(int i=0;i<jsonArray.size();i++){
//                JSONObject doctor = jsonArray.getJSONObject(i);
//                try {
//                    updateInfo(doctor);
//                }catch (Exception e){
//                    logger.info("update doctor error:"+e.toString());
//                }
//            }
//        }
//        return true;
//    }
//
//    /**
//     * 修改医生服务配置
//     * @param jsonObject
//     */
//    public Boolean update(JSONObject jsonObject)throws Exception{
//        //取出数据
//        String doctorId = jsonObject.get("doctorId").toString();
//        String introduce = jsonObject.get("introduce").toString();
//        String expertise = jsonObject.get("expertise").toString();
//        String photo = jsonObject.get("photo").toString();
//        String outpatientType = jsonObject.get("outpatientType").toString();
//        String newSpecialDisease = jsonObject.get("specialDisease").toString();
//        String newSpecialDiseaseCode = jsonObject.get("specialDiseaseCode").toString();
//        baseDoctorDao.update(doctorId,introduce,expertise,photo,outpatientType);
//        //删除医生旧专病门诊，保存新专病门诊
//        Map<String,Object> params = new HashedMap();
//        String sqlTotal ="SELECT " +
//                " COUNT(1) AS \"total\" " +
//                " FROM " +
//                " wlyy_doctor_special_disease a " +
//                " WHERE " +
//                " 1 = 1";
//        sqlTotal += " AND a.doctor_code =:doctorId";
//        params.put("doctorId",doctorId);
//        Long count = 0L;
//        List<Map<String, Object>> total = hibenateUtils.createSQLQuery(sqlTotal, params);
//        //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
//        count = hibenateUtils.objTransformLong(total.get(0).get("total"));
//        if (count > 0){
//            specialDiseaseDao.deleteByDoctorCode(doctorId);
//        }
//        if(StringUtils.isNotBlank(newSpecialDisease) && StringUtils.isNotBlank(newSpecialDiseaseCode)){
//            String[] split = newSpecialDisease.split(",");
//            String[] splitCode = newSpecialDiseaseCode.split(",");
//            specialDiseaseDao.deleteByDoctorCode(doctorId);
//            for (int i=0;i<split.length;i++ ){
//                DoctorSpecialDiseaseDo specialDiseaseDo = new DoctorSpecialDiseaseDo();
//                specialDiseaseDo.setDoctorCode(doctorId);
//                specialDiseaseDo.setDiseaseName(split[i]);
//                specialDiseaseDo.setDiseaseCode(splitCode[i]);
//                specialDiseaseDao.save(specialDiseaseDo);
//            }
//        }
//
//        return true;
//    }
//
//    public Boolean updateInfo(JSONObject jsonObject)throws Exception{
//        //取出数据
//        String doctorId = jsonObject.get("doctorId").toString();
//        String outpatientType = jsonObject.get("outpatientType").toString();
//        logger.info("doctor:"+doctorId+" outpatientType:"+outpatientType);
//        BaseDoctorDO doctorDO = baseDoctorDao.findOne(doctorId);
//        doctorDO.setOutpatientType(outpatientType);
//        baseDoctorDao.save(doctorDO);
//        return true;
//    }
//
//
//    /**
//     * 修改医生状态
//     * @param doctorId
//     * @param status
//     */
//    public void updateStatus(String doctorId,String status)throws Exception{
//        baseDoctorDao.updateStatus(doctorId,status);
//    }
//
//    public Boolean updateDoctorPw(String id,String pw,String orgPw){
//        BaseDoctorDO doctorDO = baseDoctorDao.findOne(id);
//
//        String orgPwMd5 = MD5.md5Hex(orgPw + "{" + doctorDO.getSalt() + "}");
//        if(!orgPwMd5.equals(doctorDO.getPassword())){
//            return false;
//        }
//        //认证信息设置
//        String salt = randomString(5);
//        doctorDO.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
//        doctorDO.setSalt(salt);
//
//        baseDoctorDao.save(doctorDO);
//
//        //设置更新时间
//        saveDoctorPwlimitDate(id);
//
//        return true;
//    }
//
//    public String randomString(int length) {
//        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
//        StringBuffer buffer = new StringBuffer();
//        Random random = new Random();
//
//        for(int i = 0; i < length; ++i) {
//            int pos = random.nextInt(str.length());
//            buffer.append(str.charAt(pos));
//        }
//
//        return buffer.toString();
//    }
//
//    public com.alibaba.fastjson.JSONObject findDoctorPwlimitDate(String doctor){
//        String key = "hlwyy:authPw:doctor:" + doctor;
//        String authPw = redisTemplate.opsForValue().get(key);
//        com.alibaba.fastjson.JSONObject valueJson = null;
//        if(StringUtils.isNotBlank(authPw)){
//
//            WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("pwOverDue");
//            String code[] = wlyyHospitalSysDictDO.getDictCode().split(",");
//            Integer maxDateInt = Integer.parseInt(code[0]);
//            Integer remainDateInt = Integer.parseInt(code[1]);
//
//            valueJson = JSON.parseObject(authPw);
//            Long updateTimeLong = valueJson.getLong("updateTime");
//            Date updateTime = new Date();
//            updateTime.setTime(updateTimeLong);
//            Date maxDate = DateUtil.getPreDays(updateTime,maxDateInt);
//
//            Long betweenDate = (maxDate.getTime() - new Date().getTime())/(60*60*24*1000);
//            valueJson.put("betweenDate",betweenDate);
//            if(betweenDate<remainDateInt){
//                valueJson.put("remaind",true);
//            }else {
//                valueJson.put("remaind",false);
//            }
//        }else {
//            valueJson = new com.alibaba.fastjson.JSONObject();
//            valueJson.put("isChanged",false);
//        }
//        return valueJson;
//    }
//
//    public boolean saveDoctorPwlimitDate(String doctor){
//        String key = "hlwyy:authPw:doctor:" + doctor;
//        com.alibaba.fastjson.JSONObject valueJson = new com.alibaba.fastjson.JSONObject();
//        valueJson.put("updateTime",new Date().getTime());
//        valueJson.put("isChanged",true);
//        redisTemplate.opsForValue().set(key,valueJson.toJSONString());
//        return true;
//    }
//
//
//
//
////    public static void main(String ag[]){
////        long betweenDate = (DateUtil.strToDate("2020-04-11","yyyy-MM-dd").getTime() - new Date().getTime())/(60*60*24*1000);
////        System.out.println(betweenDate);
////    }
//
////    public static void main(String ag[]){
////        String str = "[ " +
////                "{ " +
////                "\"title\":\"Java 开发\", " +
////                "\"edition\":3, " +
////                "\"author\":[\"smith\",\"张三\",\"李四\"] " +
////                "}, " +
////                "{ " +
////                "\"title\":\"Web 开发\", " +
////                "\"edition\":3, " +
////                "\"author\":[\"Allen\",\"王五\",\"赵六\"] " +
////                "} " +
////                "]";
////        JSONArray json = JSONArray.fromObject(str);
////        for(int i=0;i<json.size();i++){
////            JSONObject doctor = json.getJSONObject(i);
////            doctor.getString("doctor");
////        }
////    }
//}