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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorRoleDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.hospital.mapping.DoctorMappingDO;
import com.yihu.jw.hospital.mapping.dao.DoctorMappingDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.util.idcard.IdCardUtil;
import com.yihu.utils.network.HttpResponse;
import com.yihu.utils.network.HttpUtils;
import com.yihu.utils.security.MD5;
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.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.yihu.jw.util.common.PwdUtil.randomString;

/**
 * 眼科医院
 * Created by yeshijie on 2020/4/24.
 *
 * @author yeshijie.
 */
@Service
public class YkyyBaseService {

    private Logger logger = LoggerFactory.getLogger(YkyyBaseService.class);

    @Autowired
    private HttpClientUtil httpClientUtil;

    private static String yktUrl1 = "http://www.yanketong.com:90/";

    @Autowired
    private BasePatientDao patientDao;

    @Autowired
    private BaseDoctorHospitalDao baseDoctorHospitalDao;

    @Autowired
    private BaseDoctorRoleDao baseDoctorRoleDao;

    @Autowired
    private DoctorMappingDao doctorMappingDao;

    @Autowired
    private BaseDoctorDao baseDoctorDao;

    private final static String orgCode ="350211A5004";

    private final static String orgName ="厦门大学附属厦门眼科中心";

    private final static String url="http://192.168.20.55:10023/ykyy/createSQLQuery";

    private static String yktUrl = "http://www.yanketong.com:133/api/";

    /**
     * 眼科医院单点登录接口
     * @return
     */
    public String getDoctorInfoByVerifycode(String verifyCode){
        String url = "api/Doctor/GetDoctorInfoByverifycode";
        return httpClientUtil.get(yktUrl1+url+"?verifyCode="+verifyCode,"GBK");
    }


    /**
     * 眼科医院单点登录接口
     * @return
     */
    public String getPatientInfoByVerifycode(String verifyCode){
        String url = "/api/patient/GetPatientInfoByVerifycode";
        return httpClientUtil.get(yktUrl1+url+"?verifyCode="+verifyCode,"GBK");
    }

    /**
     *获取家庭成员信息
     *
     * @param tel
     * @param userId
     * @return
     */
    public String getFamilyList(String tel,String userId){
        String response="";
        String url = yktUrl+"doc_jkzl/get_family_list?";
        if (StringUtils.isNoneBlank(tel)&&StringUtils.isNoneBlank(userId)){
            url+="tel="+tel;
            url+="&user_id="+userId;
        }else if (StringUtils.isNoneBlank(tel)&&!StringUtils.isNoneBlank(userId)){
            url+="tel="+tel;
        }else if (!StringUtils.isNoneBlank(tel)&&StringUtils.isNoneBlank(userId)){
            url+="user_id="+userId;
        }
        response = httpClientUtil.get(url,"GBK");
        logger.info("获取家庭成员信息:"+response);
        return response;
    }

    /**
     * 眼科通登录接口
     * @param tel
     * @param password
     * @return
     */
    public String yktLogin(String tel,String password){
        String response="";
        String url = yktUrl+"user_center/patient_login?patient_account="+tel+"&patient_pwd="+password;
        response = httpClientUtil.get(url,"GBK");
        logger.info("获取眼科通登录信息:"+response);
        return response;
    }

