package cn.myapps.runtime.detail.controller;

import cn.myapps.authtime.common.service.AuthTimeServiceManager;
import cn.myapps.authtime.domain.model.DomainVO;
import cn.myapps.authtime.domain.service.DomainProcess;
import cn.myapps.authtime.user.model.UserVO;
import cn.myapps.authtime.user.service.UserProcess;
import cn.myapps.base.web.WebUser;
import cn.myapps.common.controller.Resource;
import cn.myapps.common.util.Security;
import cn.myapps.common.util.StringUtil;
import cn.myapps.runtime.common.controller.AbstractRuntimeController;
import cn.myapps.util.sequence.Sequence;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;

/**
 * 系统设置
 *
 */
@Api(tags = "系统设置模块")
@RestController
@RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class DetailController extends AbstractRuntimeController {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;
    /**
     * 系统设置跳转
     * @param userid 用户id
     * @return
     * @throws Exception
     */
    @GetMapping("/runtime/{userid}/detail")
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "系统设置跳转", notes = "系统设置跳转")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userid",value = "用户id",required = true,paramType = "path",dataType = "string")
    })
    public Resource sendDetailUrl(@PathVariable String userid) throws Exception{
        //获取当前用户
        WebUser user = AuthTimeServiceManager.getWebUser(request);
        //判断是否部门管理员
        if(user.isDepartmentUser()){
        	AuthTimeServiceManager.setAdminUser(user,request.getSession());
            String token = Security.getToken(user.getId());
            // 存放到cookie
            Cookie cookie = new Cookie(Security.ADMIN_TOKEN, token);
//    		cookie.setHttpOnly(true);//调试方便，先注释
            cookie.setPath("/");

            response.addCookie(cookie);
        }
        String url = request.getContextPath()+"/domain/index.html#/main";
        return success("ok",url);


    }

    /**
     * 获取一个新数列
     */
    @GetMapping("/runtime/sequence")
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = " 获取一个新数列", notes = " 获取一个新数列")
    public Resource getSequence() throws Exception{
        String result = Sequence.getUUID();
        return success("ok", result);
    }

    /**
     * 获取前台用户accessToken
     */
    @GetMapping("/runtime/secrets/{secret}/accessToken")
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = " 获取前台用户accessToken", notes = " 获取前台用户accessToken")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "secret",value = "secret key",required = true,paramType = "path",dataType = "string"),
        @ApiImplicitParam(name = "loginNo",value = "用户账号",required = true,paramType = "query",dataType = "string")
    })
    public Resource getAccessToken(@PathVariable String secret, @RequestParam String loginNo) throws Exception{
        UserProcess userProcess = AuthTimeServiceManager.userRuntimeService();
        DomainProcess domainProcess = AuthTimeServiceManager.domainRuntimeService();
        Collection<DomainVO> domains = domainProcess.getAllDomain();
        for (DomainVO domainVO : domains) {
            if(!StringUtil.isBlank(domainVO.getSecret()) && domainVO.getSecret().equals(secret)){
                UserVO userVO = userProcess.getUserByLoginno(loginNo, domainVO.getId());
                if(userVO != null){
                    String accessToken = Security.getToken(userVO.getId());
                    return success("ok", accessToken);
                }
            }
        }
        return error(500, "获取失败", null);
    }
}
