package com.cftech.member.web;

import com.cftech.accounts.model.MpAccountsEntity;
import com.cftech.core.sql.Conds;
import com.cftech.core.util.MpTokenUtil;
import com.cftech.core.util.StringUtils;
import com.cftech.core.util.SystemConfig;
import com.cftech.member.model.Member;
import com.cftech.member.model.MemberCars;
import com.cftech.member.service.MemberCarsService;
import com.cftech.member.service.MemberService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.mp.api.core.req.model.message.IndustryTemplateMessageSend;
import org.mp.api.core.req.model.message.TemplateData;
import org.mp.api.wxsendmsg.JwTemplateMessageAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by lisw on 2017/9/26.
 */
@Slf4j
@RestController
@RequestMapping("mobile/auth/template")
public class MobileWxTemplateMessageController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private MpTokenUtil tokenUtil;

    @Autowired
    private MemberCarsService memberCarsService;

    @RequestMapping(value="wxtemplate",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject wxtemplate(String templateId,String mCard,String first,String remark,String []keywords,String storeNo,
                                 String id,String[] car,String name,String phone,String status,HttpServletRequest request
    ){
        /**
         * 工单模板消息通知，特殊处理。跳转URL
         */
        log.info("模板消息接口调取=====");
        Enumeration enumeration =request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String paramName = (String) enumeration.nextElement();
            String paramValue = request.getParameter(paramName);
            log.info("参数名:"+paramName+"\t"+"参数值:"+paramValue);
        }
        JSONObject rtnJson = new JSONObject();
        try{
            rtnJson.put("errorNo","0");
            if(StringUtils.isBlank(templateId)){
                rtnJson.put("errorNo","1");
                rtnJson.put("errorMsg","Parameter is Empty");
                return rtnJson;
            }
            String workTemplate = SystemConfig.p.getProperty("WOEK_TEMPLATE_MESSAGE");
            String url = "";
            String appid = SystemConfig.p.get("WX_MP_SERVER_APPID").toString();
            MpAccountsEntity accountsEntity =  tokenUtil.searchAccounts(appid);
            if(workTemplate.equals(templateId) && StringUtils.isNotBlank(id)){//为工单进度模板消息ID，增加URL跳转
                String domain = SystemConfig.p.getProperty("QY_DOMAIN_NAME");
                String carStr = "";
                if(car!=null && car.length>0){
                    for(String carTemp:car){
                        carStr+=carTemp;
                    }
                }
                url+=domain+"/"+"static/mp/dc/personCenter/workorder-timeline.html?appid="+appid+"&storeNo="+storeNo+
                        "&id="+id+"&car="+carStr+"&name="+name+"&tel="+phone+"&status="+status;
                Conds memCarConds = new Conds();
                memCarConds.equal("t.del_flag","0");
                memCarConds.equal("t.plate_number",keywords[0]);
                if(StringUtils.isBlank(keywords[0])){
                    rtnJson.put("errorNo","1");
                    rtnJson.put("errorMsg","plateNumber is Empty");
                    return rtnJson;
                }
                List<MemberCars> memberCars = memberCarsService.fetchSearchByPage(memCarConds,null,0,0);
                if(memberCars==null || memberCars.size()==0){
                    rtnJson.put("errorNo","1");
                    rtnJson.put("errorMsg","Send WorkOrder ----- MemberInfo is Empty");
                    return rtnJson;
                }else{
                    for(MemberCars memberCar : memberCars){
                        sendMessage(templateId,tokenUtil.getToken(accountsEntity.getId()),memberCar.getOpenId(),first,remark,keywords,url);
                    }
                }
            }else{
                Conds conds = new Conds();
                conds.equal("member_id",mCard);
                if(StringUtils.isBlank(mCard)){
                    rtnJson.put("errorNo","1");
                    rtnJson.put("errorMsg","mCard is Empty");
                    return rtnJson;
                }
                List<Member> members = memberService.fetchSearchByPage(conds,null,0,0);
                if(members==null || members.size()==0){
                    rtnJson.put("errorNo","1");
                    rtnJson.put("errorMsg","MemberInfo is Empty");
                    return rtnJson;
                }
                for(Member member : members){
                    sendMessage(templateId,tokenUtil.getToken(accountsEntity.getId()),member.getOpenId(),first,remark,keywords,url);
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            rtnJson.put("errorNo","1");
        }

        return rtnJson;
    }


    private void sendMessage(String templateId,String token,String openId,String first,String remark,String []keywords,String url){
        IndustryTemplateMessageSend mc = new IndustryTemplateMessageSend();
        mc.setTemplate_id(templateId);
        mc.setTouser(openId);
        mc.setAccess_token(token);
        mc.setUrl(url);
        StringBuffer json = new StringBuffer();
        Gson gson = new Gson();
        String objJson = gson.toJson(mc);
        json.append(objJson);
        json.setLength(json.length()-1);
        json.append(",");
        json.append("\"data\":{");
        TemplateData template = new TemplateData();
        template.setValue(first);
        //template.setColor("#ffAADD");
        objJson = gson.toJson(template);
        json.append(" \"first\":");
        json.append(objJson);
        json.append(",");
        if(keywords!=null && keywords.length>0){
            for(int i=0;i<keywords.length;i++){
                template.setValue(keywords[i]);
                objJson = gson.toJson(template);
                json.append(" \"keyword"+(i+1)+"\":");
                json.append(objJson);
                json.append(",");
            }
        }
        template.setValue(remark);
        objJson = gson.toJson(template);
        json.append(" \"remark\":");
        json.append(objJson);
        json.append("}}");
        JwTemplateMessageAPI.sendTemplateMsgJson(json.toString(),token);
    }
}
