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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.base.dao.dict.DictJobTitleDao;
import com.yihu.jw.base.dao.doctor.BaseDoctorIncentiveDao;
import com.yihu.jw.base.dao.team.BaseTeamDao;
import com.yihu.jw.base.dao.team.BaseTeamMemberDao;
import com.yihu.jw.base.service.dict.DictDoctorDutyService;
import com.yihu.jw.base.service.doctor.excelImport.BaseDoctorExcelDO;
import com.yihu.jw.base.service.org.OrgTree;
import com.yihu.jw.base.service.org.OrgTreeService;
import com.yihu.jw.base.service.util.YkyyBaseService;
import com.yihu.jw.base.util.ConstantUtils;
import com.yihu.jw.base.util.JavaBeanUtils;
import com.yihu.jw.dict.dao.DictDoctorDutyDao;
import com.yihu.jw.dict.dao.DictHospitalDeptDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.doctor.dao.BaseDoctorRoleDao;
import com.yihu.jw.entity.base.dict.BaseIncentiveDictDO;
import com.yihu.jw.entity.base.dict.DictDoctorDutyDO;
import com.yihu.jw.entity.base.dict.DictHospitalDeptDO;
import com.yihu.jw.entity.base.dict.DictJobTitleDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorIncentiveDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorRoleDO;
import com.yihu.jw.entity.base.org.BaseOrgDO;
import com.yihu.jw.entity.base.team.BaseTeamDO;
import com.yihu.jw.entity.base.team.BaseTeamMemberDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.mapping.DoctorMappingDO;
import com.yihu.jw.exception.business.ManageException;
import com.yihu.jw.hospital.dict.BaseIncentiveDictDao;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.mapping.dao.DoctorMappingDao;
import com.yihu.jw.hospital.prescription.service.entrance.EntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.XzzxEntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.YkyyEntranceService;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.utils.security.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

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

/**
 * 
 * 医生基础信息服务service
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * litaohong    1.0  2018年08月31日 Created
 *
 * </pre>
 * @since 1.
 */
@Service
public class BaseDoctorService extends BaseJpaService<BaseDoctorDO, BaseDoctorDao> {

    @Autowired
    private BaseDoctorDao baseDoctorDao;

    @Autowired
    private BaseDoctorHospitalService baseDoctorHospitalService;

    @Autowired
    private BaseDoctorRoleService baseDoctorRoleService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private BaseOrgDao baseOrgDao;
    @Autowired
    private DictHospitalDeptDao deptDao;
    @Autowired
    private DictDoctorDutyDao dutyDao;
    @Autowired
    private BaseDoctorHospitalDao doctorHospitalDao;
    @Autowired
    private DictJobTitleDao jobTitleDao;

    @Autowired
    private OrgTreeService orgTreeService;
    @Autowired
    private BaseDoctorRoleDictService baseDoctorRoleDictService;

    @Autowired
    private DictDoctorDutyService dictDoctorDutyService;
    @Autowired
    private DictHospitalDeptDao dictHospitalDeptDao;
    @Autowired
    private BaseDoctorHospitalDao baseDoctorHospitalDao;
    @Autowired
    private XzzxEntranceService xzzxEntranceService;
    @Autowired
    private EntranceService entranceService;
    @Autowired
    private YkyyEntranceService ykyyEntranceService;
    @Autowired
    private DoctorMappingDao doctorMappingDao;
    @Autowired
    private BaseDoctorIncentiveDao baseDoctorIncentiveDao;
    @Autowired
    private BaseIncentiveDictDao baseIncentiveDictDao;
    @Autowired
    private BaseTeamMemberDao baseTeamMemberDao;
    @Autowired
    private YkyyBaseService ykyyService;

    @Value("${wechat.flag}")
    private boolean flag;
    @Value("${wechat.id}")
    private String  wxId;
    public static String entranceUrl = "http://172.16.100.240:10023/xzzx/";
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private BaseDoctorRoleDao baseDoctorRoleDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private WlyyHospitalSysDictDao wlyyHospitalSysDictDao;
    @Autowired
    private BaseTeamDao baseTeamDao;


