package com.hz.pm.api.external.sms;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hz.pm.api.external.sms.dto.SmsDto;
import com.hz.pm.api.external.sms.vo.SmsReceipt;
import com.hz.pm.api.external.sms.vo.SmsReply;
import com.hz.pm.api.external.sms.vo.SmsSendResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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

@Slf4j
@Component
@RequiredArgsConstructor
public class SmsServiceClient {

    /**
     * 短信服务
     */
    @Value("${sms.client-url:}")
    private String smsUrl;

    public static final String SMS_REPLY = "/sms/reply";
    public static final String SMS_SEND = "/sms/send";
    public static final String SMS_RECEIPT = "/sms/status";
    /**
     * 短信回复
     * @param result
     * @return
     */
    public List<SmsReply> smsReply(String result) {
        List<SmsReply> smsReplyList;
        String refreshUrl = smsUrl + SMS_REPLY;
        HashMap<String,Object> map = new HashMap<>();
        map.put("result",result);
        String responseResult = HttpUtil.post(refreshUrl, map);
        JSONObject responseJson = JSON.parseObject(responseResult, JSONObject.class);
        String fileData = responseJson.getString("data");
        JSONArray result1 = JSON.parseObject(fileData).getJSONArray("result");
        smsReplyList = JSONObject.parseArray(result1.toJSONString(),SmsReply.class);
        return smsReplyList;
    }

    /**
     * 短信发送
     * @return
     */
    public SmsDto<SmsSendResponse> smsSend(String content, List<String> phones) {
        String phonesSplit = String.join(",", phones);
        String refreshUrl = smsUrl + SMS_SEND;
        Map<String,Object> map = new HashMap<>();
        map.put("content",content);
        map.put("phones",phonesSplit);
        String responseResult = HttpUtil.post(refreshUrl, JSON.toJSONString(map));
        return JSONUtil.toBean(responseResult, new TypeReference<SmsDto<SmsSendResponse>>() {
        }, false);
    }

    /**
     * 短信回执
     * @param result
     * @return
     */
    public SmsReceipt smsReceipt(String result) {
        SmsReceipt smsReceipt = null;
        String refreshUrl = smsUrl + SMS_RECEIPT;
        HashMap<String,Object> map = new HashMap<>();
        map.put("result",result);
        String responseResult =  HttpUtil.post(refreshUrl, map);
        JSONObject responseJson = JSON.parseObject(responseResult, JSONObject.class);
        String fileData = responseJson.getString("data");
        return JSONObject.parseObject(fileData, SmsReceipt.class);
    }

}
