package com.zzwtec.wechat.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.zzwtec.wechat.common.constant.UrlConstants;
import com.zzwtec.wechat.config.WeChatConfig;
import com.zzwtec.wechat.controller.DoorbellController;
import com.zzwtec.wechat.rpc.APIResponse;
import com.zzwtec.wechat.rpc.api.APIService;
import com.zzwtec.wechat.rpc.inject.ProxyBuilder;
import com.zzwtec.wechat.sdk.api.ApiConfigKit;
import com.zzwtec.wechat.sdk.api.SnsAccessTokenApi;
import com.zzwtec.wechat.sdk.inlet.MsgController;
import com.zzwtec.wechat.sdk.msg.out.OutNewsMsg;
import com.zzwtec.wechat.util.CharUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 微信自定义菜单的key
 *
 * @author 邓燎燕
 *         2016年5月5日
 */
public class EventBiz {

    private static final APIService apiService = ProxyBuilder.build(APIService.class,WeChatConfig.weChatConfig);
    private static final Logger logger = LoggerFactory.getLogger(EventBiz.class);

    /**
     * 开门
     */
    public static final String KEY_DOOR = "door";
    /**
     * 个人中心
     */
    public static final String KEY_INFO = "info";
    /**
     * 公告
     */
    public static final String KEY_MSG = "msg";

    /**
     * 开门
     * @param openid 用户openid
     * @param msgController 消息控制器
     */
    public static void doorEven(String appid, String openid, MsgController msgController,String tokenId,String[] communityIds) {
        // 查询用户
        APIResponse userResponse = apiService.findUserByAppidAndOpenid(appid, openid,apiService);
        if (userResponse.isFail()) {
            logger.info("查询用户返回信息:{}",APIResponse.toJSONObject(userResponse).toJSONString());
            msgController.renderOutTextMsg(userTip(userResponse));
            return;
        }
        JSONObject userData = JSONObject.parseObject(userResponse.getData());
        //判断此默认房产是否属于当前物业
        String selCell =userData.getString("selCell");
        //当前没有选择房产
        if(StrKit.isBlank(selCell)){
            try {
                selCell = defaultCell(userData.getString("id"),communityIds);
            } catch (Exception e) {
                logger.error("查询房产出现异常!",e);

            }

        }

        // 查询房间对应的楼栋/小区
        APIResponse objRelTreeResponse = apiService.findObjRelationTreeByCellId(selCell);
        if (objRelTreeResponse.isFail()) {
            logger.info("查询用户房产返回信息:{}",APIResponse.toJSONObject(objRelTreeResponse).toJSONString());
            msgController.renderOutTextMsg("暂无对应的房产");
            return;
        }
        // 查询门 多个门返回门列表 单个门直接开门并发送消息给用户
        JSONObject cellBuildCommunity = JSONObject.parseObject(objRelTreeResponse.getData());
        String communityId = cellBuildCommunity.getString("communityId");
        String buildId = cellBuildCommunity.getString("buildId");
        boolean isContains = Arrays.asList(communityIds).contains(communityId);
        if(isContains){//是否在数据权限范围内
            DoorbellController.getDoorList(msgController, msgController.getRequest(), openid, communityId, buildId,tokenId);
        }else{
            msgController.renderOutTextMsg("暂无对应的房产，请到个人中心设置默认房产。");
            return;
        }

    }