    /**
     * 眼科通验证码
     * @param type
     * @param phone
     * @return
     */
    public String getShortMessage(String type,String phone){
        String response="";
        String url = yktUrl+"verification_code/short_message?type="+type+"&telephone="+phone;
        response = httpClientUtil.get(url,"GBK");
        logger.info("眼科通验证码:"+response);
        return response;
    }
    /**
     * 获取眼科通修改密码验证码
     * @param type
     * @param phone
     * @return
     */
    public String getResetCode(String type,String phone) throws  Exception{
        String response="";
        String codeResponse = getVerificationReal(phone,type,"");
        String veryCode = "";
        if (StringUtils.isNoneBlank(codeResponse)){
            JSONObject jsonObject = JSONObject.parseObject(codeResponse);
            if ("10000".equalsIgnoreCase(jsonObject.getString("code"))){
                veryCode =  jsonObject.getString("value");
            }
        }
        String url = yktUrl1+"api/Doctor/GetVerificationCode";
        Map param = new HashMap();
        param.put("loginid",phone);
        param.put("type",type);
        param.put("VerificationReal",veryCode);
        logger.info("请求参数:"+param.toString());
        response = httpClientUtil.httpPost(url,param);
        logger.info("眼科通验证码:"+response);
        return response;
    }
    /**获取图形验证码
     *
     * @param loginid
     * @param type
     * @param IPAddress
     * @return
     */
    public String getVerificationReal(String loginid,String type,String IPAddress) throws  Exception{
        String response="";
        Map map = new HashMap();
        map.put("loginid",loginid);
        map.put("type",type);
        map.put("IPAddress",IPAddress);
        String url = yktUrl1+"api/Share/GetVerificationReal";
        response = httpClientUtil.httpPost(url,map);
        logger.info("修改眼科同密码后的信息:"+response);
        return response;
    }
    /**
     * 忘记密码修改
     * @param loginid
     * @param password
     * @return
     */
    public String ResetPwd(String loginid,String password,String verCode) throws  Exception{
        String response="";
        String url = yktUrl1+"api/Doctor/ResetPassword";
        Map param = new HashMap();
        param.put("loginid",loginid);
        param.put("password",password);
        param.put("verCode",verCode);
        logger.info("请求参数:"+param.toString());
        response = httpClientUtil.httpPost(url,param);
        logger.info("眼科通验证码:"+response);
        return response;
    }

    /**
     * 增加家庭成员
     * @param userId
     * @param idcard
     * @param name
     * @param sex
     * @param birth
     * @param age
     * @param tel
     * @return
     */
    public String addFamily(String userId,String idcard,String name,String sex,String birth,String age,String tel){
        String response="";
        String url = yktUrl+"doc_jkzl/add_family?ass_user_id="+userId+"&id_card="+idcard+"&name="+name+"&sex="+sex
                +"&birth="+birth+"&age="+age+"&tel="+tel+"&medical_card=&illness=本人&clinic_id=";
        response = httpClientUtil.get(url,"GBK");
        logger.info("增加家庭成员:"+response);
        return response;
    }


    /**获取眼科通忘记密码信息
     *
     * @param tel
     * @param password
     * @param vercode
     * @return
     */
    public String   forgetPassword(String tel,String password,String vercode){
        String response="";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("loginid",tel);
        jsonObject.put("password",password);
        String url = "http://www.yanketong.com:90/api/Patient/ForgotPassword4Jkzl";
        response = httpClientUtil.sendPost(url,jsonObject.toJSONString());
        logger.info("获取眼科通忘记密码信息:"+response);
        return response;
    }

    /**
     * telephone=15578008051&patient_pwd=123456&code=513970&invite_code=a01522&equipment_type=ios&equipment_guid=12312321
     * 眼科通用户注册
     *
     * @param telephone
     * @param patientPwd
     * @param code
     * @return
     */
    public String getRegisterUser(String telephone,String patientPwd,String code,String inviteCode,String equipmentType,String equipmentGuid){
        String response="";
        String url = yktUrl+"user_center/patient_register01?telephone="+telephone+"&patient_pwd="+patientPwd+"&code="+code+"&invite_code="+inviteCode+"&equipment_type="+equipmentType+
                "&equipment_guid="+equipmentGuid;
        response = httpClientUtil.get(url,"GBK");
        logger.info("眼科通用户注册:"+response);
        return response;
    }