    /**
     * 获取医生信息
     * @param doctorId 医生id
     * @return
     */
    public JSONObject getOneDoctorInfo(String doctorId) throws Exception{
        JSONObject result = new JSONObject();
        if(StringUtils.isEmpty(doctorId)){
            result.put("msg","parameter doctorId is null ");
            result.put("response",ConstantUtils.FAIL);
            return result;
        }

        //医生基本信息
        BaseDoctorDO doctors = baseDoctorDao.findOne(doctorId);
        if(null == doctors){
            result.put("msg","医生不存在:" + doctorId);
            result.put("response",ConstantUtils.FAIL);
            return result;
        }
        List<WlyyHospitalSysDictDO> list = wlyyHospitalSysDictDao.findByDictName("doctor_level");
        for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:list){
            if (doctors.getLevel().equals(wlyyHospitalSysDictDO.getDictCode())){
                doctors.setLevelName(wlyyHospitalSysDictDO.getDictValue());
            }
        }
        //医生归属业务模块角色信息，非必填，数据可有可没有
        String[] paramNames = {"doctorCode"};
        Object[] paramValue = {doctorId};
        JSONObject jsonObject = new JSONObject();
        List<BaseTeamMemberDO> baseTeamMemberDO = baseTeamMemberDao.findUseDoctorCode(doctorId);
        List<BaseTeamDO> teamlist = new ArrayList<>();
        if (baseTeamMemberDO!=null&&baseTeamMemberDO.size()>0){
            for (BaseTeamMemberDO baseTeamMemberDO1:baseTeamMemberDO){
                String teamCode = baseTeamMemberDO1.getTeamCode();
                BaseTeamDO baseTeamDO = baseTeamDao.findOne(teamCode);
                teamlist.add(baseTeamDO);
            }
            jsonObject.put("teamInfo",teamlist);
        }
        List<BaseDoctorRoleDO> roleList = baseDoctorRoleService.findByFields(paramNames,paramValue);
        jsonObject.put("doctor",doctors);
        jsonObject.put("role",roleList);
        List<BaseDoctorHospitalDO> baseDoctorHospitalDO = baseDoctorHospitalDao.findByDoctorCode(doctorId);
        jsonObject.put("hospital",baseDoctorHospitalDO);
        result.put("response",ConstantUtils.SUCCESS);
        result.put("msg",jsonObject);
        return result;
    }

    /**
     * 获取医生信息（包括医生任职的医院相关信息）
     * @param nameOrIdcard
     * @param orgCode
     * @param docStatus
     * @return
     */
    public JSONObject queryDoctorListFullInfo(String nameOrIdcard, String orgCode, String docStatus, int page, int size,String wechatId) throws Exception {
        JSONObject result = new JSONObject();
        String orgCodeVale = null == orgCode ? "" : orgCode;
        String del = null == docStatus ? "" : docStatus;
        String nameOrIdcardValue = null == nameOrIdcard ? "" : "%" + nameOrIdcard + "%";
        int start = 0 == page ? page++ : (page - 1) * size;
        int end = 0 == size ? 15 : page * size;
//        String sql = "select" +
//                "  tb.id as id," +
//                "  tb.name as name," +
//                "  tb.idcard as idcard,  " +
//                "  tb.sex as sex,  " +
//                "  tb.mobile as mobile,  " +
//                "  GROUP_CONCAT(tb.org SEPARATOR ',') as orgInfo,  " +
//                "  tb.job_title_name as jobTitleName,  " +
//                "  tb.status as status " +
//                "from  " +
//                "  (  " +
//                "    select  " +
//                "     doc.id,  " +
//                "     doc.name,  " +
//                "     doc.idcard,  " +
//                "     case doc.sex when 1 then '男' when 2 then '女' else '未知' end as sex,  " +
//                "     doc.mobile,  " +
//                "     concat(hos.org_name,'/',dept.name,'/',hos.doctor_duty_name) as org,  " +
//                "     doc.job_title_name,  " +
//                "     case doc.del when 0 then '已失效' when 1 then '生效中' end as status,  " +
//                "      doc.create_time  " +
//                "   from  " +
//                "     base_doctor doc,  " +
//                "     base_doctor_hospital hos,  " +
//                "     dict_hospital_dept dept  " +
//                "  where  " +
//                "    doc.id = hos.doctor_code  " +
//                "    and  " +
//                "    hos.org_code = dept.org_code " +
//                "    and " +
//                "    hos.dept_code = dept.code  " +
//                "    and  " +
//                "    ((doc.idcard like '{idcard}' or ''= '{idcard}' ) or (doc.name like '{name}'  or ''= '{name}' )  and (hos.org_code = '{orgCode}' or ''= '{orgCode}') and (doc.del = '{docStatus}' or ''= '{docStatus}'))  " +
//                "  ) tb  " +
//                "GROUP BY tb.id order by tb.create_time desc limit {start},{end} ";
//        String finalSql = sql
//                .replace("{idcard}",nameOrIdcardValue)
//                .replace("{name}",nameOrIdcardValue)
//                .replace("{orgCode}",orgCodeVale)
//                .replace("{docStatus}",del)
//                .replace("{start}",String.valueOf(start))
//                .replace("{end}",String.valueOf(end));

        String sql="SELECT\n" +
                "\ttb.id AS \"id\",\n" +
                "\ttb.idcard AS \"idcard\",\n" +
                "\ttb.name AS \"name\",\n" +
                "\ttb.sex AS \"sex\",\n" +
                "\ttb.orgName AS \"orgName\",\n" +
                "\ttb.deptname AS \"deptname\",\n" +
                "\ttb.doctorDutyName AS \"doctorDutyName\",\n" +
                "\ttb.doctor_level AS \"doctorLevel\",\n" +
                "\ttb.mobile AS \"mobile\",";
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
            if (flag){
                sql+=" GROUP_CONCAT(tb.org SEPARATOR ',') AS orgInfo,";
            }else {
                sql+="  wm_concat (tb.org || ',') AS \"orgInfo\",";
            }

        }else {
            sql+=" GROUP_CONCAT(tb.org SEPARATOR ',') AS orgInfo,";
        }
        sql+="tb.job_title_name AS \"jobTitleName\",\n" +
                "\ttb.status AS \"status\",\n" +
                "  tb.create_time AS \"createtime\"\n" +
                "FROM\n" +
                "\t(\n" +
                "\t\tSELECT\n" +
                "\t\t\tdoc.id,\n" +
                "\t\t\tdoc.name,\n" +
                "\t\t\tdoc.idcard,\n" +
                "\t\t\tCASE\n" +
                "\t\tWHEN doc.sex = 1 THEN\n" +
                "\t\t\t'男'\n" +
                "\t\tWHEN doc.sex = 2 THEN\n" +
                "\t\t\t'女'\n" +
                "\t\tELSE\n" +
                "\t\t\t'未知'\n" +
                "\t\tEND AS sex,\n" +
                "\t\tdoc.mobile,\n" +
                "\t\tdoc.doctor_level,\n" +
                "\t\thos.org_name || '/' || dept. NAME || '/' || hos.doctor_duty_name AS org,\n" +
                "\t\thos.org_name as orgName,\n" +
                "\t\tdept.NAME as deptname,\n" +
                "\t\thos.doctor_duty_name as doctorDutyName,\n" +
                "\t\tdoc.job_title_name,\n" +
                "\t\tCASE\n" +
                "\tWHEN doc.del = 0 THEN\n" +
                "\t\t'已失效'\n" +
                "\tWHEN doc.del = 1 THEN\n" +
                "\t\t'生效中'\n" +
                "\tEND AS status,\n" +
                "\tdoc.create_time\n" +
                "FROM\n" +
                " base_doctor doc LEFT join base_doctor_hospital hos on doc.id = hos.doctor_code " +
                " LEFT JOIN dict_hospital_dept dept on hos.org_code = dept.org_code" +
                " AND hos.dept_code = dept.code"+
                /*"\tbase_doctor doc,\n" +
                "\tbase_doctor_hospital hos,\n" +
                "\tdict_hospital_dept dept\n" +*/
                " WHERE 1=1";
                /*"\tdoc.id = hos.doctor_code\n" +
                "AND hos.org_code = dept.org_code\n" +
                "AND hos.dept_code = dept.code\n"*/
        if (!StringUtils.isEmpty(nameOrIdcard)){
            sql += " and (doc.idcard LIKE '%"+nameOrIdcard+"%' or doc.name LIKE '%"+nameOrIdcard+"%')";
        }if (!StringUtils.isEmpty(orgCode)){
            sql += " and hos.org_code = '"+orgCode+"'";
        }
        if (!StringUtils.isEmpty(del)){
            sql += " and doc.del  = '"+del+"'";
        }
                sql+="\t) tb" +
                "  GROUP BY\n" +
                "\ttb. ID,\n" +
                "\ttb.idcard,\n" + "\ttb.doctor_level,\n" +
                "\ttb.name,\n" +
                "\ttb.sex,\n" +
                "\ttb.mobile,\n" +
                "\ttb.job_title_name,\n" +
                "\ttb.status,\n" +"\ttb.orgName,\n" +"\ttb.deptname,\n" +"\ttb.doctorDutyName,\n" +
                "  tb.create_time\n" +
                "ORDER BY\n" +
                "\ttb.create_time DESC";

//        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
//            sql+=" GROUP BY\n" +
//                    "\ttb. ID,\n" +
//                    "\ttb.idcard,\n" +
//                    "\ttb. NAME,\n" +
//                    "\ttb.sex,\n" +
//                    "\ttb.mobile,\n" +
//                    "\ttb.job_title_name,\n" +
//                    "\ttb.status,\n" +
//                    "  tb.create_time\n" +
//                    "ORDER BY\n" +
//                    "\ttb.create_time DESC";
//        }else {
//            sql+=" GROUP BY\n" +
//                    "\ttb. ID\n" +
//                    "ORDER BY\n" +
//                    "\ttb.create_time DESC";
//        }



        List<Map<String,Object>> list=null;
        list = hibenateUtils.createSQLQuery(sql,page,size);
       /* if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){

            if (flag){
                sql+=" LIMIT  " + (page - 1) * size + "," + size + "";
                Logger.getAnonymousLogger().info("finalCountSql="+sql);
                list = jdbcTemplate.queryForList(sql);
            }else {
                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;

                oracleSql+="\t\t\t) A\n" +
                        "\t\tWHERE\n" +
                        "  ROWNUM <="+page*size +
                        "\t) \n" +
                        "WHERE\n" +
                        "\tROWNUM >= "+(page-1)*size;
                Logger.getAnonymousLogger().info("oracleSql="+oracleSql);
                list = jdbcTemplate.queryForList(oracleSql);
            }


        }else {
            sql+=" LIMIT  " + (page - 1) * size + "," + size + "";
            Logger.getAnonymousLogger().info("finalCountSql="+sql);
            list = jdbcTemplate.queryForList(sql);
        }*/


        String countSql = " select " +
                "     COUNT(DISTINCT (doc.id)) as count " +
                "   from " +
                "     base_doctor doc, " +
                "     base_doctor_hospital hos, " +
                "     dict_hospital_dept dept " +
                "  where " +
                "    doc.id = hos.doctor_code " +
                "    and " +
                "    hos.org_code = dept.org_code " +
                "    and " +
                "    hos.dept_code = dept.code " ;
        if (!StringUtils.isEmpty(nameOrIdcard)){
            countSql += " and (doc.idcard LIKE '%"+nameOrIdcard+"%' or doc.name LIKE '%"+nameOrIdcard+"%')";
        }if (!StringUtils.isEmpty(orgCode)){
            countSql += " and hos.org_code = '"+orgCode+"'";
        }
        if (!StringUtils.isEmpty(del)){
            countSql += " and doc.del  = '"+del+"'";
        }

