package com.zzwtec.wechat.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.StrKit;
import com.zzwtec.jdbc.entity.ThirdUserWechat;
import com.zzwtec.jdbc.service.ThirdUserWechatService;
import com.zzwtec.third.model.basedata.dto.UserDTO;
import com.zzwtec.third.utils.StringUtil;
import com.zzwtec.third.utils.TimeUtil;
import com.zzwtec.wechat.biz.WechatBiz;
import com.zzwtec.wechat.common.ErrorMsg;
import com.zzwtec.wechat.common.constant.UrlConstants;
import com.zzwtec.wechat.common.enums.UserCellType;
import com.zzwtec.wechat.config.WeChatConfig;
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.*;
import com.zzwtec.wechat.service.LoginService;
import com.zzwtec.wechat.service.SMSService;
import com.zzwtec.wechat.util.CharUtil;
import com.zzwtec.wechat.util.CommonUtil;
import com.zzwtec.wechat.util.SessionKeyUtil;
import com.zzwtec.wechat.util.StringSecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;

import static com.zzwtec.wechat.common.enums.UserCellType.*;
import static com.zzwtec.wechat.sdk.utils.RenderUtil.renderText;
import static java.util.stream.Collectors.toList;

/**
 * 个人中心
 */
@Controller
@RequestMapping("/info")
public class UserCenterController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SMSService smsService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private ThirdUserWechatService thirdUserWechatService;
    private static final APIService apiService = ProxyBuilder.build(APIService.class,WeChatConfig.weChatConfig);

    @Value("${face.headFaceUrl}")
    private String headFaceUrl;

    @Autowired
    private WeChatConfig weChatConfig;

    @RequestMapping("/wechatOauth2")
    public ModelAndView wechatOauth2(){

        ModelAndView modelAndView = new ModelAndView();
        String appid=weChatConfig.getAppId();

        // 生成回调路径
        String redirect_uri = CharUtil.encode(WeChatConfig.weChatConfig.getHost() + UrlConstants.INFO_INDEX);

        String state = weChatConfig.getAppId();
        String url = String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=%s#wechat_redirect",appid,redirect_uri,state);
        modelAndView.addAllObjects(new HashMap<String, Object>(){{
            put("url", url);
        }});
        modelAndView.setViewName("/info/view/wechatOauth2.html");
        return modelAndView;
    }

    /**
     * 绑定账号页面
     * code		微信服务返回的，没有表示用户不同意授权
     * state	微信服务返回的
     */
    @RequestMapping("/bing")
    public String bing() {
        String state = WeChatConfig.weChatConfig.getAppId();

        SnsAccessToken snsAccessToken = WechatBiz.getUserInfo();
        if (snsAccessToken == null || snsAccessToken.getErrorCode() != null) {
            return "/common/view/tips.html";
        }
        if(snsAccessToken.getErrorCode() != null && snsAccessToken.getErrorCode() == 40163){//code已使用
            wechatOauth2();
            return null;
        }
        String openid = snsAccessToken.getOpenid();
        if (openid == null) {
            return "/common/view/tips.html";
        } else {
            String url = WeChatConfig.weChatConfig.getHost() + UrlConstants.INFO_BING + "?state=" + state;
            return bing(openid, state, url);
        }
    }

    /**
     * 获取验证码
     */
    @RequestMapping(value = "/getcheckmsg",produces = "application/json")
    @ResponseBody
    public JSONObject getMsgVerify(String phone) {
        JSONObject json = JSONObject.parseObject("{}");
        if (StrKit.notBlank(phone)) {

//            根据手机号码查询用户是否存在
            APIResponse userResultObject = apiService.queryUserByPhone(phone,loginService.getLoginToken());
            if(userResultObject.getData()==null){//用户不存在
                json.put("error","310");
                json.put("errormsg",ErrorMsg._310);
                return json;
            }
            String key = SessionKeyUtil.getSMSRedisKey(phone);
            String num = redisTemplate.opsForValue().get(key); //存储格式 "验证码-时间戳"，如"1234-1516670934102"
            if (num != null) {
                if(num.indexOf("-")>0){
                    String[] nums = num.split("-");
                    long time = Math.abs(System.currentTimeMillis() - Long.parseLong(nums[1]));
                    if(time<60000){//少于1分钟
                        json.put("error","411");
                        json.put("errormsg",ErrorMsg._411);
                        return json;
                    }
                }else{// 旧的格式 "验证码"
                    json.put("error","411");
                    json.put("errormsg",ErrorMsg._411);
                    return json;
                }
            }
            boolean temp=smsService.sendMsg(phone);
            if(!temp){
                json.put("error","500");
                json.put("errormsg","发送短信验证码失败");
            }else{
                json.put("error", "0");
                json.put("errormsg", ErrorMsg._0);
            }
        } else {
            json.put("error", "302");
            json.put("errormsg", ErrorMsg._302);
        }
        return json;
    }

    /**
     * 绑定账号
     */
    @RequestMapping(value = "/tiewx",produces = "application/json")
    @ResponseBody
    public JSONObject tiewx(String appid,String openid,String phone,String verifyCode) {

        // 参数不完整
        if (StrKit.isBlank(appid) || StrKit.isBlank(openid) || StrKit.isBlank(phone) || StrKit.isBlank(verifyCode)) {
            return APIResponse.toJSONObject("302", ErrorMsg._302);
        }
        // 校验验证码
        String key = SessionKeyUtil.getSMSRedisKey(phone);
        String num = redisTemplate.opsForValue().get(key); //存储格式 "验证码-时间戳"，如"1234-1516670934102"
        if (num == null) return APIResponse.toJSONObject("313", ErrorMsg._313);
        if(num.indexOf("-")>0){
            String[] nums = num.split("-");
            if (!nums[0].equals(verifyCode)) return APIResponse.toJSONObject("312", ErrorMsg._312);
        }else{// 旧的格式 "验证码"
            if (!num.equals(verifyCode)) return APIResponse.toJSONObject("312", ErrorMsg._312);
        }

//        APIResponse response = apiService.bindWechat(phone, openid, appid);

        // 根据手机获取用户信息
        APIResponse apiResponse = apiService.queryUserByPhone(phone,loginService.getLoginToken());
        if (apiResponse.isFail()) {
            return APIResponse.toJSONObject(apiResponse);
        }
        UserDTO userDTO = JSONObject.parseObject(apiResponse.getData(), UserDTO.class);
        if (userDTO == null || StringUtil.isEmpty(userDTO.getId())) {
            APIResponse errorResp = new APIResponse(1, ErrorMsg._310);
            return APIResponse.toJSONObject(errorResp);
        }
        // 对用户房产校验
        APIResponse checkUserCellResp = checkUserCell(userDTO);
        if (checkUserCellResp.isFail()) {
            return APIResponse.toJSONObject(checkUserCellResp);
        }
        // 查询是否已经绑定了该微信和用户
        ThirdUserWechat hasUserWechat = thirdUserWechatService.queryUserWechatByOpenid(openid);
        if (hasUserWechat != null) {
            APIResponse errorResp = new APIResponse(1, ErrorMsg._423);
            return APIResponse.toJSONObject(errorResp);
        } else {
            // 添加微信用户信息
            ThirdUserWechat userWechat = new ThirdUserWechat();
            userWechat.setId(CommonUtil.getUUID());
            userWechat.setOpenid(openid);
            userWechat.setPhone(phone);
            userWechat.setUserId(userDTO.getId());
            userWechat.setDeletec(false);
            userWechat.setCreateTime(TimeUtil.getNowTime());
            userWechat.setUpdateTime(TimeUtil.getNowTime());
            int rowChanged = thirdUserWechatService.add(userWechat);
            if (rowChanged <= 0) {
                APIResponse errorResp = new APIResponse(1, ErrorMsg._505);
                return APIResponse.toJSONObject(errorResp);
            }
        }
        APIResponse response = new APIResponse(0, "success");

        return APIResponse.toJSONObject(response);
    }

    /**
     * 校验绑定的手机用户是存在于该微信公众号管理的小区
     *
     * @param userDTO
     * @return APIResponse.code = 1：不存在；APIResponse.code=0：存在
     * @author wxy
     */
    private APIResponse checkUserCell(UserDTO userDTO) {
        if (StringUtil.isEmpty(userDTO.getSelCell())) {
            return new APIResponse(1, ErrorMsg._417);
        }
        // 获取用户所有的房产及其对应的小区id
        List<String> userComList = new ArrayList<>();
        APIResponse userCellResp = apiService.queryUserAndCellByUserId(userDTO.getId());
        if (userCellResp.isFail()) {
            return userCellResp;
        }
        List<Map<String,Object>> userCellList = JSONObject.parseObject(userCellResp.getData(), List.class);
        userCellList.forEach(map -> {
            String communityId = (String) map.get("communityId");
            userComList.add(communityId);
        });
        // 获取当前公众号管理的所有小区id
        loginService.getLoginToken();
        String communityIds = (String) redisTemplate.opsForValue().get("adminCommunityIds");
        for (String communityId : communityIds.split(",")) {
            boolean contains = userComList.contains(communityId);
            if (contains) {
                return new APIResponse(0, "success");
            }
        }

        return new APIResponse(1, ErrorMsg._417);
    }

    /**
     * 解绑账号
     */
    @RequestMapping(value = "/unbing",produces = "application/json")
    @ResponseBody
    public Object unbing(String openid) {
        APIResponse userResponse = apiService.findUserByAppidAndOpenid(ApiConfigKit.getAppId(), openid,apiService);
        if (userResponse.isFail()) {
            return userResponse;
        }
        String phone = JSONObject.parseObject(userResponse.getData()).getString("loginphone");
//        APIResponse unBindResponse = apiService.unBindWechat(phone, openid, ApiConfigKit.getAppId());

        // 查询是否已经绑定了该微信和用户
        ThirdUserWechat hasUserWechat = thirdUserWechatService.queryUserWechatByOpenid(openid);
        if (hasUserWechat == null) {
            APIResponse errorResp = new APIResponse(1, ErrorMsg._420);
            return APIResponse.toJSONObject(errorResp);
        }
        // 物理删除微信用户信息
        int rowChanged = thirdUserWechatService.deleteByOpenidAndPhone(openid, phone);
        if (rowChanged <= 0) {
            APIResponse errorResp = new APIResponse(1, ErrorMsg._505);
            return APIResponse.toJSONObject(errorResp);
        }
        APIResponse unBindResponse = new APIResponse(0, "success");

        return APIResponse.toJSONObject(unBindResponse);
    }

    /**
     * 个人中心页
     */
    @RequestMapping("/index")
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView();

