package com.codvision.auth.controller.third;

import com.codvision.auth.entity.ding.gov.GovUserInfo;
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.GovDingService;
import com.codvision.auth.support.UserContext;
import com.codvision.authcore.bean.SysUserBean;
import com.codvision.commoncore.common.ResponseEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
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 hxl
 */
@Slf4j
@RestController
@RequestMapping("/govDing")
@Api(tags = "用户端-专有钉钉（浙政钉）管理")
public class GovDingController {

    @Resource
    @Lazy
    private GovDingService govDingService;

    @Resource
    private ISysUserService sysUserService;

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

        GovUserInfo userInfo;
        if (LoginTypeEnum.SCAN_LOGIN.getCode().equals(loginType)) {
            userInfo = govDingService.getUserInfoByScan(code);
        } else {
            userInfo = govDingService.getUserInfo(code);
        }

        String accountId = userInfo.getAccountId().toString();
        SysUserVO user = sysUserService.getByZzdId(accountId);
        if (null == user) {
            return responseEntity.error(100001, "无该浙政钉用户");
        }

        SysUserBean sysUser = UserContext.set(user);
        user.setToken(sysUser.getToken());
        responseEntity.data(sysUser);

        return responseEntity.ok().data(sysUser);
    }

    @PostMapping("/getTicket")
    @ApiOperation("鉴权")
    public ResponseEntity<String> getTicket() {
        return new ResponseEntity<String>().data(govDingService.getTicket());
    }
}
