package com.codvision.auth.controller.third;

import com.codvision.auth.entity.ding.DingConfig;
import com.codvision.auth.entity.vo.SysUserVO;
import com.codvision.auth.enums.LoginTypeEnum;
import com.codvision.auth.service.ISysUserService;
import com.codvision.auth.service.third.DingTalkService;
import com.codvision.auth.support.UserContext;
import com.codvision.authcore.bean.SysUserBean;
import com.codvision.commoncore.common.ResponseEntity;
import com.codvision.commoncore.exception.AuthException;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author codvision
 */
@Slf4j
@RestController
@Api(tags = "用户端-普通钉钉管理")
@RequestMapping("/ding")
public class DingController {

    @Resource
    @Lazy
    private DingTalkService dingTalkService;

    @Resource
    private ISysUserService sysUserService;


    @PostMapping("/login")
    @ApiOperation("普通钉钉登陆")
    public ResponseEntity<SysUserBean> handlePostDingLogin(@ApiParam(value = "临时授权码") @RequestParam(value = "code") String code,
                                                           @ApiParam(value = "登陆类型(0-免登 1-扫码登陆)") @RequestParam(value = "loginType") Integer loginType) {
        ResponseEntity<SysUserBean> responseEntity = new ResponseEntity<>();

        OapiV2UserGetResponse rsp;
        try {
            if (LoginTypeEnum.SCAN_LOGIN.getCode().equals(loginType)) {
                rsp = dingTalkService.getUserInfoByScan(code);
            } else {
                rsp = dingTalkService.getUserInfo(code);
            }

            OapiV2UserGetResponse.UserGetResponse result = rsp.getResult();
            SysUserVO user = sysUserService.getByDingTalkUid(result.getUserid());
            if (null == user) {
                throw new AuthException(100001, "无该钉钉用户");
            }

            SysUserBean sysUser = UserContext.set(user);
            user.setToken(sysUser.getToken());
            responseEntity.data(sysUser);
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new AuthException(10000, "钉钉登陆失败");
        }

        return responseEntity.ok();
    }

    @PostMapping("/config")
    @ApiOperation("鉴权")
    public DingConfig config(@RequestParam() String url) {
        return dingTalkService.getConfig(url);
    }

}
