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

import com.usoftchina.qywx.sdk.AddrBookSdk;
import com.usoftchina.qywx.sdk.dto.GetUserInfoResp;
import com.usoftchina.qywx.sdk.dto.GetUserResp;
import com.usoftchina.uas.office.entity.DataCenter;
import com.usoftchina.uas.office.jdbc.DataSourceHolder;
import com.usoftchina.uas.office.qywx.entity.Employee;
import com.usoftchina.uas.office.qywx.manage.entity.QywxAgent;
import com.usoftchina.uas.office.qywx.manage.service.QywxAgentService;
import com.usoftchina.uas.office.qywx.service.UasEmployeeService;
import com.usoftchina.uas.office.service.DataCenterService;
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/15
 */
@Controller
public class QywxAuthController {

    @Autowired
    private AddrBookSdk addrBookSdk;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UasEmployeeService employeeService;

    @Autowired
    private QywxAgentService agentService;

    /**
     * 获取身份登录
     *
     * @param code   授权码
     * @param agent  应用编号
     * @param master uas账套名 不指定就进默认账套
     * @param url    验证通过后跳转的具体页面 base64加密的
     */
    @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");
        }
        if (!addrBookSdk.enabled()) {
            return new ModelAndView("/error");
        }
        GetUserInfoResp infoResp = addrBookSdk.getUserInfo(agent, code);
        try {
            DataSourceHolder.set(dataCenter);
            Employee employee = employeeService.getByQywx(infoResp.getUserId());
            if (null == employee) {
                GetUserResp userResp = addrBookSdk.getUser(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_qywx(infoResp.getUserId());
                    employeeService.setQywx(employee);
                }
            }
            if (null == employee) {
                return new ModelAndView("/error");
            }
            QywxAgent 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();
        }
    }
}
