package com.yihu.jw.sms.service;

import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.sms.dao.HospitalSysDictDao;
import com.yihu.jw.util.http.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

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

/**
 * 福州总部的短信接口
 */
@Service
public class ZBSmsService {
    private Logger logger= LoggerFactory.getLogger(ZBSmsService.class);
    private String smsHandlerId;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private HospitalSysDictDao sysDictDao;
    private String appId;
    private String secret;//正式参数
    private String prixUrl;//正式参数


    /**
     * 初始化总部接口参数
     */
    private void init(){
        List<WlyyHospitalSysDictDO> dictDOList = sysDictDao.findByDictName("zbSms");
        for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:dictDOList){
            if (wlyyHospitalSysDictDO.getDictCode().equalsIgnoreCase("smsHandlerId")){
                smsHandlerId=wlyyHospitalSysDictDO.getDictValue();
            }else if (wlyyHospitalSysDictDO.getDictCode().equalsIgnoreCase("appId")){
                appId=wlyyHospitalSysDictDO.getDictValue();
            }else if (wlyyHospitalSysDictDO.getDictCode().equalsIgnoreCase("secret")){
                secret=wlyyHospitalSysDictDO.getDictValue();
            }else if (wlyyHospitalSysDictDO.getDictCode().equalsIgnoreCase("prixUrl")){
                prixUrl=wlyyHospitalSysDictDO.getDictValue();
            }
        }
    }


    /**
     * 发送短信
     * @return
     */
    public Integer sendMessage(String mobile,String code) throws Exception {
        try{
            //初始化参数
            init();
            String apiUrl = prixUrl+"MsgGW/Sms/send";
            String timestamp =
                    Long.toString(System.currentTimeMillis());//timestamp必须与服务器时间相差在5分钟以内，否则调用将失败;

            Map<String, String> paramMap = new HashMap<>();
            JSONObject object = new JSONObject();
            object.put("code",code);
            paramMap.put("mobile", mobile);
            paramMap.put("templateParam", object.toJSONString());
            paramMap.put("handlerId", smsHandlerId);
            paramMap.put("timestamp", timestamp);

            StringBuilder stringBuilder = new StringBuilder();

            // 对参数名进行字典排序
            String[] keyArray = paramMap.keySet().toArray(new String[0]);
            Arrays.sort(keyArray);
            // 拼接有序的参数名-值串
            stringBuilder.append(appId);
            for (String key : keyArray)
            {
                stringBuilder.append(key).append(paramMap.get(key));
            }
            String codes = stringBuilder.append(secret).toString();
            String sign = org.apache.commons.codec.digest.DigestUtils.shaHex(codes).toUpperCase();

            // 添加签名,并发送请求
            paramMap.put("appId", appId);
            paramMap.put("sign", sign);

            String rep = httpClientUtil.httpPost(apiUrl, paramMap);
            logger.info("总部短信接口请求返回值："+rep);
            if (!StringUtils.isEmpty(rep)){
                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(rep);
                if ( jsonObject.getInteger("Code")==10000){
                    return 0;
                }else {
                    throw new Exception(jsonObject.getString("Message"));
                }
            }
            return 1;
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return null;
    }
}