    /**
     * 同步眼科通数据
     * @param patient
     * @return
     * @throws Exception
     */
    public void registerYkt(String patient,String pw,String code) throws Exception {
        BasePatientDO basePatientDO  = patientDao.findById(patient);
        if (basePatientDO!=null){
            String userId = basePatientDO.getUserId();
            if (StringUtils.isNoneBlank(userId)){
                String familyList =getFamilyList(null,userId);
                JSONObject object = JSONObject.parseObject(familyList);
                if (object.getString("code").equalsIgnoreCase("200")){
                    JSONObject object1 = object.getJSONObject("data");
                    JSONArray array = object1.getJSONArray("list");
                    if (array!=null&&array.size()!=0){
                        JSONObject jsonObject = array.getJSONObject(0);
                        if (jsonObject!=null){
                            String yktId = jsonObject.getString("ID");
                            basePatientDO.setYktId(yktId);
                            patientDao.save(basePatientDO);
                        }
                    }else {
                        String birdth = IdCardUtil.getBirthdayForIdcardStr(basePatientDO.getIdcard());
                        Integer age = IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard());
                        Integer sex = basePatientDO.getSex()!=null?basePatientDO.getSex():0;
                        String family = addFamily(userId,basePatientDO.getIdcard(),basePatientDO.getName(),sex.toString(),birdth,age.toString(),basePatientDO.getMobile());
                        JSONObject object2 = JSONObject.parseObject(family);
                        if (object2.getString("code").equalsIgnoreCase("200")){
                            JSONObject object3 = object2.getJSONObject("data");
                            String yktId = object3.getString("ID");
                            basePatientDO.setYktId(yktId);
                            patientDao.save(basePatientDO);
                        }
                    }

                }else {
                    throw new Exception("查询家庭成员失败！");
                }
            }else {
                String r =getRegisterUser(basePatientDO.getMobile(),pw,code,"a01522","xmijk","xmijk");
                JSONObject object4 = JSONObject.parseObject(r);
                if (object4.getString("code").equalsIgnoreCase("200")){
                    JSONObject object5 = object4.getJSONObject("data");
                    if (object5!=null){
                        userId = object5.getString("ID");
                        basePatientDO.setUserId(userId);
                        patientDao.save(basePatientDO);
                        String familyList =getFamilyList(null,userId);
                        JSONObject object = JSONObject.parseObject(familyList);
                        if (object.getString("code").equalsIgnoreCase("200")){
                            JSONObject object1 = object.getJSONObject("data");
                            JSONArray array = object1.getJSONArray("list");
                            if (array!=null&&array.size()!=0){
                                JSONObject jsonObject1 = array.getJSONObject(0);
                                if (jsonObject1!=null){
                                    String yktId = jsonObject1.getString("ID");
                                    userId = jsonObject1.getString("ASSUSERID");
                                    basePatientDO.setYktId(yktId);
                                    basePatientDO.setUserId(userId);
                                    patientDao.save(basePatientDO);
                                }
                            }else {
                                String birdth = IdCardUtil.getBirthdayForIdcardStr(basePatientDO.getIdcard());
                                Integer age = IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard());
                                Integer sex = basePatientDO.getSex()!=null?basePatientDO.getSex():0;
                                String family = addFamily(userId,basePatientDO.getIdcard(),basePatientDO.getName(),sex.toString(),birdth,age.toString(),basePatientDO.getMobile());
                                JSONObject object2 = JSONObject.parseObject(family);
                                if (object2.getString("code").equalsIgnoreCase("200")){
                                    JSONObject object3 = object2.getJSONObject("data");
                                    String yktId = object3.getString("ID");
                                    basePatientDO.setYktId(yktId);
                                    userId = object3.getString("ASSUSERID");
                                    basePatientDO.setUserId(userId);
                                    patientDao.save(basePatientDO);
                                }
                            }

                        }else {
                            throw new Exception("查询家庭成员失败！");
                        }
                    }
                }else {
                    String familyList =getFamilyList(basePatientDO.getMobile(),null);
                    JSONObject object = JSONObject.parseObject(familyList);
                    if (object.getString("code").equalsIgnoreCase("200")){
                        JSONObject object1 = object.getJSONObject("data");
                        JSONArray array = object1.getJSONArray("list");
                        if (array!=null&&array.size()!=0){
                            JSONObject jsonObject1 = array.getJSONObject(0);
                            if (jsonObject1!=null){
                                String yktId = jsonObject1.getString("ID");
                                userId = jsonObject1.getString("ASSUSERID");
                                basePatientDO.setYktId(yktId);
                                basePatientDO.setUserId(userId);
                                patientDao.save(basePatientDO);
                            }
                        }else {
                            userId=object1.getString("user_id");
                            String birdth = DateUtil.dateToStrShort(IdCardUtil.getBirthdayForIdcard(basePatientDO.getIdcard()));
                            Integer age = IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard());
                            Integer sex = basePatientDO.getSex()!=null?basePatientDO.getSex():0;
                            String family = addFamily(userId,basePatientDO.getIdcard(),basePatientDO.getName(),sex.toString(),birdth,age.toString(),basePatientDO.getMobile());
                            JSONObject object2 = JSONObject.parseObject(family);
                            if (object2.getString("code").equalsIgnoreCase("200")){
                                JSONObject object3 = object2.getJSONObject("data");
                                String yktId = object3.getString("ID");
                                basePatientDO.setYktId(yktId);
                                userId = object3.getString("ASSUSERID");
                                basePatientDO.setUserId(userId);
                                patientDao.save(basePatientDO);
                            }
                        }
                    }else {
                        throw new Exception("查询家庭成员失败！");
                    }
                }
            }
        }
    }

    /**
     * 医生端眼科通登陆
     * @param loginId 账户
     * @param password 密码
     * @return
     */
    public String DoctorLogin(String loginId,String password){
        String response="";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("loginId",loginId);//账户
        jsonObject.put("password",password);//密码
        String url = "http://www.yanketong.com:90/api/Doctor/DoctorLogin";
        response = httpClientUtil.sendPost(url,jsonObject.toJSONString());
        logger.info("医生端登陆:"+response);
        return response;
    }


    public String updateYkyyDoctor(String idCard,String verifyCode,String yktDoctorId)throws Exception{
        String sql ="select y.code AS \"code\",y.name AS \"name\",y.expertise AS \"expertise\",y.introduce AS \"introduce\",y.mobile AS \"mobile\",y.idCard AS \"idcard\",y.JOBTITLECODE AS \"jobTitleCode\",y.JOBTITLENAME AS \"jobTitleName\",y.dept AS \"dept\",y.deptName AS \"deptName\" from v_Hlw_Ysxx y where y.idcard is not null";
        sql +=" and y.idcard ='"+idCard+"' ";
        Map<String,Object> params = new HashedMap();
        params.put("sql",sql);
        HttpResponse response = HttpUtils.doGet(url,params);
        String content = response.getContent();
        logger.info("response:"+content);
        JSONObject rs = JSON.parseObject(content);
        Integer status = rs.getInteger("status");
        if(status!=null&&status == 200){
            JSONArray array = rs.getJSONArray("detailModelList");
            logger.info("doctor size:"+array.size());
            if(array!=null&&array.size()>0) {
                for (int i = 0; i < array.size(); i++) {
                    JSONObject doctorJson = array.getJSONObject(i);
                    String idcard = doctorJson.getString("idcard");

                    //过滤身份证脏数据
                    if(idcard.length()>=15){

                        BaseDoctorDO doctorDOs = baseDoctorDao.findByIdcardAndId(idcard);

                        if(doctorDOs!=null){

                            BaseDoctorDO doctor = doctorDOs;

                            String salt = randomString(5);
                            String pw = idcard.substring(idcard.length() - 6);
                            doctor.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                            doctor.setSalt(salt);
                            if(StringUtils.isNoneBlank(doctorJson.getString("jobTitleCode"))){
                                doctor.setJobTitleCode(doctorJson.getString("jobTitleCode"));
                                doctor.setJobTitleName(doctorJson.getString("jobTitleName"));
                            }
                            doctor.setVerifyCode(verifyCode);
                            doctor.setYktDoctorId(yktDoctorId);
//                            doctor.setExpertise(doctorJson.getString("expertise"));
//                            doctor.setIntroduce(doctorJson.getString("introduce"));
//                            doctor.setMobile(doctorJson.getString("mobile"));

                            BaseDoctorDO temp = baseDoctorDao.save(doctor);

                            List<BaseDoctorHospitalDO> hospitalDOs = baseDoctorHospitalDao.findByOrgCodeAndDeptCodeAndDoctorCode(orgCode,doctorJson.getString("dept"),doctor.getId());
                            if(hospitalDOs!=null&&hospitalDOs.size()>0){
                                //机构信息部门信息
                                BaseDoctorHospitalDO hospitalDO = hospitalDOs.get(0);
                                hospitalDO.setDeptCode(doctorJson.getString("dept"));
                                hospitalDO.setDeptName(doctorJson.getString("deptName"));
                                hospitalDO.setDel("1");
                                baseDoctorHospitalDao.save(hospitalDO);
                            }


                        }else{
                            //新增医生
                            BaseDoctorDO doctor = new BaseDoctorDO();
                            doctor.setName(doctorJson.getString("name"));
                            doctor.setIdcard(idcard);

                            doctor.setSex(Integer.parseInt(com.yihu.jw.util.common.IdCardUtil.getSexForIdcard_new(idcard)));
                            doctor.setBirthday(com.yihu.jw.util.common.IdCardUtil.getBirthdayForIdcard(idcard));

                            doctor.setProvinceCode("350000");
                            doctor.setProvinceName("福建省");
                            doctor.setTownCode("350203");
                            doctor.setTownName("思明区");
                            doctor.setCityCode("350200");
                            doctor.setCityName("厦门市");
                            doctor.setVerifyCode(verifyCode);
                            doctor.setYktDoctorId(yktDoctorId);
//                            doctor.setExpertise(doctorJson.getString("expertise"));
//                            doctor.setIntroduce(doctorJson.getString("introduce"));
//                            doctor.setMobile(doctorJson.getString("mobile"));
                            //认证信息设置
                            String salt = randomString(5);
                            String pw = idcard.substring(idcard.length() - 6);
                            doctor.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                            doctor.setSalt(salt);
                            doctor.setDel("1");
                            doctor.setEnabled(1);
                            doctor.setLocked(0);
                            doctor.setCreateTime(new Date());

                            doctor.setJobTitleCode(doctorJson.getString("jobTitleCode"));
                            doctor.setJobTitleName(doctorJson.getString("jobTitleName"));

                            BaseDoctorDO temp = baseDoctorDao.save(doctor);

                            //机构信息部门信息
                            BaseDoctorHospitalDO hospitalDO = new BaseDoctorHospitalDO();
                            hospitalDO.setDoctorCode(temp.getId());
                            hospitalDO.setOrgCode(orgCode);
                            hospitalDO.setOrgName(orgName);
                            hospitalDO.setDeptCode(doctorJson.getString("dept"));
                            hospitalDO.setDeptName(doctorJson.getString("deptName"));
                            hospitalDO.setDel("1");
                            baseDoctorHospitalDao.save(hospitalDO);

                            //保存角色
                            BaseDoctorRoleDO role = new BaseDoctorRoleDO();
                            role.setDoctorCode(temp.getId());
                            role.setRoleCode("specialist");
                            baseDoctorRoleDao.save(role);

                            //保存mapping
                            DoctorMappingDO mappingDO = new DoctorMappingDO();
                            mappingDO.setIdcard(idcard);
                            mappingDO.setDoctor(temp.getId());
                            mappingDO.setDoctorName(temp.getName());

                            mappingDO.setOrgCode(orgCode);
                            mappingDO.setOrgName(orgName);

                            mappingDO.setMappingCode(doctorJson.getString("code"));
                            mappingDO.setMappingName(temp.getName());
                            mappingDO.setCreateTime(new Date());

                            doctorMappingDao.save(mappingDO);
                        }
                    }
                }
            }
        }
        return "success";
    }

}