//        // 检查参数
        String state = WeChatConfig.weChatConfig.getAppId();

        SnsAccessToken snsAccessToken = WechatBiz.getUserInfo();
        // 用户不同意授权
        if (snsAccessToken == null || snsAccessToken.getErrorCode() != null) {
            modelAndView.setViewName("/common/view/tips.html");
            return modelAndView;
        }
        if(snsAccessToken.getErrorCode() != null && snsAccessToken.getErrorCode() == 40163){//code已使用
            wechatOauth2();
            return null;
        }
        // 检查参数
        String openid = snsAccessToken.getOpenid();
        // appid不正确
        if (!state.equals(WeChatConfig.weChatConfig.getAppId())) {
            renderText("appid不正确");
            return null;

        }
        // 用户不同意授权
        if (openid == null) {
            modelAndView.setViewName("/common/view/tips.html");
            return modelAndView;
        }
        // 查询用户信息
        APIResponse userResponse = apiService.findUserByAppidAndOpenid(ApiConfigKit.getAppId(), openid,apiService);
        if (userResponse.isFail()) {
            if (userResponse.getCode() == 420) {
                String url = WeChatConfig.weChatConfig.getHost() + UrlConstants.INFO_INDEX + "?state=" + state;
                String bing = bing(openid, state, url);
                if(StrKit.notBlank(bing)){
                    modelAndView.setViewName(bing);
                    return modelAndView;
                }else{
                    renderText("");
                    return null;
                }
            } else {
                renderText(userResponse.getMsg());
                return null;
            }
        }
        JSONObject user = JSONObject.parseObject(userResponse.getData());
        String userId = user.getString("id");
        // 查询用户对应的房产
        APIResponse userCellResponse = apiService.findUserAndCellByUserId(userId,apiService);
        if (userCellResponse.isFail()) {
            renderText(userCellResponse.getMsg());
            return null;
        }
        System.out.println(JSONArray.parseArray(userCellResponse.getData()));
        // 没有默认房产
        JSONArray userCells = JSONArray.parseArray(userCellResponse.getData());
        //当前物业里面没有房产
        JSONArray permissionCells=dataPermissionUserCell(userCells);
        if(permissionCells.size()<=0){

            modelAndView.addAllObjects(new HashMap<String, Object>(){{
                put("errorMsg", ErrorMsg._417);
            }});
            modelAndView.setViewName("/common/view/errorMsg.html");
            return modelAndView;
        }

        JSONObject defaultUserCell = defaultUserCell(permissionCells, user.getString("selCell"));
        if (defaultUserCell == null) {
            modelAndView.addAllObjects(new HashMap<String, Object>(){{
                put("errorMsg", "您没有绑定默认房产");
            }});
            modelAndView.setViewName("/common/view/errorMsg.html");
            return modelAndView;
        }

        /*
        * 用户默认房产不属于该物业则进行提示显示处理
        * */
        Boolean[] selCellIsManaged = {true};
        // 获取用户的默认房产
        JSONObject defaultUserCellObj = defaultUserCell(userCells, user.getString("selCell"));
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(defaultUserCellObj);
        // 从默认房产中获取属于该物业的房产 从而判断用户房产是否属于该物业
        JSONArray defaultUserCellForDP = dataPermissionUserCell(jsonArray);
        if (defaultUserCellForDP == null || defaultUserCellForDP.size() <= 0) {
            selCellIsManaged[0] = false;
        }

