package com.ematou.wxservice.mp.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ematou.wxservice.entity.pojo.UserInfo;
import com.ematou.wxservice.mp.message.WeChatMessage;
import com.ematou.wxservice.mp.message.WeChatMpXmlOutMessage;
import com.ematou.wxservice.service.UserInfoService;
import com.ematou.wxservice.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component
public class WeChatScannHandler  implements WeChatMessageHandler {

    @Autowired
    UserInfoService userInfoService;

    @Override
    public WeChatMpXmlOutMessage handlerMessage(WeChatMessage weChatMessage) {
        return WeChatMpXmlOutMessage.TEXT().content(scannMsg(weChatMessage)).toUser(weChatMessage.getFromUser()).fromUser(weChatMessage.getToUser()).build();
    }

    private String scannMsg(WeChatMessage weChatMessage) {
        Map<String, Object> mapMsg = JSONObject.toJavaObject(JSON.parseObject(weChatMessage.getEventKey()), Map.class);
        Map<String,String> map = new HashMap<>();
        map.put("clientId",mapMsg.get("clientId").toString());
        UserInfo userInfo = userInfoService.queryUserInfoByOpenId(weChatMessage.getFromUser());
        map.put("phone",userInfo.getTellPhoneNumber());
        map.put("openId",weChatMessage.getFromUser());
        String wxMpTake = HttpUtils.sendPost("http://icsp-api.ds-bay.com/order/collect/wxMpTakeObject",JSON.toJSONString(map));

        Map<String, Object> weChatMapMsg = JSONObject.toJavaObject(JSON.parseObject(wxMpTake), Map.class);
        if(weChatMapMsg.get("code").equals("50009")){
            return weChatMapMsg.get("msg").toString();
        }else{
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("取件成功！\n");
            List<JSONObject> data = JSON.parseArray(weChatMapMsg.get("data").toString(), JSONObject.class);
            for(JSONObject jsonObject : data){
                stringBuffer.append("\n").append("订单编号："+jsonObject.get("orderSn")).append("柜子编号"+jsonObject.get("lockerName")).append("\n");
            }
            return stringBuffer.toString();
        }

    }
}