    /**
     * 公告
     * @param openid
     * @param msgController
     */
    public static void msgEven(String appId, String openid, MsgController msgController,String[] communityIds) {
        // 查询用户
        APIResponse userResponse = apiService.findUserByAppidAndOpenid(appId, openid,apiService);
        if (userResponse.isFail()) {
            logger.info("查询用户返回信息:{}",APIResponse.toJSONObject(userResponse).toJSONString());
            msgController.renderOutTextMsg(userTip(userResponse));
            return;
        }

        JSONObject userData = JSONObject.parseObject(userResponse.getData());
        String selCell = userData.getString("selCell");
        //当前没有选择房产
        if(StrKit.isBlank(selCell)){
            try {
                String userID = userData.getString("id");
                selCell = defaultCell(userID,communityIds);
            } catch (Exception e) {
                logger.error("查询房产出现异常!",e);
                msgController.renderOutTextMsg("暂无对应的房产");
                return;
            }

        }

        // 查询房间对应的楼栋/小区
        APIResponse objRelTreeResponse = apiService.findObjRelationTreeByCellId(selCell);
        if (objRelTreeResponse.isFail()) {
            msgController.renderOutTextMsg("暂无对应的房产");
            logger.info("公告返回信息:" + APIResponse.toJSONObject(objRelTreeResponse).toJSONString());
            return;
        }
        // 查询最新12条公告
        JSONObject cellBuildCommunity = JSONObject.parseObject(objRelTreeResponse.getData());
        String communityId = cellBuildCommunity.getString("communityId");

        boolean isContains = Arrays.asList(communityIds).contains(communityId);//小区是否在数据范围内
        if(!isContains){//是否在数据权限范围内
            msgController.renderOutTextMsg("暂无对应的房产，请到个人中心设置默认房产。");
            return;
        }
        String buildId = cellBuildCommunity.getString("buildId");
        String cellId = cellBuildCommunity.getString("cellId");
        APIResponse response = apiService.queryNoticeList(communityId, 1, 12);
        if (response.isFail()) {
            msgController.renderOutTextMsg("暂无新公告");
            return;
        }
        // 没有公告
        JSONObject pageObject = JSONObject.parseObject(response.getData());
        if (pageObject == null || pageObject.get("data") == null) {
            msgController.renderOutTextMsg("暂无新公告");
            return;
        }
        JSONArray noticeArr = JSONArray.parseArray(pageObject.getString("data"));
        if (noticeArr == null || noticeArr.size() == 0) {
            msgController.renderOutTextMsg("暂无新公告");
            return;
        }
        // 如果公告条数超过微信能展示的最多条数，则附加查看更多公告
        OutNewsMsg outNewsMsg = new OutNewsMsg(msgController.getInMsg());
        int i = 0;
        int wxArticleCount = WeChatConfig.weChatConfig.getWxArticleCount();
        int maxShow = wxArticleCount;
        if (noticeArr.size() > wxArticleCount) {
            maxShow = wxArticleCount - 1;
        }
        Pattern pattern = Pattern.compile("^\\[(.*)\\]\\((.*)\\)$");
        for (int j = 0; j < noticeArr.size(); i++, j++) {
            if (i < maxShow) {
                String title = noticeArr.getJSONObject(j).getString("noticeTitle");
                String url;
                Matcher matcher = pattern.matcher(title);
                if (matcher.find()) {
                    title = matcher.group(1);
                    url = matcher.group(2);
                } else {
                    url = WeChatConfig.weChatConfig.getHost() + UrlConstants.MSG_GET_MSG + "/" + noticeArr.getJSONObject(j).getString("noticeId");
                }
                String picUrl = null;
                if (i == 0) {
                    picUrl = WeChatConfig.weChatConfig.getHost() + "/images/msg_list_top.png";
                }
                outNewsMsg.addNews(title, "公告", picUrl, url);
            } else {
                break;
            }
        }
        if (maxShow == (wxArticleCount - 1)) {
            String url = WeChatConfig.weChatConfig.getHost() + UrlConstants.MSG_GET_MSG_LIST + "?openid=" + openid + "&communityId=" + communityId + "&buildId=" + buildId + "&cellId=" + cellId;
            outNewsMsg.addNews("查看更多公告", "更多公告", null, url);
        }
        if (i == 0) {
            msgController.renderOutTextMsg("暂无新公告");
        } else {
            msgController.render(outNewsMsg);
        }
    }


    private static String bindTip() {
        String url = CharUtil.encode(WeChatConfig.weChatConfig.getHost() + UrlConstants.INFO_BING);
        String authorizeURL = SnsAccessTokenApi.getAuthorizeURL(ApiConfigKit.getAppId(), url,ApiConfigKit.getAppId(), false);
        return "你未绑定账号，请点击<a href=\"" + authorizeURL + "\">“绑定账号”</a>";
    }


    private static String userTip(APIResponse userResponse){
        logger.info("查询用户返回信息:{}",APIResponse.toJSONObject(userResponse).toJSONString());
        int code = userResponse.getCode();
        if(code == 310){
            return "查询不到您的用户信息";
        }else if (code == 420){
           return bindTip();
        }
       return "查询不到您的用户信息!";
    }

    //在数据权限内 任意选择一个房产为默认房产
    private static String defaultCell(String userId,String[] communityIds){
        String cellId ="";
        APIResponse userCellResponse = apiService.queryUserAndCellByUserId(userId);
        if(userCellResponse.isFail()){
            return null;
        }

        JSONArray userCells = JSONArray.parseArray(userCellResponse.getData());
        if(userCells == null || userCells.isEmpty()){
            return null;
        }
        for(int i=0;i<userCells.size();i++){
            if(cellId==""){
                JSONObject userCell = (JSONObject) userCells.get(i);
                for(String communityId:communityIds){
                    if(communityId.equals(userCell.getString("communityId"))){
                        cellId = userCell.getString("cellId");
                        break;
                    }
                }
            }
        }
        if(StrKit.isBlank(cellId)){
            return null;
        }
        return cellId;
    }
}