//         设置个人信息
        String url = WeChatConfig.weChatConfig.getHost() + UrlConstants.INFO_INDEX + "?state=" + state;
        setJsSDKParam(state, url);

        // 住户人脸信息
        String avatarURL=(String)user.get("avatarURL");
        if(StringUtil.notEmpty(avatarURL)){
           // avatarURL="http://fastdfs.zzwtec.com/"+avatarURL;
            avatarURL=headFaceUrl+avatarURL;
        }else{
            avatarURL="";
        }
        String faceUrl=avatarURL;
        modelAndView.addAllObjects(new HashMap<String, Object>(){{
            String userTypeStr=defaultUserCell.get("type")+"";
            int type=-1;
            if(StringUtil.notEmpty(userTypeStr)){
                if ("MASTER".equals(userTypeStr)) {
                    type=1;
                }else if("MEMBER".equals(userTypeStr)){
                    type=2;
                }else if("TENANT".equals(userTypeStr)){
                    type=3;
                }
            }
            put("openid", openid);
            put("userId", userId);
            put("name", defaultUserCell.get("userName"));
            put("phone", defaultUserCell.getString("userLoginphone"));
            put("showPhone", StringSecurityUtil.getPhoneSeccurity(defaultUserCell.getString("userLoginphone")));
            if (selCellIsManaged[0]) {
                put("cellName", defaultUserCell.get("cellName"));
            } else {
                put("cellName", "本物业未绑定默认房产");
            }
            put("selCell", defaultUserCell.get("cellId"));
            put("type", type);
            put("faceUrl", faceUrl);
            put("list", permissionCells.stream().map(new UserCell2CellFun()).collect(toList()));

        }});
        modelAndView.setViewName("/info/view/index.html");
        return modelAndView;
    }

    /**
     * 修改智之屋账号名称
     */
    @RequestMapping(value = "/updatename",produces ="application/json")
    @ResponseBody
    public JSONObject updatename(String userId,String name,String phone,String selCell) {
        APIResponse response = apiService.userUpdate(userId, loginService.getLoginToken(), name, phone, selCell);
        return APIResponse.toJSONObject(response);
    }

    /**
     * 选择默认房间
     */
    @RequestMapping(value = "/cellsel",produces = "application/json")
    @ResponseBody
    public JSONObject cellsel(String userId,String cellSel,String name,String phone) {
        APIResponse response = apiService.userUpdate(userId, loginService.getLoginToken(),name, phone, cellSel);
        return APIResponse.toJSONObject(response);
    }

    /**
     * 成员详情
     * @param memberId
     * @param selCell
     * @return
     */
    @RequestMapping("/memberinfo")
    public ModelAndView memberinfo(String memberId, String selCell) {
        ModelAndView modelAndView = new ModelAndView();

        // 检查参数
        if (StringUtils.isEmpty(memberId) || StringUtils.isEmpty(selCell)) {
            renderText("请求参数不完整");
            return null;
        }
//        // 请求失败
//        APIResponse configResponse = apiService.queryCommunityConfigByCellId(selCell);
//        if (configResponse.isFail()) {
//            renderText(configResponse.getMsg());
//            return null;
//        }
//        APIResponse userCellResponse = apiService.queryUserAndCellByCellId(selCell);
//        if (userCellResponse.isFail()) {
//            renderText(userCellResponse.getMsg());
//            return null;
//        }

        // 查询用户对应的房产
        APIResponse userResponse = apiService.queryUserByUserId(memberId);
        if (userResponse.isFail()) {
            renderText(userResponse.getMsg());
            return null;
        }
        System.out.println(JSONObject.parseObject(userResponse.getData()));
        // 没有默认房产
        JSONObject userJSON = JSONObject.parseObject(userResponse.getData());
        // 住户人脸信息
        String avatarURL=(String)userJSON.get("avatarURL");
        if(StringUtil.notEmpty(avatarURL)){
            //avatarURL="http://fastdfs.zzwtec.com/"+avatarURL;
            avatarURL=headFaceUrl+avatarURL;
        }else{
            avatarURL="";
        }
        String faceUrl=avatarURL;
        modelAndView.addAllObjects(new HashMap<String, Object>(){{
            put("appId", ApiConfigKit.getAppId());
            put("name", userJSON.get("name"));
            put("phone", StringSecurityUtil.getPhoneSeccurity(userJSON.getString("loginphone")));
            put("userId", memberId);
            put("faceUrl", faceUrl);

        }});
        modelAndView.setViewName("/info/view/memberinfo.html");
        return modelAndView;
    }

    /**
     * 成员管理页面
     * v0 openid
     * v1 userUuid
     * v2 selCell
     */
    @RequestMapping("/memberlist")
    public ModelAndView memberlist(String openid, String userId, String selCell) {
        ModelAndView modelAndView = new ModelAndView();

        // 检查参数
        if (StringUtils.isEmpty(openid) || StringUtils.isEmpty(userId) || StringUtils.isEmpty(selCell)) {
            renderText("请求参数不完整");
            return null;
        }
        // 请求失败
        APIResponse configResponse = apiService.queryCommunityConfigByCellId(selCell);
        if (configResponse.isFail()) {
            renderText(configResponse.getMsg());
            return null;
        }
        APIResponse userCellResponse = apiService.queryUserAndCellByCellId(selCell);
        if (userCellResponse.isFail()) {
            renderText(userCellResponse.getMsg());
            return null;
        }
        // 设置成员页面信息
        JSONArray userCells = JSONArray.parseArray(userCellResponse.getData());

        modelAndView.addAllObjects(new HashMap<String, Object>(){{
            put("appId", ApiConfigKit.getAppId());
            put("userId", userId);
            put("openid", openid);
            put("cellSel", selCell);
            put("unableAddUser", unableAddUser(configResponse.getData()));
            put("masterList", toMemberList(userCells, userId, MASTER));
            put("memberList", toMemberList(userCells, userId, MEMBER));
            put("tenantList", toMemberList(userCells, userId, TENANT));

        }});
        modelAndView.setViewName("/info/view/memberlist.html");
        return modelAndView;
    }

    /**
     * 成员添加
     */
    @RequestMapping(value = "/memberadd",produces = "application/json")
    @ResponseBody
    public JSONObject memberadd(String cellSel,String name,String member,int type) {
        APIResponse response = apiService.memberAdd(type, cellSel, member, name,loginService.getLoginToken());
        return APIResponse.toJSONObject(response).fluentPut("member_id",response.getData());

    }

    /**
     * 测试自定义菜单
     */
    @RequestMapping(value = "/createmenu",produces = "application/json")
    @ResponseBody
    public JSONObject createmenu() {
        String host=weChatConfig.getHost();
        String json="{\n" +
                "        \"button\": [\n" +
                "            {\n" +
                "                \"type\": \"click\", \n" +
                "                \"name\": \"开门\", \n" +
                "                \"key\": \"door\", \n" +
                "                \"sub_button\": [ ]\n" +
                "            }, \n" +
                "            {\n" +
                "                \"name\": \"我的\", \n" +
                "                \"sub_button\": [\n" +
                "                    {\n" +
                "                        \"type\": \"view\", \n" +
                "                        \"name\": \"个人中心\", \n" +
                "                        \"url\": \""+host+"/info/wechatOauth2\", \n" +
                "                        \"sub_button\": [ ]\n" +
                "                    }, \n" +
                "                    {\n" +
                "                        \"type\": \"click\", \n" +
                "                        \"name\": \"公告\", \n" +
                "                        \"key\": \"msg\", \n" +
                "                        \"sub_button\": [ ]\n" +
                "                    }\n" +
                "                ]\n" +
                "            }, \n" +
                "            {\n" +
                "                \"name\": \"关于\", \n" +
                "                \"sub_button\": [\n" +
                "                    {\n" +
                "                        \"type\": \"view\", \n" +
                "                        \"name\": \"合作\", \n" +
                "                        \"url\": \"http://m.zzwtec.com/index.php?m=content&c=index&a=lists&catid=12\", \n" +
                "                        \"sub_button\": [ ]\n" +
                "                    }, \n" +
                "                    {\n" +
                "                        \"type\": \"view\", \n" +
                "                        \"name\": \"产品视频\", \n" +
                "                        \"url\": \"http://v.youku.com/v_show/id_XMTU4Mjc2MjMyMA==.html?from=s1.8-1-1.2&spm=a2h0k.8191407.0.0#paction\", \n" +
                "                        \"sub_button\": [ ]\n" +
                "                    }, \n" +
                "                    {\n" +
                "                        \"type\": \"view\", \n" +
                "                        \"name\": \"产品介绍\", \n" +
                "                        \"url\": \"http://m.zzwtec.com/index.php?m=content&c=index&a=lists&catid=36\", \n" +
                "                        \"sub_button\": [ ]\n" +
                "                    }, \n" +
                "                    {\n" +
                "                        \"type\": \"view\", \n" +
                "                        \"name\": \"企业介绍\", \n" +
                "                        \"url\": \"http://m.zzwtec.com/index.php?m=content&c=index&a=lists&catid=13\", \n" +
                "                        \"sub_button\": [ ]\n" +
                "                    },\n" +
                "                    {\n" +
                "                        \"type\": \"view\", \n" +
                "                        \"name\": \"APP下载\", \n" +
                "                        \"url\": \"http://web.zzwtec.com/mobile/apk/download\", \n" +
                "                        \"sub_button\": [ ]\n" +
                "                    }\n" +
                "                ]\n" +
                "            }\n" +
                "        ]\n" +
                "    }";
        ApiResult apiResult= MenuApi.createMenu(json);

        return APIResponse.toJSONObject("0", ErrorMsg._0);


    }

    /**
     * 开锁反馈详情
     */
    @RequestMapping("/feedbackdetail")
    public ModelAndView feedbackdetail() {
        ModelAndView modelAndView = new ModelAndView();
        //暂无详情跳转空白页
        modelAndView.setViewName("/common/view/blankPage.html");
        return modelAndView;
    }
    /**
     * 成员删除
     */
    @RequestMapping(value = "/memberdel",produces = "application/json")
    @ResponseBody
    public JSONObject memberdel(String cellSel,String memberId) {

        APIResponse response = apiService.memberDel(cellSel, memberId,loginService.getLoginToken());
        return APIResponse.toJSONObject(response);

    }

    /**
     * 呼叫电话页面
     * v0 openid
     * v1 userUuid
     * v2 selCell
     */
    @RequestMapping("/phone")
    public ModelAndView phone(String openid, String userId, String selCell) {
        ModelAndView modelAndView = new ModelAndView();
        if (StrKit.notBlank(openid) &&
                StrKit.notBlank(userId) &&
                StrKit.notBlank(selCell)) {
            boolean cancall = false;
            String callphone = "";
            APIResponse response = apiService.queryCell(selCell);
            if (response.isSuccess() && response.getData() != null) {
                JSONObject cell = JSONObject.parseObject(response.getData());
                cancall = cell.getBoolean("cancall");
                callphone = cell.getString("callphone");
            }

            String finalCallphone = callphone;
            boolean finalCancall = cancall;
            modelAndView.addAllObjects(new HashMap<String, Object>(){{
                put("appId", ApiConfigKit.getAppId());
                put("cancall", finalCancall);
                put("showCallphone", StringSecurityUtil.getPhoneSeccurity(finalCallphone));
                put("callphone", finalCallphone);
                put("userId", userId);
                put("openid", openid);
                put("cellSel", selCell);

            }});
            modelAndView.setViewName("/info/view/phone.html");
            return modelAndView;
        }
        renderText("");
        return null;
    }

    /**
     * 设置呼叫电话
     */
    @RequestMapping(value = "/setphone",produces = "application/json")
    @ResponseBody
    public JSONObject setphone(boolean cancall,String callphone,String cellSel) {

        // 查询房间
        APIResponse response = apiService.queryCell(cellSel);
        if (response == null || response.getCode() != 0) {
            return APIResponse.toJSONObject(response);
        }
        if (response.getData() == null) {
            return APIResponse.toJSONObject("408", ErrorMsg._408);
        }
        if(callphone.contains("*")){//如果电话号码里包含* 证明电话号码未修改
            return APIResponse.toJSONObject("302", ErrorMsg._302);
        }
        // 更新房间
        JSONObject cellInfo = JSONObject.parseObject(response.getData());
        response = apiService.updateCell(cellInfo.getString("buildId"), cellSel, cellInfo.getString("name"), cellInfo.getString("num"), cellInfo.getString("address"), cancall, callphone, loginService.getLoginToken());
        return APIResponse.toJSONObject(response);
    }

    /**
     * 检测用户是否注册
     * 暂未使用
     */
    @RequestMapping(value = "/checkuser",produces = "application/json")
    @ResponseBody
    public JSONObject checkUser(String phone) {
        if (StrKit.isBlank(phone)) {
            return APIResponse.toJSONObject("302", ErrorMsg._302);
        }
        APIResponse response = apiService.checkUserByPhone(phone);
        return APIResponse.toJSONObject(response).fluentPut("data", Boolean.parseBoolean(response.getData()));
    }

    /**
     * 上传人脸图片
     */
    @RequestMapping(value = "/uploadFaceImage",produces = "application/json")
    @ResponseBody
    public JSONObject uploadFaceImage(String userId,String imgBase64) {
        if (StrKit.isBlank(userId) || StrKit.isBlank(imgBase64) ) {
            return APIResponse.toJSONObject("302", ErrorMsg._302);
        }
        imgBase64=imgBase64.substring(imgBase64.indexOf(",") + 1);
//        //人脸检测
//        APIResponse response =apiService.faceDetection(imgBase64,,CommonUtil.getUUID());
//        if(Boolean.parseBoolean(response.getData())){
//
//        }

        // 上传人脸图片(已经包含了人脸检测)
        APIResponse response = apiService.updateFaceToken(userId,imgBase64,loginService.getLoginToken());


        return APIResponse.toJSONObject(response);
    }

    /**
     * 进入绑定页面
     * @param openid
     * @param appid
     * @param url
     */
    private String bing(String openid, String appid, String url) {
        if (appid.equals(WeChatConfig.weChatConfig.getAppId())) {
            request.setAttribute("openid", openid);
            setJsSDKParam(appid, url);
            return "/info/view/bing.html";
        } else {
            return "";
        }
    }

    /**
     * 设置微信内置浏览器的JS SDK参数
     *
     * @param appid appid
     * @param url url
     */
    private void setJsSDKParam(String appid, String url) {
        ApiConfigKit.setThreadLocalAppId(appid);
        JsTicket jsTicket = JsTicketApi.getTicket(JsTicketApi.JsApiType.jsapi);
        AccessTokenApi.refreshAccessToken();

        long timestamp = System.currentTimeMillis();
        String noncestr = CharUtil.makeVerifyNum(false, 16);

        String string1 = "jsapi_ticket=" + jsTicket.getTicket() + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&value=" + url;
        String signature = HashKit.sha1(string1);

        request.setAttribute("appid", appid);
        request.setAttribute("timestamp", String.valueOf(timestamp));
        request.setAttribute("nonceStr", noncestr);
        request.setAttribute("signature", signature);
    }

    /**
     *   过滤出用户默认的房产
     */
    private JSONObject defaultUserCell(JSONArray userCells, String defaultCellId) {
        if(userCells == null){
            return null;
        }
        Optional<Object> userCellOptional = userCells.stream().filter(o -> ((JSONObject) o).getString("cellId").equals(defaultCellId)).findFirst();
        return (JSONObject) userCellOptional.orElse(userCells.isEmpty() ? null : ((JSONObject)userCells.get(0)));
    }

    /**
     * 根据数据权限筛除房产
     */
    public JSONArray dataPermissionUserCell(JSONArray userCells) {
        JSONArray result=new JSONArray();
        if(userCells == null){
            return null;
        }
        loginService.getLoginToken();
        String adminCommunityIds=redisTemplate.opsForValue().get("adminCommunityIds");
        if(StringUtil.notEmpty(adminCommunityIds)){
            String[] communityIds=adminCommunityIds.split(",");
            for(int i=0;i<userCells.size();i++){
                JSONObject josnObject=(JSONObject)userCells.get(i);
                for(String communityId:communityIds){
                    if(josnObject.getString("communityId").equals(communityId)){
                        result.add(josnObject);
                        break;
                    }
                }
            }
        }


       return result;
    }

    /**
     * 小区是否禁止户主添加成员
     * */
    private boolean unableAddUser(String configJson) {
        JSONObject configJsonObj = JSONObject.parseObject(configJson);
        JSONArray services = configJsonObj == null ? null : JSONArray.parseArray(configJsonObj.getString("services"));
        return services != null && services.contains("unableAddUser");
    }

    private List<Map<String, Object>> toMemberList(JSONArray userCells, String userId, UserCellType userCellType) {
        if (CollectionUtils.isEmpty(userCells)) {
            return null;
        }
        return userCells.stream()
                .filter(new FilterSelf(userId))
                .filter(new FilterUserCellType(userCellType))
                .map(new UserCell2MemberFun())
                .collect(toList());
    }




    /**
     * 过滤出其他成员
     * */
    class FilterSelf implements Predicate<Object> {
        String userId;
        FilterSelf(String userId) {
            this.userId = userId;
        }
        @Override
        public boolean test(Object obj) {
            JSONObject userCell = (JSONObject) obj;
            return !userId.equals(userCell.getString("userId"));
        }
    }

    /**
     * 过滤出与类型对应的成员
     * */
    class FilterUserCellType implements Predicate<Object> {
        UserCellType userCellType;
        FilterUserCellType(UserCellType userCellType) {
            this.userCellType = userCellType;
        }
        @Override
        public boolean test(Object obj) {
            JSONObject userCell = (JSONObject) obj;
//            1:MASTER,2:MEMBER,3:TENANT;
            int userCellTypeInt = 0;
            if("MASTER".equals(userCell.get("type"))){
                userCellTypeInt = 1;
            }else if("MEMBER".equals(userCell.get("type"))){
                userCellTypeInt = 2;
            }else if("TENANT".equals(userCell.get("type"))){
                userCellTypeInt = 3;
            }else{
                userCellTypeInt = userCell.getIntValue("type");
            }
            return userCellType == getUserCellType(userCellTypeInt);
        }
    }

    /**
     * 转换成cell
     * */
    class UserCell2CellFun implements Function<Object, Map<String, Object>> {
        @Override
        public Map<String, Object> apply(Object obj) {
            JSONObject userCell = (JSONObject) obj;
            Map<String, Object> data = new HashMap<>();
            data.put("cellId", userCell.get("cellId"));
            data.put("cellName", userCell.get("cellName"));
//            1:MASTER,2:MEMBER,3:TENANT;
            if("MASTER".equals(userCell.get("type"))){
                data.put("type", 1);
            }else if("MEMBER".equals(userCell.get("type"))){
                data.put("type", 2);
            }else if("TENANT".equals(userCell.get("type"))){
                data.put("type", 3);
            }else{
                data.put("type", userCell.getIntValue("type"));
            }

            return data;
        }
    }

    /**
     * 转换成member
     * */
    class UserCell2MemberFun implements Function<Object, Map<String, Object>> {
        @Override
        public Map<String, Object> apply(Object obj) {
            JSONObject userCell = (JSONObject) obj;
            Map<String, Object> member = new HashMap<>();
            member.put("memberId", userCell.get("userId"));
            member.put("member", userCell.get("userLoginphone"));
            member.put("name", userCell.get("userName"));
//            1:MASTER,2:MEMBER,3:TENANT;
            if("MASTER".equals(userCell.get("type"))){
                member.put("type", 1);
            }else if("MEMBER".equals(userCell.get("type"))){
                member.put("type", 2);
            }else if("TENANT".equals(userCell.get("type"))){
                member.put("type", 3);
            }else{
                member.put("type", userCell.getIntValue("type"));
            }
            return member;
        }
    }

}
