package com.yeejoin.amos.boot.module.cylinder.biz.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.component.feign.config.TokenOperation;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.ApplicationModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.IdPasswordAuthModel;
import com.yeejoin.amos.feign.privilege.util.DesUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zjw
 * @date 2020-03-30
 */

@RestController
@RequestMapping(value = "/api/loginBytoken")
@Api(tags = "通过userName登录Api")
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${outSystem.user.password}")
    private String password;

    @Value("${amos.system.user.product}")
    private String product;

    @Value("${amos.system.user.app-key}")
    private String appKey;



    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @ApiOperation(value = "通过userId登录",  notes = "查询设备指标")
    @GetMapping(value = "/{userId}")
    synchronized  public ReginParams getBindEquipment(@PathVariable("userId") String userId) throws Exception {

        if (ObjectUtils.isEmpty(userId)){
            throw new Exception("用户信息不存在");
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        String token = "wxxcxdl";
        ReginParams reginParams;
        reginParams = JSON.parseObject(redisTemplate.opsForValue().get(buildKey(userId, token)), ReginParams.class);
        if(reginParams == null){
            reginParams = getLogin(userId, token);
        }else{
            RequestContext.setProduct(product);
            if (!TokenOperation.refresh(reginParams.getToken())) {
                reginParams = getLogin(userId, token);
            }
        }
        return reginParams;
    }


    private ReginParams getLogin(String userId, String token) throws Exception{
        ReginParams reginParams = new ReginParams();
        IdPasswordAuthModel  dPasswordAuthModel = new IdPasswordAuthModel();
        dPasswordAuthModel.setLoginId(userId);
        dPasswordAuthModel.setPassword(DesUtil.encode(password, "qaz"));
        RequestContext.setProduct(product);
        FeignClientResult feignClientResult = Privilege.authClient.idpassword(dPasswordAuthModel);
        if (ObjectUtils.isEmpty(feignClientResult.getResult())){
            throw new Exception("缺失登录信息");
        }
        // 调用平台授权接口
        Map<String ,String > re = (Map<String, String>) feignClientResult.getResult();
        String amosToken = re.get("token");

        logger.info("应用授权开始======================================"+amosToken);
        RequestContext.setToken(amosToken);
        RequestContext.setProduct(product);
        RequestContext.setAppKey(appKey);

        List<ApplicationModel>  fd = Privilege.applicationClient.queryUserService().getResult();

        logger.info("应用授权结束======================================"+JSON.toJSONString(fd)+amosToken);

        AgencyUserModel userModel  =  (AgencyUserModel) Privilege.agencyUserClient.getme().getResult();
        CompanyModel companyModel = userModel.getCompanys().get(0);

        reginParams.setToken(amosToken);
        reginParams.setUserModel(userModel);
        redisTemplate.opsForValue().set(buildKey(userId, token), JSONObject.toJSONString(reginParams),28, TimeUnit.DAYS);
        return reginParams;
    }


    private String buildKey(String userId, String token) {
        return "region_" + userId + "_" + token;
    }
}