//        List<Map<String,Object>> list = jdbcTemplate.queryForList(finalSql);
        Logger.getAnonymousLogger().info("finalCountSql="+countSql);
        int count = jdbcTemplate.queryForObject(countSql,Integer.class);
        List<WlyyHospitalSysDictDO> listDict = wlyyHospitalSysDictDao.findByDictName("doctor_level");
        for (Map<String,Object> map:list){
            String orgname = map.get("orgName")==null?"":map.get("orgName").toString();
            String deptname = map.get("deptname")==null?"":map.get("deptname").toString();
            String doctorDutyName = map.get("doctorDutyName")==null?"":map.get("doctorDutyName").toString();
            map.put("orgInfo",orgname+"/"+deptname+"/"+doctorDutyName);
            /*for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:listDict){
                if (map.get("doctorlevel").toString().equals(wlyyHospitalSysDictDO.getDictCode())){
                    map.put("levelName",wlyyHospitalSysDictDO.getDictValue());
                }
            }*/
        }
        result.put("count", count);
        result.put("msg", JavaBeanUtils.getInstance().mapListJson(list));
        return result;
    }

    /**
     * 新增医生
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String createDoctor(String jsonData) {
        JSONObject result = new JSONObject();
        if (StringUtils.isEmpty(jsonData)) {
            result.put("msg", "jsonData is null");
            result.put("response", ConstantUtils.FAIL);
            return result.toJSONString();
        }
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        JSONObject doctor = jsonObject.getJSONObject("doctor");
        JSONArray role = jsonObject.getJSONArray("role");
        String teamCode = jsonObject.getString("teamCode");
        JSONArray hospital = jsonObject.getJSONArray("hospital");
        String doctorMappingCode = jsonObject.getString("doctorMappingCode");
        if (null == doctor) {
            result.put("msg", "医生信息不可为空！");
            result.put("response", ConstantUtils.FAIL);
            return result.toJSONString();
        }
        //组装医生信息
        BaseDoctorDO baseDoctorDO = null;
        BaseDoctorDO baseDoctorvo = null;
        String orgCode = "";
        DoctorMappingDO doctorMappingDO = null;
        try {
            baseDoctorvo = objectMapper.readValue(doctor.toJSONString(), BaseDoctorDO.class);
            baseDoctorDO =  baseDoctorDao.findByIdcardAndDel(baseDoctorvo.getIdcard());
            if (null==baseDoctorDO){
                baseDoctorvo.setSalt(randomString(5));
                baseDoctorvo.setEnabled(1);
                baseDoctorvo.setLocked(0);
                baseDoctorvo.setChargeType("12");
                baseDoctorvo.setBirthday(IdCardUtil.getBirthdayForIdcard(baseDoctorvo.getIdcard()));
                baseDoctorvo.setPassword(MD5.md5Hex(baseDoctorvo.getIdcard().substring(12, 18) + "{" + baseDoctorvo.getSalt() + "}"));
                baseDoctorDO = baseDoctorDao.save(baseDoctorvo);
                if ("xm_zsyy_wx".equalsIgnoreCase(wxId)){

                }else if("xm_xzzx_wx".equalsIgnoreCase(wxId)){
                    String url = entranceUrl+"selectDoctorInfo?idCard="+baseDoctorDO.getIdcard();
                    String response = httpClientUtil.get(url,"GBK");
                    JSONObject object = JSONObject.parseObject(response);
                    String mappingCode = "";
                    if(object.getInteger("status")==200){
                        String obj = object.getString("obj");
                        JSONArray array = JSONArray.parseArray(obj);
                        if (array!=null&&array.size()!=0){
                            JSONObject jsonObjectDoctor = array.getJSONObject(0);
                            mappingCode = jsonObjectDoctor.getString("code");
                        }else {

                        }
                    }
                    doctorMappingDO = doctorMappingDao.findByDoctor(baseDoctorDO.getId());
                    if (null==doctorMappingDO){
                        doctorMappingDO = new DoctorMappingDO();
                        doctorMappingDO.setMappingCode(mappingCode);
                        doctorMappingDO.setDoctor(baseDoctorDO.getId());
                        doctorMappingDO.setDoctorName(baseDoctorDO.getName());
                        doctorMappingDO.setIdcard(baseDoctorDO.getId());
                        doctorMappingDO.setOrgCode("350211A5010");
                        doctorMappingDO.setOrgName("厦门大学附属心血管病医院");
                        doctorMappingDO.setCreateTime(new Date());
                        doctorMappingDao.save(doctorMappingDO);
                    }
                }
                if (!StringUtils.isEmpty(doctorMappingCode)){
                    doctorMappingDO = doctorMappingDao.findByIdcard(baseDoctorvo.getIdcard());
                    if (doctorMappingDO==null){
                        doctorMappingDO = new DoctorMappingDO();
                    }
                    doctorMappingDO.setMappingCode(doctorMappingCode);
                    doctorMappingDO.setDoctor(baseDoctorDO.getId());
                    doctorMappingDO.setDoctorName(baseDoctorDO.getName());
                    doctorMappingDO.setIdcard(baseDoctorDO.getId());
                    doctorMappingDO.setCreateTime(new Date());
                    doctorMappingDO= doctorMappingDao.save(doctorMappingDO);
                }
            }
        } catch (IOException e) {
            result.put("msg", "convert doctor jsonObject to BaseDoctorDO failed," + e.getCause());
            result.put("response", ConstantUtils.FAIL);
            return result.toJSONString();
        } catch (Exception e) {
            result.put("msg", "convert doctor birth failed," + e.getCause());
            result.put("response", ConstantUtils.FAIL);
            return result.toJSONString();
        }
        //组装医生角色关联关系,医生默认可以没有角色，没有机构/部门信息等
        if (!CollectionUtils.isEmpty(role)) {
            BaseDoctorRoleDO baseDoctorRoleDO = null;
            List<BaseDoctorRoleDO> baseDoctorRoleDOList = new ArrayList<>();
            List<BaseDoctorRoleDO> list = baseDoctorRoleDao.findByDoctorCode(baseDoctorDO.getId());
            if (list!=null&&list.size()>0){
                for (BaseDoctorRoleDO baseDoctorRoleDO2 : list){
                    baseDoctorRoleDao.delete(baseDoctorRoleDO2.getId());
                }
            }
            try {
                for (Object object : role) {
                    baseDoctorRoleDO = objectMapper.readValue(object.toString(), BaseDoctorRoleDO.class);
                    BaseDoctorRoleDO baseDoctorRoleDO1 = baseDoctorRoleDao.findByDoctorCodeAndroleCode(baseDoctorDO.getId(),baseDoctorRoleDO.getRoleCode());
                    if (null==baseDoctorRoleDO1){
                        baseDoctorRoleDO.setDoctorCode(baseDoctorDO.getId());
                        baseDoctorRoleDao.save(baseDoctorRoleDO);
                    }
                }
            } catch (IOException e) {
                result.put("msg", "convert hospital jsonObject to baseDoctorHospitalDO failed," + e.getCause());
                result.put("response", ConstantUtils.FAIL);
                return result.toJSONString();
            }
        }

        // 组装医生任职机构及职业信息,医生默认可以没有角色，没有机构/部门信息等
        if (!CollectionUtils.isEmpty(hospital)) {
            BaseDoctorHospitalDO baseDoctorHospitalDO = null;
            List<BaseDoctorHospitalDO> hospitalDOList = new ArrayList<>();
            String orgName = "";
            try {
                for (Object object : hospital) {
                    baseDoctorHospitalDO = objectMapper.readValue(object.toString(), BaseDoctorHospitalDO.class);
                    BaseDoctorHospitalDO baseDoctorHospitalDO1 =  baseDoctorHospitalDao.findByOrgCodeAndDeptCodeAndDoctorCodeOnly(baseDoctorHospitalDO.getOrgCode(),baseDoctorHospitalDO.getDeptCode(),baseDoctorDO.getId());
                    if (baseDoctorHospitalDO1 == null) {
                        baseDoctorHospitalDO.setDoctorCode(baseDoctorDO.getId());
                        baseDoctorHospitalDO.setDel("1");
                        baseDoctorHospitalDO.setCreateTime(new Date());
                        DictHospitalDeptDO dictHospitalDeptDO = dictHospitalDeptDao.findByCode(baseDoctorHospitalDO.getDeptCode());
                        if (null!=dictHospitalDeptDO){
                            baseDoctorHospitalDO.setDeptName(dictHospitalDeptDO.getName());
                        }
                        orgCode = baseDoctorHospitalDO.getOrgCode();
                        orgName = baseDoctorHospitalDO.getOrgName();
                        baseDoctorHospitalDao.save(baseDoctorHospitalDO);
                    }else {
                        try {
                            throw new Exception("添加失败，该医生以添加过相同的部门信息");
                        }catch (Exception e){
                            result.put("msg", "添加失败，该医生以添加过相同的部门信息");
                            result.put("response", ConstantUtils.FAIL);
                            return result.toJSONString();
                        }
                    }
                }
                if(doctorMappingDO!=null){
                    doctorMappingDO.setOrgCode(orgCode);
                    doctorMappingDO.setOrgName(orgName);
                    doctorMappingDao.save(doctorMappingDO);
                }

            } catch (IOException e) {
                result.put("msg", "convert hospital jsonObject to baseDoctorHospitalDO failed," + e.getCause());
                result.put("response", ConstantUtils.FAIL);
                return result.toJSONString();
            }

        }
        if (!StringUtils.isEmpty(teamCode)){
            String[] teamCodeList = teamCode.split(",");
            for (int i=0;i<teamCodeList.length;i++){
                BaseTeamMemberDO mems = baseTeamMemberDao.findUseDoctorCodeAndTeamCode(baseDoctorDO.getId(),teamCodeList[i]);
                if (mems==null){
                    mems = new BaseTeamMemberDO();
                }
                mems.setTeamCode(teamCodeList[i]);
                mems.setDoctorCode(baseDoctorDO.getId());
                mems.setOrgCode(orgCode);
                mems.setDel("1");
                mems.setCreateTime(new Date());
                baseTeamMemberDao.save(mems);
            }

        }
        result.put("response", ConstantUtils.SUCCESS);
        result.put("msg", baseDoctorDO);
        return result.toJSONString();
    }

    /**
     * 修改医生
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String updateDoctor(String jsonData){
        JSONObject result = new JSONObject();
        if(StringUtils.isEmpty(jsonData)){
            result.put("msg","jsonData is null");
            result.put("response", ConstantUtils.FAIL);
            return result.toJSONString();
        }
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        String teamCode = jsonObject.getString("teamCode");
        JSONObject doctor = jsonObject.getJSONObject("doctor");
        JSONArray role = jsonObject.getJSONArray("role");
        String doctorMappingCode = jsonObject.getString("doctorMappingCode");
        JSONArray hospital = jsonObject.getJSONArray("hospital");
        if(null == doctor){
            result.put("msg","parameter doctor of jsonData is null");
            result.put("response", ConstantUtils.FAIL);
            return result.toJSONString();
        }
        String orgCode="";
        //判断医生id是否存在
        if(StringUtils.isEmpty(doctor.getString("id"))){
            result.put("msg","parameter id for doctor is null when update doctor");
            result.put("response", ConstantUtils.FAIL);
            return result.toJSONString();
        }
        // 修改医生信息
        BaseDoctorDO baseDoctorDO = null;

        try {
            baseDoctorDO = objectMapper.readValue(doctor.toJSONString(),BaseDoctorDO.class);
            BaseDoctorDO oldDoctor = baseDoctorDao.findOne(baseDoctorDO.getId());
            if (oldDoctor!=null&&!oldDoctor.getIdcard().equalsIgnoreCase(baseDoctorDO.getIdcard())){
              List<BaseDoctorDO> isExist =  baseDoctorDao.findByIdcard(baseDoctorDO.getIdcard());
              if (isExist!=null&&isExist.size()>0){
                  result.put("msg","当前身份证号已存在，请检查身份证号是否正确");
                  result.put("response", ConstantUtils.FAIL);
                  return result.toJSONString();
              }
            }
            baseDoctorDO.setPassword(oldDoctor.getPassword());
            baseDoctorDO.setEnabled(baseDoctorDO.getDel().equalsIgnoreCase("1")?1:0);
        } catch (IOException e) {
            result.put("msg","convert doctor jsonObject to BaseDoctorDO failed," + e.getCause());
            result.put("response",ConstantUtils.FAIL);
            return result.toJSONString();
        }
        this.save(baseDoctorDO);
        DoctorMappingDO doctorMappingDO = null;
        if (!StringUtils.isEmpty(doctorMappingCode)){
            doctorMappingDO = doctorMappingDao.findByIdcard(baseDoctorDO.getIdcard());
            if (doctorMappingDO==null){
                doctorMappingDO = new DoctorMappingDO();
            }
            doctorMappingDO.setMappingCode(doctorMappingCode);
            doctorMappingDO.setDoctor(baseDoctorDO.getId());
            doctorMappingDO.setDoctorName(baseDoctorDO.getName());
            doctorMappingDO.setIdcard(baseDoctorDO.getId());
            doctorMappingDO.setCreateTime(new Date());
            doctorMappingDO= doctorMappingDao.save(doctorMappingDO);
        }

        //修改医生角色关联关系，医生默认可以没有角色，前端不修改就不做任何操作
        if(!CollectionUtils.isEmpty(role)){
            BaseDoctorRoleDO baseDoctorRoleDO = null;
            Set<Object> roleIdList = baseDoctorRoleService.findRoleIdList(baseDoctorDO.getId());
            try {
                for(Object object : role){
                    baseDoctorRoleDO = objectMapper.readValue(object.toString(),BaseDoctorRoleDO.class);
                    if(roleIdList.contains(baseDoctorRoleDO.getId())){
                        roleIdList.remove(baseDoctorRoleDO.getId());
                    }
                    baseDoctorRoleDO.setDoctorCode(baseDoctorDO.getId());
                    baseDoctorRoleService.save(baseDoctorRoleDO);
                }
            } catch (IOException e) {
                result.put("msg","convert hospital jsonObject to baseDoctorHospitalDO failed," + e.getCause());
                result.put("response",ConstantUtils.FAIL);
            }
            if(roleIdList.size() > 0){
                baseDoctorRoleService.delete(roleIdList.toArray());
            }

        }else{
            Set<Object> roleIdList = baseDoctorRoleService.findRoleIdList(baseDoctorDO.getId());
            if(roleIdList.size() > 0){
                baseDoctorRoleService.delete(roleIdList.toArray());
            }
        }

        // 修改医生任职机构及职业信息，，医生默认可以没有机构/部门信息，前端不修改就不做任何操作
         if(!CollectionUtils.isEmpty(hospital)){
             BaseDoctorHospitalDO baseDoctorHospitalDO = null;
             Set<Object> hospitalIdList = baseDoctorHospitalService.findDocHospIdList(baseDoctorDO.getId());
             String orgName="";
             try {
                 for(Object object : hospital){
                     baseDoctorHospitalDO = objectMapper.readValue(object.toString(),BaseDoctorHospitalDO.class);
                     if(hospitalIdList.contains(baseDoctorHospitalDO.getId())){
                         hospitalIdList.remove(baseDoctorHospitalDO.getId());
                     }
                     baseDoctorHospitalDO.setDoctorCode(baseDoctorDO.getId());
                     String deptCode = baseDoctorHospitalDO.getDeptCode();
                     DictHospitalDeptDO dictHospitalDeptDO = dictHospitalDeptDao.findByCode(deptCode);
                     if (dictHospitalDeptDO!=null){
                         baseDoctorHospitalDO.setDeptName(dictHospitalDeptDO.getName());
                     }
                     orgCode = baseDoctorHospitalDO.getOrgCode();
                     orgName = baseDoctorHospitalDO.getOrgName();
                     baseDoctorHospitalDO.setDel("1");
                     baseDoctorHospitalService.save(baseDoctorHospitalDO);
                 }
                 if(doctorMappingDO!=null){
                     doctorMappingDO.setOrgCode(orgCode);
                     doctorMappingDO.setOrgName(orgName);
                     doctorMappingDao.save(doctorMappingDO);
                 }
             } catch (IOException e) {
                 result.put("msg","convert hospital jsonObject to baseDoctorHospitalDO failed," + e.getCause());
                 result.put("response",ConstantUtils.FAIL);
             }
             if(hospitalIdList.size() > 0){
                 baseDoctorHospitalService.delete(hospitalIdList.toArray());
             }
         }
         else {//全部移除
            List<BaseDoctorHospitalDO> doctorHospitalDOS = baseDoctorHospitalDao.findByDoctorCode(baseDoctorDO.getId());
             baseDoctorHospitalDao.delete(doctorHospitalDOS);
         }
        if (!StringUtils.isEmpty(teamCode)){
            String[] teamCodeList = teamCode.split(",");
            List<BaseTeamMemberDO> tmlist = baseTeamMemberDao.findUseDoctorCode(baseDoctorDO.getId());
            for (BaseTeamMemberDO baseTeamMemberDO:tmlist){
                baseTeamMemberDO.setDel("0");
            }
            baseTeamMemberDao.save(tmlist);
            for (int i=0;i<teamCodeList.length;i++){
                BaseTeamMemberDO mems = baseTeamMemberDao.findUseDoctorCodeAndTeamCode(baseDoctorDO.getId(),teamCodeList[i]);
                if (mems==null){
                    mems = new BaseTeamMemberDO();
                }
                mems.setTeamCode(teamCodeList[i]);
                mems.setDoctorCode(baseDoctorDO.getId());
                mems.setOrgCode(orgCode);
                mems.setDel("1");
                mems.setCreateTime(new Date());
                baseTeamMemberDao.save(mems);
            }

        }else {
            List<BaseTeamMemberDO> tmlist = baseTeamMemberDao.findUseDoctorCode(baseDoctorDO.getId());
            for (BaseTeamMemberDO baseTeamMemberDO:tmlist){
                baseTeamMemberDO.setDel("0");
            }
            baseTeamMemberDao.save(tmlist);
        }
        result.put("response",ConstantUtils.SUCCESS);
        result.put("msg",baseDoctorDO);
        return result.toJSONString();

    }

    /**
     * 生效或失效单个医生
     * @param doctorCode
     * @param del
     * @return
     */
    public String enableOrDisableDoctor(String doctorCode,String del){
        JSONObject result = new JSONObject();
        if(StringUtils.isEmpty(doctorCode) || StringUtils.isEmpty(del)){
            result.put("msg","parameter doctorCode or del is null");
            result.put("response",ConstantUtils.FAIL);
            return result.toJSONString();
        }
        BaseDoctorDO baseDoctorDO = baseDoctorDao.findOne(doctorCode);
        if( null == baseDoctorDO ){
            result.put("msg","doctor not exist for id:" + doctorCode);
            result.put("response",ConstantUtils.FAIL);
            return result.toJSONString();
        }
        baseDoctorDO.setDel(del);
        baseDoctorDO.setEnabled(Integer.parseInt(del));
        this.save(baseDoctorDO);
        result.put("response",ConstantUtils.SUCCESS);
        return result.toJSONString();
    }

    /**
     * 获取医生已选中的区县/机构列表，当有机构是被选中时，要标有checked=true的状态，由前端加载生成树形机构，
     * @param doctorCode
     * @return
     */
    public JSONObject getOrgListByTownAndDoctorCode(String doctorCode,String townCode) throws Exception {
        JSONObject result = new JSONObject();
        if(StringUtils.isEmpty(townCode)){
            result.put("msg","townCode is not allowed to be null");
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        List<Map<String, Object>> list = new ArrayList<>();
        list  = orgTreeService.findOrgListByParentCode(townCode);
        if(StringUtils.isEmpty(doctorCode)){
            result.put("response", ConstantUtils.SUCCESS);
            result.put("msg",list);
            return result;
        }
        Map<String,Map<String, Object>> orgCodeMap = new HashMap<>();
        list.forEach( one-> orgCodeMap.put(String.valueOf(one.get("code")),one));
        List<Map<String,Object>> selectedList = baseDoctorHospitalService.getOrgAndDutyListByDoctorCode(doctorCode);
        for(Map<String,Object> one : selectedList){
            if(orgCodeMap.containsKey(one.get("orgCode"))){
                orgCodeMap.get(one.get("orgCode")).put("checked",true);
            }
        }
        result.put("response", ConstantUtils.SUCCESS);
        result.put("msg",JavaBeanUtils.getInstance().mapListJson(orgCodeMap.values()));
        return result;
    }


    /**
     * 获取医生已选中的机构/职务树形结构,当有机构是被选中时，要标有checked=true的状态，生成树形结构，前端直接获取
     * @param doctorCode
     * @return
     */
    public JSONObject getDoctorDutyTree(String doctorCode) throws Exception {
        JSONObject result = new JSONObject();
        if(StringUtils.isEmpty(doctorCode)){
            result.put("msg","doctorCode is not allowed to be null");
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        List<DictDoctorDutyDO> dutyDOList = dictDoctorDutyService.search(null,"-name");

        List<Map<String,Object>> selectedDutylist = baseDoctorHospitalService.getOrgAndDutyListByDoctorCode(doctorCode);
        Set<String> selectedDutySet = new HashSet<>();
        selectedDutylist.forEach( one -> selectedDutySet.add(String.valueOf(one.get("orgCode"))+one.get("doctorDutyCode")));

        List<OrgTree> orgTreeList = new ArrayList<>();
        for(Map<String,Object> one : selectedDutylist){
            OrgTree orgTreeParent = new OrgTree();
            orgTreeParent.setParentCode("");
            orgTreeParent.setCode(String.valueOf(one.get("orgCode")));
            orgTreeParent.setName(String.valueOf(one.get("orgName")));
            orgTreeList.add(orgTreeParent);

            for(DictDoctorDutyDO dictDoctorDutyDO :dutyDOList){
                OrgTree orgTreeChild = new OrgTree();
                orgTreeChild.setParentCode(String.valueOf(one.get("orgCode")));
                orgTreeChild.setCode(dictDoctorDutyDO.getCode());
                orgTreeChild.setName(dictDoctorDutyDO.getName());
                if(selectedDutySet.contains(String.valueOf(one.get("orgCode"))+dictDoctorDutyDO.getCode())){
                    orgTreeParent.setChecked(true);
                    orgTreeChild.setChecked(true);
                }
                orgTreeList.add(orgTreeChild);
            }
        }
        result.put("response", ConstantUtils.SUCCESS);
        // 不同医院职务可以相同
        result.put("msg", objectMapper.readValue(orgTreeService.makeTree(orgTreeList,true,false),JSONArray.class));
        return result;
    }

    /**
     * 获取医生已选中的机构/科室树形结构,当有机构是被选中时，要标有checked=true的状态，生成树形结构，前端直接获取
     * @param doctorCode
     * @return
     */
    public JSONObject getDoctorDeptTree(String doctorCode) throws Exception {
        JSONObject result = new JSONObject();
        if(StringUtils.isEmpty(doctorCode)){
            result.put("msg","doctorCode is not allowed to be null");
            result.put("response", ConstantUtils.FAIL);
            return result;
        }

        //医生已选中的机构的里的科室列表
        String orgDeptSql = "SELECT" +
                "  org.code AS orgCode," +
                "  org.name     AS orgName," +
                "  dept.code    AS deptCode," +
                "  dept.name    AS deptName" +
                " FROM" +
                "  base_org org," +
                "  dict_hospital_dept dept" +
                " WHERE" +
                "  dept.org_code = org.code" +
                "  AND" +
                "  dept.org_code" +
                "  in (" +
                "    SELECT DISTINCT hos.org_code from" +
                "      base_doctor_hospital hos where hos.doctor_code = '" + doctorCode + "'" +
                "  ) ORDER BY dept.name";
        List<Map<String,Object>> deptList = jdbcTemplate.queryForList(orgDeptSql);

        //医生已选中的机构的里的所在科室
        String doctorSelectedDeptSql = "select" +
                "  hos.doctor_code ," +
                "  hos.org_code as orgCode," +
                "  org.name as orgName," +
                "  dept.code as deptCode," +
                "  dept.name as deptName" +
                " from" +
                "  base_doctor_hospital hos," +
                "  base_org org," +
                "  dict_hospital_dept dept" +
                " where" +
                "  hos.org_code = org.code" +
                "  and" +
                "  hos.org_code = dept.org_code" +
                " and  hos.dept_code = dept.code and hos.doctor_code = '" + doctorCode + "' " +
                "  ORDER BY dept.name";
        List<Map<String,Object>> selectedDeptlist = jdbcTemplate.queryForList(doctorSelectedDeptSql.replace("{doctorCode}",doctorCode));

        Set<String> selectedDeptCodeSet = new HashSet<>();
        List<OrgTree> orgTreeList = new ArrayList<>();
        selectedDeptlist.forEach(one -> {
            selectedDeptCodeSet.add(String.valueOf(one.get("orgCode")) + String.valueOf(one.get("deptCode")));
            //机构树
            OrgTree orgTreeParent = new OrgTree();
            orgTreeParent.setParentCode("");
            orgTreeParent.setCode(String.valueOf(one.get("orgCode")));
            orgTreeParent.setName(String.valueOf(one.get("orgName")));
            orgTreeList.add(orgTreeParent);
            //本身就是加载已经选中了的机构，所以机构状态为true
            orgTreeParent.setChecked(true);
        });

        //科室树
        for (Map<String, Object> dept : deptList) {
            OrgTree orgTreeChild = new OrgTree();
            orgTreeChild.setParentCode(String.valueOf(dept.get("orgCode")));
            orgTreeChild.setCode(String.valueOf(dept.get("deptCode")));
            orgTreeChild.setName(String.valueOf(dept.get("deptName")));
            orgTreeList.add(orgTreeChild);
            if (selectedDeptCodeSet.contains(String.valueOf(dept.get("orgCode")) + dept.get("deptCode"))) {
                orgTreeChild.setChecked(true);
            }
        }
        result.put("response", ConstantUtils.SUCCESS);
        //不同医院科室可以相同
        result.put("msg",objectMapper.readValue(orgTreeService.makeTree(orgTreeList,true,false),JSONArray.class));
        return result;
    }

    /**
     * 获取某一科室下的医生列表
     * @param deptCode
     * @return
     */
    public JSONObject getDoctorListByDept(String deptCode) throws Exception {
        JSONObject result = new JSONObject();
        if(StringUtils.isEmpty(deptCode)){
            result.put("msg","parameter deptCode is null");
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        String sql = "select " +
                "  DISTINCT hos.doctor_code as doctorCode, " +
                "  doc.name as name, " +
                "  hos.dept_code as deptCode " +
                " from " +
                "  base_doctor_hospital hos, " +
                "  base_doctor doc " +
                " where " +
                "  hos.doctor_code = doc.id" +
                " and hos.dept_code = '" + deptCode + "'";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        result.put("response", ConstantUtils.SUCCESS);
        result.put("msg",JavaBeanUtils.getInstance().mapListJson(list));
        return result;
    }

    public Map<String, Object> batchInsertDoctor(List<BaseDoctorExcelDO> doctors) throws ManageException {
        Map<String, Object> result = new HashMap<>();
        //批量存储的集合
//        int correctCount = 0;
//        List<BasDrugExcelDO> corrects = new ArrayList<>();
        BaseDoctorDO baseDoctorDO;
        //批量存储
        for(BaseDoctorExcelDO one:doctors){
            baseDoctorDO = new BaseDoctorDO();
            baseDoctorDO.setName(one.getName());
            baseDoctorDO.setDel(one.getDel());
            baseDoctorDO.setSex(one.getSex());
            baseDoctorDO.setIdcard(one.getIdcard());
            baseDoctorDO.setMobile(one.getMobile());
            baseDoctorDO.setIsFamous(one.getIsFamous());
            baseDoctorDO.setExpertise(one.getExpertise());
            baseDoctorDO.setIntroduce(one.getBrief());
            baseDoctorDO.setEnabled(1);
            baseDoctorDO.setLocked(0);
            String salt = UUID.randomUUID().toString().substring(0,5);
            baseDoctorDO.setSalt(salt);
            String pw = one.getIdcard().substring(one.getIdcard().length()-6,one.getIdcard().length());
            baseDoctorDO.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
            if(!StringUtils.isEmpty(one.getJobTitleName())){
                String[] job = one.getJobTitleName().split(",");
                String jobCode = job[0];
                DictJobTitleDO jobTitleDO = jobTitleDao.findByCode(jobCode);
                baseDoctorDO.setJobTitleCode(jobTitleDO.getCode());
                baseDoctorDO.setJobTitleName(jobTitleDO.getName());
            }
            baseDoctorDao.save(baseDoctorDO);
            if(!StringUtils.isEmpty(one.getHospitalInfo())){
                BaseOrgDO orgDO = null;
                DictHospitalDeptDO hospitalDeptDO = null;
                DictDoctorDutyDO doctorDutyDO = null;
                String[] hospitals = one.getHospitalInfo().split(";");
                List<BaseDoctorHospitalDO> doctorHospitalList = new ArrayList<>();
                for(String hospital:hospitals){
                    String[] element = hospital.split("/");
                    String[] org = element[0].split(",");//机构
                    String[] dept = element[1].split(",");//部门
                    String[] duty = element[2].split(",");//职务
                    String orgCode = org[0];
                    String deptCode = dept[0];
                    String dutyCode = duty[0];
                    orgDO =baseOrgDao.findByCode(orgCode);
                    hospitalDeptDO = deptDao.findByCode(deptCode);
                    doctorDutyDO = dutyDao.findByCode(dutyCode);

                    //医生执业信息实体
                    BaseDoctorHospitalDO doctorHospitalDO = new BaseDoctorHospitalDO();
                    doctorHospitalDO.setOrgCode(orgDO.getCode());
                    doctorHospitalDO.setOrgName(orgDO.getName());
                    doctorHospitalDO.setDoctorCode(baseDoctorDO.getId());
                    doctorHospitalDO.setDeptCode(hospitalDeptDO.getCode());
                    doctorHospitalDO.setDoctorDutyCode(doctorDutyDO.getCode());
                    doctorHospitalDO.setDoctorDutyName(doctorDutyDO.getName());
                    doctorHospitalDO.setDel("1");
                    doctorHospitalList.add(doctorHospitalDO);
                }
                doctorHospitalDao.save(doctorHospitalList);

            }
            if(!StringUtils.isEmpty(one.getRoleInfo())){
                BaseDoctorRoleDO baseDoctorRoleDO = null;
                String[] roles = one.getRoleInfo().split(";");
                List<BaseDoctorRoleDO> baseDoctorRoleDOList = new ArrayList<>();
                for(String role:roles){
                    String[] element = role.split(",");
                    String roleCode = element[0];
                    baseDoctorRoleDO = new BaseDoctorRoleDO();
                    baseDoctorRoleDO.setDoctorCode(baseDoctorDO.getId());
                    baseDoctorRoleDO.setRoleCode(roleCode);
                    baseDoctorRoleDOList.add(baseDoctorRoleDO);
                }
                baseDoctorRoleService.batchInsert(baseDoctorRoleDOList);
            }
        }
        result.put("correctCount", doctors.size());
        return result;
    }
    public Map saveIncentive(String doctor,String incentiveIds){
        List<BaseDoctorIncentiveDO> list = baseDoctorIncentiveDao.findByDoctorCode(doctor);
        Map map = new HashMap();
        String name = "";
        BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctor);
        if (baseDoctorDO!=null){
            name = baseDoctorDO.getName();
            map.put("status",-1);
            map.put("msg","获取医生信息失败");
        }
        if (incentiveIds.contains(",")){
            String[] incentiveId = incentiveIds.split(",");
            for (int i= 0;i<incentiveId.length;i++){
                BaseIncentiveDictDO baseIncentiveDictDO = baseIncentiveDictDao.findoneById(incentiveId[i]);
                if (list!=null&&list.size()>0){
                    for (int j= 0;j<list.size();j++){
                        if (list.get(j).getIncentiveId().equalsIgnoreCase(incentiveId[i])){
                            list.get(j).setIsDel("1");
                            baseDoctorIncentiveDao.save(list.get(j));
                            list.remove(j);
                        }else {
                            BaseDoctorIncentiveDO baseDoctorIncentiveDO = new BaseDoctorIncentiveDO();
                            baseDoctorIncentiveDO.setIsDel("1");
                            baseDoctorIncentiveDO.setDoctorCode(doctor);
                            baseDoctorIncentiveDO.setDoctorName(name);
                            baseDoctorIncentiveDO.setIncentiveId(baseIncentiveDictDO.getId());
                            baseDoctorIncentiveDO.setIncentiveName(baseIncentiveDictDO.getIncentiveName());
                            baseDoctorIncentiveDO.setIncentiveImg(baseIncentiveDictDO.getIncentiveImg());
                            baseDoctorIncentiveDao.save(baseDoctorIncentiveDO);
                        }
                    }
                    for (BaseDoctorIncentiveDO baseDoctorIncentiveDO:list){
                        baseDoctorIncentiveDO.setIsDel("0");
                        baseDoctorIncentiveDao.save(baseDoctorIncentiveDO);
                    }
                }else {
                    BaseDoctorIncentiveDO baseDoctorIncentiveDO = new BaseDoctorIncentiveDO();
                    baseDoctorIncentiveDO.setIsDel("1");
                    baseDoctorIncentiveDO.setDoctorCode(doctor);
                    baseDoctorIncentiveDO.setDoctorName(name);
                    baseDoctorIncentiveDO.setIncentiveId(baseIncentiveDictDO.getId());
                    baseDoctorIncentiveDO.setIncentiveName(baseIncentiveDictDO.getIncentiveName());
                    baseDoctorIncentiveDO.setIncentiveImg(baseIncentiveDictDO.getIncentiveImg());
                    baseDoctorIncentiveDao.save(baseDoctorIncentiveDO);
                }
            }
            map.put("status",200);
            map.put("msg","操作成功");
        }else {
            BaseIncentiveDictDO baseIncentiveDictDO = baseIncentiveDictDao.findoneById(incentiveIds);
            if (baseIncentiveDictDO!=null){
                BaseDoctorIncentiveDO baseDoctorIncentiveDO = new BaseDoctorIncentiveDO();
                baseDoctorIncentiveDO.setIsDel("1");
                baseDoctorIncentiveDO.setDoctorCode(doctor);
                baseDoctorIncentiveDO.setDoctorName(name);
                baseDoctorIncentiveDO.setIncentiveId(baseIncentiveDictDO.getId());
                baseDoctorIncentiveDO.setIncentiveName(baseIncentiveDictDO.getIncentiveName());
                baseDoctorIncentiveDO.setIncentiveImg(baseIncentiveDictDO.getIncentiveImg());
                baseDoctorIncentiveDao.save(baseDoctorIncentiveDO);
            }
            map.put("status",200);
            map.put("msg","操作成功");
        }
        return map;
    }
    @Transactional
    public Map saveDoctorIncentive(String doctor,String incentiveIds) throws Exception{
        List<BaseDoctorIncentiveDO> list = baseDoctorIncentiveDao.findByDoctorCode(doctor);
        List<BaseDoctorIncentiveDO> saveList = new ArrayList<>();
        Map map = new HashMap();
        String name = "";
        BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctor);
        if (baseDoctorDO!=null){
            name = baseDoctorDO.getName();
            map.put("status",-1);
            map.put("msg","获取医生信息失败");
        }
        if (incentiveIds.contains(",")){
            String[] incentiveId = incentiveIds.split(",");
            for (int i= 0;i<incentiveId.length;i++){
                BaseIncentiveDictDO baseIncentiveDictDO = baseIncentiveDictDao.findoneById(incentiveId[i]);
                if (list!=null&&list.size()>0){
                    for (int j= 0;j<list.size();j++){
                        if (list.get(j).getIncentiveId().equalsIgnoreCase(incentiveId[i])&&"1".equalsIgnoreCase(list.get(j).getIsDel())){
                            throw new Exception("该激励已经保存过");

                        }else {
                            BaseDoctorIncentiveDO baseDoctorIncentiveDO = new BaseDoctorIncentiveDO();
                            baseDoctorIncentiveDO.setIsDel("1");
                            baseDoctorIncentiveDO.setDoctorCode(doctor);
                            baseDoctorIncentiveDO.setDoctorName(name);
                            baseDoctorIncentiveDO.setIncentiveId(baseIncentiveDictDO.getId());
                            baseDoctorIncentiveDO.setIncentiveName(baseIncentiveDictDO.getIncentiveName());
                            baseDoctorIncentiveDO.setIncentiveImg(baseIncentiveDictDO.getIncentiveImg());
                            saveList.add(baseDoctorIncentiveDO);
                        }
                    }
                }else {
                    BaseDoctorIncentiveDO baseDoctorIncentiveDO = new BaseDoctorIncentiveDO();
                    baseDoctorIncentiveDO.setIsDel("1");
                    baseDoctorIncentiveDO.setDoctorCode(doctor);
                    baseDoctorIncentiveDO.setDoctorName(name);
                    baseDoctorIncentiveDO.setIncentiveId(baseIncentiveDictDO.getId());
                    baseDoctorIncentiveDO.setIncentiveName(baseIncentiveDictDO.getIncentiveName());
                    baseDoctorIncentiveDO.setIncentiveImg(baseIncentiveDictDO.getIncentiveImg());
                    saveList.add(baseDoctorIncentiveDO);
                }
            }
            baseDoctorIncentiveDao.save(saveList);
            map.put("status",200);
            map.put("msg","操作成功");
        }else {
            BaseIncentiveDictDO baseIncentiveDictDO = baseIncentiveDictDao.findoneById(incentiveIds);
            if (baseIncentiveDictDO!=null){
                BaseDoctorIncentiveDO baseDoctorIncentiveDO = new BaseDoctorIncentiveDO();
                baseDoctorIncentiveDO.setIsDel("1");
                baseDoctorIncentiveDO.setDoctorCode(doctor);
                baseDoctorIncentiveDO.setDoctorName(name);
                baseDoctorIncentiveDO.setIncentiveId(baseIncentiveDictDO.getId());
                baseDoctorIncentiveDO.setIncentiveName(baseIncentiveDictDO.getIncentiveName());
                baseDoctorIncentiveDO.setIncentiveImg(baseIncentiveDictDO.getIncentiveImg());
                baseDoctorIncentiveDao.save(baseDoctorIncentiveDO);
            }
            map.put("status",200);
            map.put("msg","操作成功");
        }
        return map;
    }
    public Envelop removeDoctorIncentive(String doctor, String incentiveId){
        Envelop envelop = new Envelop();
        BaseDoctorIncentiveDO baseDoctorIncentiveDO = baseDoctorIncentiveDao.findByDoctorCodeAndIncentiveIdAndIsDel(doctor,incentiveId,"1");
        if (baseDoctorIncentiveDO!=null){
            baseDoctorIncentiveDO.setIsDel("0");
            baseDoctorIncentiveDao.save(baseDoctorIncentiveDO);
            envelop.setStatus(200);
            envelop.setMessage("删除成功");
        }else {
            envelop.setStatus(-1);
            envelop.setMessage("删除失败");
        }
        return envelop;
    }

    public MixEnvelop findIncentiveByDoctor(String doctorId,String name, Integer page, Integer pageSize) {
        MixEnvelop mixEnvelop = new MixEnvelop();
        String sql = "select t.id as \"id\"," +
                "t.doctor_code as \"doctorCode\"," +
                "t.doctor_name as \"doctorName\"," +
                "t.incentive_id as \"incentiveId\"," +
                "b.incentive_code as \"incentiveCode\"," +
                "t.incentive_img as \"incentiveImg\"," +
                "t.incentive_name as \"incentiveName\"," +
                "t.create_time as \"createTime\"," +
                "t.is_del as \"isDel\" from base_doctor_incentive t left join base_incentive_dict b " +
                " on b.id = t.incentive_id where t.is_del =1 ";
        if (!StringUtils.isEmpty(doctorId)){
            sql +=" and t.doctor_code ='"+doctorId+"'";
        }
        if (!StringUtils.isEmpty(name)){
            sql +=" and t.incentive_name like '%"+name+"%'";
        }
        List<Map<String,Object>> list  = hibenateUtils.createSQLQuery(sql,page,pageSize);
        List<BaseDoctorIncentiveDO> listCount = baseDoctorIncentiveDao.findByDoctorCodeListCount(doctorId);
        mixEnvelop.setPageSize(pageSize);
        mixEnvelop.setCurrPage(page);
        mixEnvelop.setTotalCount(listCount==null?0:listCount.size());
        mixEnvelop.setDetailModelList(list);
        return mixEnvelop;
    }
    public List<Map<String,Object>> findIncentiveDict(String doctorCode){
        String sql = "select b.id as \"id\"," +
                "b.incentive_name as \"incentiveName\"," +
                "b.incentive_img as \"incentiveImg\"," +
                "b.incentive_status as \"incentiveStatus\"," +
                "b.is_del as \"isDel\"," +
                "b.incentive_code as \"incentiveCode\"," +
                "b.create_time as \"createTime\"" +
                "from base_incentive_dict b where b.is_del = '1' ";
        if (!StringUtils.isEmpty(doctorCode)){
            sql+=" and b.id not in (select  d.incentive_id from base_doctor_incentive d where d.doctor_code ='"+doctorCode+"'  and d.is_del= '1'" +
                    "  group by  d.incentive_id)";
        }
        List<Map<String,Object>> list = 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("incentiveStatus").toString().equalsIgnoreCase(sysDictDO.getDictCode())){
                        map.put("incentiveStatusName",sysDictDO.getDictValue());
                    }
                }
            }
        }
        return list;
    }
    //医生重置密码
    @Transactional
    public String  resetDoctorPwd(String doctor) throws Exception{

        BaseDoctorDO baseDoctorDO= baseDoctorDao.findById(doctor);
        if (baseDoctorDO!=null){
            String salt = baseDoctorDO.getSalt();
            if (StringUtils.isEmpty(salt)){
                salt = randomString(5);
                baseDoctorDO.setSalt(salt);
            }
            baseDoctorDO.setPassword(MD5.md5Hex(baseDoctorDO.getIdcard().substring(12, 18) + "{" + salt + "}"));
            baseDoctorDao.save(baseDoctorDO);
            if ("xm_ykyy_wx".equalsIgnoreCase(wxId)){
                String res = ykyyService.getResetCode("4",baseDoctorDO.getMobile());
                String resltCode ="";
                String captcha = "";
                if (!StringUtils.isEmpty(res)){
                    JSONObject jsonObject = JSONObject.parseObject(res);
                    if ("10000".equalsIgnoreCase(jsonObject.getString("code"))){
                        captcha = jsonObject.getString("value");
                        resltCode = jsonObject.getString("code");
                        String response =  ykyyService.ResetPwd(baseDoctorDO.getMobile(),baseDoctorDO.getIdcard().substring(12, 18),captcha);
                        if (org.apache.commons.lang3.StringUtils.isNoneBlank(response)){
                            JSONObject object = JSONObject.parseObject(response);
                            if (object.getString("code").equalsIgnoreCase("10000")){
                                return "修改成功！";
                            }else {
                                throw  new Exception("修改失败");
                            }
                        }else {
                            throw  new Exception("修改失败");
                        }
                    }
                }
            }
            return "操作成功";
        }
        return "医生不存在";
    }
}
