package yangtz.cs.liu.dingding.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiUserGetuserinfoRequest;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.request.OapiV2UserGetuserinfoRequest;
import com.dingtalk.api.response.OapiUserGetuserinfoResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.dingtalk.api.response.OapiV2UserGetuserinfoResponse;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SchoolTeacher;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import yangtz.cs.liu.campus.service.impl.teacher.SchoolTeacherServiceImpl;
import yangtz.cs.liu.dingding.utils.AccessTokenUtils;

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

/**
 *
 *  企业内部应用免登
 * @author openapi@dingtalk
 * 2020-11-3
 */
@RestController
@RequestMapping("/dd/user")
public class DdLoginController {

    @Autowired
    private AccessTokenUtils accessTokenUtils;
    @Autowired
    private SysUserServiceImpl sysUserService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private SchoolTeacherServiceImpl schoolTeacherService;

    /**
     *
     * @param code
     * @return
     * ServiceResult
     * 2020-11-3
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public AjaxResult login (@RequestParam("code") String code) {
        AjaxResult ajaxResult = new AjaxResult();
        // 获取access_token，注意正式代码要有异常流处理
        String access_token= accessTokenUtils.getToken();
        // 获取用户信息
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo");
        OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
        request.setCode(code);
        request.setHttpMethod("GET");
        OapiUserGetuserinfoResponse response;
        try {
            response = client.execute(request, access_token);
        } catch (ApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        // 查询得到当前用户的userId
        // 获得到userId之后应用应该处理应用自身的登录会话管理（session）,避免后续的业务交互（前端到应用服务端）每次都要重新获取用户身份，提升用户体验
        String userId = response.getUserid();
        if (StringUtils.isEmpty(userId)){
            throw new ServiceException("免登码已失效，请重新获取");
        }
        //获取用户详细信息
        Map<String, Object> userInfo = getUserInfo(userId, access_token);
        String phone = (String) userInfo.get("phone");
        String unionId = (String) userInfo.get("unionId");
        SchoolTeacher schoolTeacher = schoolTeacherService.selectTeacherByPhone(phone);
        if (StringUtils.isNull(schoolTeacher)){
            throw new ServiceException("未查询到该用户信息");
        }
        Long userId1 = schoolTeacher.getId();
        SysUser sysUser = sysUserService.selectUserById(userId1);
        //更新钉钉用户iid和unionId
        sysUser.setUnionId(unionId);
        schoolTeacherService.updateDdUserId(sysUser, userId);
        String token = loginService.loginNew(sysUser);
        ajaxResult.put(Constants.TOKEN, token);
        return ajaxResult;
    }

    public Map<String,Object> getUserInfo(String userId,String token){
        Map<String,Object> map = new HashMap<>();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
            req.setUserid(userId);
            OapiV2UserGetResponse rsp = client.execute(req, token);
            OapiV2UserGetResponse.UserGetResponse result = rsp.getResult();
            String name = result.getName();
            String phone = result.getMobile();
            String unionId = result.getUnionid();
            map.put("userName",name);
            map.put("phone",phone);
            map.put("unionId",unionId);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return map;
    }
}
