package com.platform.api;

import com.alibaba.fastjson.JSON;
import com.platform.entity.*;
import com.platform.service.ApiBrandService;
import com.platform.service.ApiUserService;
import com.platform.service.custom.MySysUserBrandService;
import com.platform.service.impl.ZhiHouseService;
import com.platform.utils.CommonDataUtils;
import com.platform.utils.SyncWxSubscribeServiceImpl;
import com.platform.vos.OpenApiRequestVo;
import com.platform.vos.TbUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * @author abnerhou
 * @date 2020/6/16 14:33
 * @desciption
 */
@Api(description = "开放平台回调相关接口")
@Slf4j
@Controller
@RequestMapping("/4dkankan")
public class OpenApiNotifyController {


    @Autowired
    private SyncWxSubscribeServiceImpl wxSubscribeService;

    @Autowired
    private ApiBrandService brandService;

    @Autowired
    private MySysUserBrandService mySysUserBrandService;

    @Autowired
    private ApiUserService apiUserService;
    @Autowired
    private ZhiHouseService zhiHouseService;

    @ApiOperation(value = "接收消息订阅通知")
    @PostMapping(value = "/shop/notify")
    @ResponseBody
    public Result wxSubscribe(@RequestBody @ApiParam(name="开放api通知请求实体",value="传入json格式",required=true) OpenApiRequestVo openApiRequestVo) {

        log.debug("收到open-api的订阅消息回调,参数:{}" , JSON.toJSONString(openApiRequestVo));
        if(null == openApiRequestVo){
            log.warn("收到来自open-api的微信消息订阅通知请求，但是请求体为空");
        }else{
            if(null == openApiRequestVo.getBrandId() || null == openApiRequestVo.getRoomId()){
                return Result.failure("缺失店铺ID或者语音房间ID");
            }
            BrandVo brandVo =  brandService.queryObject(CommonDataUtils.getIntegerWithDefault(openApiRequestVo.getBrandId() , true));
            if(null == brandVo){
                return Result.failure(3019 , "店铺不存在");
            }
            List<SysUserBrand> userIdList = mySysUserBrandService.getBrandBindUserIdList(brandVo.getId());
            if(CollectionUtils.isEmpty(userIdList)){
                return Result.failure(3020 , "当前店铺未绑定带看人员");
            }
            int successCount = 0;
            //获取有带看权限的人的微信openId
            for (SysUserBrand sysUserBrand : userIdList) {
                //有带看权限的人处于空闲
                if(null != sysUserBrand.getIsBusy() && sysUserBrand.getIsBusy().compareTo(0) == 0){
                    //TODO:这里改成要轮询有空的人，这期先不做，这里占个坑
                }
                TbUser sysUserEntity = zhiHouseService.getByUserId(sysUserBrand.getUserId());
                if(null == sysUserEntity){
                    log.error("店铺管理员无效了");
                    continue;
                }
                if(StringUtils.isBlank(sysUserEntity.getPhone())){
                    log.error("店铺管理员缺失手机号");
                    continue;
                }
                UserVo userVo = apiUserService.queryByMobile(sysUserEntity.getPhone());
                if(null == userVo || StringUtils.isBlank(userVo.getWeixin_openid())){
                    //没有手机号或者openId直接跳过
                    log.error("店铺管理员无法通过手机号获取或者缺失openId");
                    continue;
                }
                Map<String, Object> content = new HashMap<>();
                content.put("number1", openApiRequestVo.getRoomId());
                content.put("number2", openApiRequestVo.getBrandId());
                String page = "pages/webview/index?roomId=" + openApiRequestVo.getRoomId() +  "&type=1&id=" + openApiRequestVo.getBrandId();
                log.info("跳转的链接为:{}", page);
                Map<String, Object> result = wxSubscribeService.executeAsync(content, page, userVo.getWeixin_openid());
                if (null != result && result.containsKey("errcode")) {
                    int errorCode = (int) result.get("errcode");
                    String errmsg = (String) result.get("errmsg");
                    log.info("微信消息订阅完成，返回码={},返回描述={}", errorCode, errmsg);
                    if (errorCode == 0) {
                        successCount += 1;
                    }
                }
            }
            if(successCount <=0){
                return Result.failure("发送订阅消息失败");
            }

        }
        return Result.success("推送消息成功成功",null);
    }


}
