package com.yihu.wlyy.service.third.guahao;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.util.SystemConf;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by hzp on 2016/8/13.
 * 医护网挂号服务
 */
@Service
public class GuahaoYihuService implements IGuahaoService {

    private String url = SystemConf.getInstance().getGuahaoUrl();
    private String appid = SystemConf.getInstance().getGuahaoAppid();
    private String secret = SystemConf.getInstance().getGuahaoSecret();

    private String ORG_LIST = "baseinfo/HospitalApi/querySimpleHospitalList";//获取医院列表
    private String DEP_LIST = "baseinfo/HosDeptApi/querySimpleHosDeptList"; //科室列表
    private String DOCTOR_LIST = "baseinfo/DoctorInfoApi/querySimpleDoctorList"; //医生列表
    private String DOCTOR_ARRANGE_SIMPLE = "/gh/GhOpen/QueryGhtArrangeWater"; //医生排班列表
    private String DOCTOR_ARRANGE = "/gh/GhOpen/QueryNumbers"; //医生排班列表(号源)
    private String ORDER_CREATE = "TradeMgmt/Open/createRegOrderForOpen";  //新建预约
    private String ORDER_CANCEL = "TradeMgmt/Open/cancelOrder";   //取消预约
    private String ORDER_INFO = "TradeMgmt/Open/getRegOrderInfo";//预约信息详情

    private ObjectMapper objectMapper = new ObjectMapper();

    /**
     * http调用方法，因旧项目http调用方法混乱，后面可剥离封装
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    private String httpPost(String url, Map<String, String> params) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            if(params!=null&&params.size()>0){
                List<NameValuePair> valuePairs = new ArrayList<NameValuePair>(
                                params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                        NameValuePair nameValuePair = new BasicNameValuePair(
                                        entry.getKey(), String.valueOf(entry.getValue()));
                        valuePairs.add(nameValuePair);
                    }
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
                                valuePairs, "UTF-8");
                httpPost.setEntity(formEntity);
            }
            CloseableHttpResponse resp = httpclient.execute(httpPost);
            try {
                HttpEntity entity = resp.getEntity();
                String respContent = EntityUtils.toString(entity, "UTF-8").trim();
                return respContent;
            } finally {
                resp.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            httpclient.close();
        }
    }

    /**
     * 获取加密后参数集合
     * @param params
     * @return
     */
    private Map<String,String> getSecretParams(Map<String, String> params)
    {
        String timestamp = Long.toString(System.currentTimeMillis());
        params.put("timestamp", timestamp);
        StringBuilder stringBuilder = new StringBuilder();

        // 对参数名进行字典排序  
        String[] keyArray = params.keySet().toArray(new String[0]);
        Arrays.sort(keyArray);
        // 拼接有序的参数名-值串  
        stringBuilder.append(appid);
        for(String key : keyArray)
        {
            stringBuilder.append(key).append(params.get(key));
        }
        String codes = stringBuilder.append(secret).toString();
        String sign = org.apache.commons.codec.digest.DigestUtils.shaHex(codes).toUpperCase();
        // 添加签名,并发送请求  
        params.put("appId", appid);
        params.put("sign", sign);

        return params;
    }

    /**
     * 获取医院列表
     */
    public List<Map<String,String>> GetOrgList(String city,String filter,String type,Integer pageIndex,Integer pageSize) throws Exception{
        List<Map<String,String>> re = new ArrayList<>();
        String province =  city.substring(0,2) + "0000";
        Map<String, String> params = new HashMap<>();
        params.put("provinceCode", province);
        params.put("cityCode", city);
        params.put("pageIndex", String.valueOf(pageIndex));
        params.put("pageSize", String.valueOf(pageSize));
        params.put("hosNameLike", filter);
        params.put("state", "2");

        //调用服务
        String response = httpPost(url + ORG_LIST,getSecretParams(params));
        Map<String,String> map = objectMapper.readValue(response,Map.class);
        if(map.get("Code").equals("10000"))
        {

        }
        else{
            String message = map.get("Message");
            throw new Exception(message);
        }

        return  re;
    }


    /**
     * 获取科室接口
     */
    public List<Map<String,String>> GetOrgDepList(String hospitalId,String filter,Integer pageIndex,Integer pageSize) throws Exception{
        List<Map<String,String>> re = new ArrayList<>();
        Map<String, String> params = new HashMap<>();
        params.put("hospitalId", hospitalId);
        params.put("pageIndex", String.valueOf(pageIndex));
        params.put("pageSize", String.valueOf(pageSize));
        params.put("state", "2");

        //调用服务
        String response = httpPost(url + DEP_LIST,getSecretParams(params));
        Map<String,String> map = objectMapper.readValue(response,Map.class);
        if(map.get("Code").equals("10000"))
        {

        }
        else{
            String message = map.get("Message");
            throw new Exception(message);
        }

        return  re;
    }

    /**
     * 获取医生列表接口
     */
    public List<GuahaoDoctor> GetDoctorList(String hospitalId,String hosDeptId,String filter,Integer pageIndex,Integer pageSize) throws Exception{
        List<GuahaoDoctor> re = new ArrayList<>();
        Map<String, String> params = new HashMap<>();
        params.put("hospitalId", hospitalId);
        params.put("hosDeptId", hosDeptId);
        params.put("pageIndex", String.valueOf(pageIndex));
        params.put("pageSize", String.valueOf(pageSize));
        params.put("doctorService_gh", "2");

        //调用服务
        String response = httpPost(url + DEP_LIST,getSecretParams(params));
        Map<String,String> map = objectMapper.readValue(response,Map.class);
        if(map.get("Code").equals("10000"))
        {
            GuahaoDoctor doctor = new GuahaoDoctor();
        }
        else{
            String message = map.get("Message");
            throw new Exception(message);
        }

        return  re;
    }

    /**
     * 获取医生排班接口
     */
    public List<Map<String,Object>> GetDoctorArrange(String hospitalId,String hosDeptId,String doctorId) throws Exception{
        List<Map<String,Object>> re = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        map.put("test","2");
        re.add(map);
        return  re;
    }

    /**
     * 获取医生排班接口 （一级）
     */
    public List<Map<String,String>> GetDoctorArrangeSimple(String hospitalId,String hosDeptId,String doctorId) throws Exception{
        List<Map<String,String>> re = new ArrayList<>();
        Map<String, String> params = new HashMap<>();
        params.put("hospitalId", hospitalId);
        params.put("hosDeptId", hosDeptId);
        params.put("state", "2");

        //调用服务
        String response = httpPost(url + DEP_LIST,getSecretParams(params));
        Map<String,String> map = objectMapper.readValue(response,Map.class);
        if(map.get("Code").equals("10000"))
        {

        }
        else{
            String message = map.get("Message");
            throw new Exception(message);
        }

        return  re;
    }

    /**
     * 创建挂号单
     */
    public String CreateOrder(String hospitalId,String hospitalName,String hosDeptId,String hosDeptName,String doctorId,String doctorName,String arrangeDate,String patient,String patientName,String cardNo,String clinicCard,String patientPhone) throws Exception{

        return  "";
    }

    /**
     * 取消挂号单
     */
    public boolean CancelOrder(String orderId)   throws Exception
    {
        return true;
    }

    /**
     * 获取医生信息
     */
    public GuahaoDoctor GetDoctorInfo(String doctorId,String hospitalId,String hosDeptId)   throws Exception
    {
        return null;
    }
}
