package com.usoftchina.uas.office.dingtalk.controller;

import com.dingtalk.api.response.OapiUserGetResponse;
import com.dingtalk.api.response.OapiUserGetuserinfoResponse;
import com.usoftchina.dingtalk.sdk.AddrBookSdk;
import com.usoftchina.uas.office.dingtalk.entity.Employee;
import com.usoftchina.uas.office.dingtalk.manage.entity.DingTalkAgent;
import com.usoftchina.uas.office.dingtalk.manage.service.DingTalkAgentService;
import com.usoftchina.uas.office.dingtalk.service.UasEmployeeService;
import com.usoftchina.uas.office.entity.DataCenter;
import com.usoftchina.uas.office.jdbc.DataSourceHolder;
import com.usoftchina.uas.office.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;

/**
 * @author yingp
 * @date 2020/2/18
 */
@Controller
public class DingTalkAuthController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AddrBookSdk userSdk;

    @Autowired
    private UasEmployeeService employeeService;

    @Autowired
    private DingTalkAgentService agentService;

    @RequestMapping(value = "/api/authorize")
    public ModelAndView authorize(@RequestParam(value = "code") String code, @RequestParam(value = "agent") String agent,
                                  @RequestParam(value = "master", required = false) String master,
                                  @RequestParam(value = "url") String url, HttpServletResponse response) throws IOException {
        DataCenter dataCenter = DataCenter.INSTANCE;
        if (null == dataCenter) {
            return new ModelAndView("/error");
        }
        OapiUserGetuserinfoResponse infoResp = userSdk.getUserInfo(agent, code);
        try {
            DataSourceHolder.set(dataCenter);
            Employee employee = employeeService.getByDingUserId(infoResp.getUserid());
            if (null == employee) {
                OapiUserGetResponse userResp = userSdk.getUser(agent, infoResp.getUserid());
                if (StringUtils.hasText(userResp.getMobile())) {
                    employee = employeeService.getByMobile(userResp.getMobile());
                }
                if (null == employee && StringUtils.hasText(userResp.getEmail())) {
                    employee = employeeService.getByEmail(userResp.getEmail());
                }
                if (null != employee) {
                    employee.setEm_ding(infoResp.getUserid());
                    employeeService.setDingUserId(employee);
                }
            }
            if (null == employee) {
                return new ModelAndView("/error");
            }
            DingTalkAgent uasAgent = agentService.findByCode("Uas");
            redisTemplate.opsForValue().set(code, employee.getEm_id(), Duration.ofMinutes(1));
            response.sendRedirect(String.format("%sopen/authorize.action?token=%s&master=%s&url=%s",
                    uasAgent.getOuterUrl(), code, master == null ? "" : master, url));
            return null;
        } finally {
            DataSourceHolder.clear();
        }
    }
}
