package com.iamberry.wechat.handles.Join;

import com.iamberry.cache.LocalCache;
import com.iamberry.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.sendmsg.CodeService;
import com.iamberry.wechat.tools.ResponseJson;
import com.iamberry.wechat.tools.ResultInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;

@Controller
@RequestMapping("/user")
public class AibeJoinHandler {

    private LocalCache<String,Integer> cache = new LocalCache<>(300);

    @Autowired
    private CodeService codeService;
    @Autowired
    private SystemService systemService;

    @ResponseBody
    @RequestMapping("/add")
    public ResponseJson newsList(HttpServletRequest request,
         @RequestParam(value= "name",defaultValue= "" ,required=false) String name,
         @RequestParam(value = "tel", defaultValue = "",required=false) String tel) {
        ResponseJson rj = new ResponseJson();
        rj.setReturnCode(500);
        rj.setResultCode(500);

        if(StringUtils.isEmpty(name)){
            rj.setResultMsg("姓名不能为空！");
            return rj;
        }

        if(StringUtils.isEmpty(tel)){
            rj.setResultMsg("电话不能为空！");
            return rj;
        }

        Integer telNum = cache.get(tel);
        if(telNum == null){
            cache.put(tel,1);
        }else{
            if(telNum > 3){
                rj.setResultMsg("您已经发过三次加盟信息了！");
                return rj;
            }else{
                cache.put(tel,telNum+1);
            }
        }

        String msgTel = systemService.selectOneShopRuleByIdDynamic(258).getRuleDesc();
        String text = MessageFormat.format(ResultInfo.telJoinMsg, name, tel);
        String result = codeService.informShipping(msgTel, text);
        if("SUCCESS".equals(result)){
            rj.setResultMsg("提交成功！");
            rj.setReturnCode(200);
            rj.setResultCode(200);
            return rj;
        }
        rj.setResultMsg("发送短信失败！"+ result);
        return rj;
    }
}
