package com.chinacreator.video.restful.controller;


import com.alibaba.fastjson.JSONObject;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.restful.service.CdnSendSmsService;
import com.chinacreator.video.util.SendSmsUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.URLDecoder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Logger;


/**
 * @author yu.su
 * @date 2020.12.10
 */
@RestController
public class CdnSendSmsController {

    @Autowired
    private CdnSendSmsService cdnSendSmsService;

    private Logger logger = Logger.getLogger("cdnsms");

    @PostMapping("/cdnSendSms")
    public Map<String, Object> sendSms(@RequestBody String params) throws Exception {
        Map<String, Object> logMap = new LinkedHashMap<>();
        logMap.put("resultcode", "0");
        logMap.put("msg", "");
        logger.info("请求参数========" + params);
        OrderInfo orderInfo = new OrderInfo();
        try {
            Map<String,Object> map = JSONObject.parseObject(params, Map.class);
            BeanUtils.populate(orderInfo,map);
            cdnSendSmsService.busiCheck(orderInfo);
            boolean bl = cdnSendSmsService.findByUserid(orderInfo.getUserid(), orderInfo.getChannel());
            if (bl) {
                SendSmsUtil.send(orderInfo.getUserid(), URLDecoder.decode((String) map.get("content"),"utf-8"));
                logger.info(orderInfo.getUserid() + "====发送成功");
            } else {
                logMap.put("resultcode", "9000");
                logMap.put("msg", "该用户没配置白名单");
            }
            logMap.put("phone", orderInfo.getUserid());
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(orderInfo.getUserid() + "=========发送短信失败===" + e.getMessage());
            logMap.put("phone", orderInfo.getUserid());
            if (e instanceof BussinessException) {
                logMap.put("resultcode", ((BussinessException) e).getCode());
                logMap.put("msg", e.getMessage());
            } else {
                logMap.put("resultcode", "8000");
                logMap.put("msg", "短信接口出现异常====" + e.getMessage());
            }
        }
        return logMap;
    }
}
