package com.cpop.oam.business.controller.backstage;

import com.cpop.core.base.R;
import com.cpop.oam.business.service.OamWxCpService;
import com.cpop.oam.business.vo.WxCpLoginVo;
import com.cpop.oam.framework.config.wxCp.WxCpConfiguration;
import com.cpop.system.business.vo.LoginUserInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.cp.api.WxCpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author DB
 * @createTime 2023/11/17 9:38
 * @description
 */
@Slf4j
@RestController
@Api(tags = "企业微信相关模块")
@RequestMapping("/backstage/wxCp")
public class BackstageWxCpController {

    @Autowired
    private OamWxCpService oamWxCpService;

    @Value("${wx.cp.oAuth2registerUrl}")
    private String oAuth2registerUrl;

    /**
     * @author LOST.yuan
     * 根据code换取用户信息 
     * @since 14:52 2022/9/7
     * @return {@link R<LoginUserInfoVo>}
     **/
    @GetMapping("/getOauth2Url")
    @ApiOperation("获取oauth2认证链接")
    public R<String> getOauth2Url() {
        WxCpService cpService = WxCpConfiguration.getCpService(1000024);
        String authUrl = cpService.getOauth2Service().buildAuthorizationUrl(oAuth2registerUrl, null, "snsapi_privateinfo");
        return R.ok(authUrl);
    }

    /**
     * @author LOST.yuan
     * @Description 根据code换取用户信息
     * @date 14:52 2022/9/7
     * @return {@link R<LoginUserInfoVo>}
     **/
    @GetMapping("/loginUserInfoByCode")
    @ApiOperation("根据code换取用户信息")
    public R<WxCpLoginVo> loginUserInfoByCode(HttpServletRequest httpServletRequest, @RequestParam("code") String code) {
        WxCpLoginVo loginVo = oamWxCpService.loginUserInfoByCode(httpServletRequest, code);
        return R.ok(loginVo);
    }

    /**
     * @return R<Void>
     * @Description: 同步企业微信部门
     * @Author DB
     * @Date: 2023/5/9 20:47
     */
    @Deprecated
    @PreAuthorize("@aps.hasPermission('*:*:*')")
    @ApiOperation("同步企业微信部门")
    @PostMapping("/syncWxCpDept")
    public R<Void> syncWxCpDept() {
        oamWxCpService.syncWxCpDept();
        return R.ok();
    }

    /**
     * @return R<Void>
     * @Description: 同步企业微信员工
     * @Author DB
     * @Date: 2023/5/9 20:47
     */
    @Deprecated
    @PreAuthorize("@aps.hasPermission('*:*:*')")
    @ApiOperation("同步企业微信员工")
    @PostMapping("/syncWxCpStaff")
    public R<Void> syncWxCpStaff() {
        oamWxCpService.syncWxCpStaff();
        return R.ok();
    }
}
