package cn.quantgroup.xyqb.service.user;

import cn.quantgroup.xyqb.entity.SmsTemplateEntity;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.repository.ISmsTemplateRepository;
import cn.quantgroup.xyqb.util.GcodeUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.inject.Inject;
import java.util.*;

/**
 * Created by hechao on 2020/2/17.
 */
@Slf4j
@Service
public class ISmsService {


    @Inject
    private ISmsTemplateRepository smsTemplateRepository;

    public String sendSms(Long clientId, String type, String phoneNo) {
        JsonResult res = new JsonResult();
        String code = null;
        try {
           Optional<SmsTemplateEntity> optional = smsTemplateRepository.findFirstByClientIdAndType(clientId, type);
           if (!optional.isPresent()) {
               log.error("没有指定的模板");
               return code;
           }
           SmsTemplateEntity smsTemplateEntity = optional.orElse(new SmsTemplateEntity());
           RestTemplate restTemplate = new RestTemplate();
           Map<String, Object> user = new HashMap<>();
           List<String> contentArgs = new ArrayList<>();
           code = GcodeUtils.generatedcode(5);
           contentArgs.add(code);
           user.put("merchantId", smsTemplateEntity.getMerchantId());
           user.put("phoneNo", phoneNo);
           user.put("contentId", smsTemplateEntity.getContentId());
           user.put("contentArgs", contentArgs);
           ResponseEntity<String> responseEntity = restTemplate.postForEntity("https://msgapi-qa.liangkebang.net/middle_office/send/message/quick", user, String.class); //提交的body内容为user对象，请求的返回的body类型为String
           int statusCode = responseEntity.getStatusCodeValue();
           String bodyCode = JSONObject.parseObject(responseEntity.getBody(), HashMap.class).get("code").toString();
           if (200 != statusCode || !"0".equals(bodyCode)) {
               log.error("验证码发送失败");
               return null;
           }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发送验证码异常---{}", e.getMessage());
        }
        return code;
    }
}
