package com.bohuikeji.delivery.backstage.controller.api.courier;

import com.alibaba.fastjson.JSONObject;
import com.bohuikeji.delivery.backstage.constants.WxAppEm;
import com.bohuikeji.delivery.backstage.entity.wx.TWxUser;
import com.bohuikeji.delivery.backstage.service.IWxUserService;
import com.bohuikeji.delivery.backstage.util.WxUtils;
import com.bohuikeji.frame.module.admin.base.ApiController;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * @author 孙劲辉
 */
@Slf4j
@Api(tags = {"派送员微信相关业务类"})
@RestController
@RequestMapping("/api/v2/courier/wx")
@RequiredArgsConstructor
public class CourierWxV2Api extends ApiController {

    final IWxUserService wxUserService;

    @ApiOperation(value = "派送员绑定微信小程序",notes = "该接口用于派送员使用账号密码或短信验证码等传统登录方式完成登录后，在微信小程序端还需要绑定小程序，以便接受消息通知。<br>微信登录凭证Code获取参见：https://uniapp.dcloud.io/api/plugins/login?id=login")
    @GetMapping("/mp/binding")
    @ApiImplicitParams({
            @ApiImplicitParam(name="code",value="微信登录凭证Code",dataType="String",example="071X0cll2XwVu743gMll23ImeE1X0clS", paramType = "query",required = true)})
    public APIEntity buildMp(@RequestAttribute("JwtUserId") Integer id,String code){
        WxAppEm app= WxAppEm.MP_COURIER;
        TWxUser wxUser=wxUserService.getUserByType(id,WxAppEm.WX_USER_TYPE_COURIER,app);
        if (wxUser!=null){
            return APIEntity.success();
        }
        wxUser=new TWxUser();
        JSONObject res=WxUtils.getCodeLoginInfo(code, app);
        wxUser.setUserType(WxAppEm.WX_USER_TYPE_COURIER);
        wxUser.setUserId(Long.valueOf(id));
        wxUser.setWxAppType(app.getType());
        wxUser.setWxAppId(app.getAppId());
        wxUser.setWxAppName(app.getName());
        wxUser.setWxUserOpenid(res.getString("openid"));
        wxUser.setWxUserUnionid(res.getString("unionid"));
        wxUser.setWxUserSessionkey(res.getString("session_key"));
        wxUserService.saveOrUpdate(wxUser);
        return APIEntity.success();
    }
    @ApiOperation(value = "获取骑手公众号网页授权链接",notes = "返回一个链接地址，请使用web-view组件在微信内打开<br>待处理完成后跳转到小程序指定的页面")
    @GetMapping(value = "/courier/gzh/oauth/url")
    public APIEntity<String> getGzhOauthUrl(
            @RequestAttribute("JwtUserId") Integer id){
        return APIEntity.success(wxUserService.getGzhAutoUrl(id,WxAppEm.WX_USER_TYPE_COURIER,"/open/wx/follow",WxAppEm.GZH_TCJS));
    }

    /**
     * 是否绑定公众号
     * @return
     */
    @GetMapping(value = "/courier/gzh/is/build")
    public APIEntity isBindGZh(@RequestAttribute("JwtUserId") Integer id){
        TWxUser user=wxUserService.getUserByType(id,WxAppEm.WX_USER_TYPE_COURIER,WxAppEm.GZH_TCJS);
        if (user!=null){
            return APIEntity.success(true);
        }
        return APIEntity.success(false);
    }
}
