package com.yeejoin.amos.fas.business.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.typroject.tyboot.core.foundation.context.RequestContext;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.bo.CompanyBo;
import com.yeejoin.amos.boot.biz.common.bo.DepartmentBo;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.bo.RoleBo;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.fas.business.feign.PrivilegeFeign;
import com.yeejoin.amos.fas.business.feign.RemoteSecurityService;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.feign.privilege.model.IdPasswordAuthModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.amos.feign.privilege.util.DesUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @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 PrivilegeFeign privilegeFeign;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RemoteSecurityService remoteSecurityService;

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

    @Value("${security.productWeb}")
    private String product;

    @Value("${security.appKey}")
    private String appKey;

    @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 = (String) request.getHeader("token");
        ReginParams reginParams;
        reginParams = JSON.parseObject(redisTemplate.opsForValue().get(buildKey(userId, token)), ReginParams.class);
        if(reginParams == null){
            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");
            privilegeFeign.warrant(appKey, product, amosToken);
            RequestContext.setToken(amosToken);
            RequestContext.setProduct(product);
            RequestContext.setAppKey(appKey);

            AgencyUserModel userModel  =  (AgencyUserModel) Privilege.agencyUserClient.getme().getResult();
            CompanyModel companyModel = userModel.getCompanys().get(0);
            List<DepartmentModel> deptList = remoteSecurityService.getDepartmentTreeByCompanyId(amosToken, product, appKey, companyModel.getSequenceNbr().toString());
            if(deptList.size() > 0){
                CompanyBo companyBo = convertCompanyModelToBo(companyModel);
                DepartmentBo departmentBo = convertDepartmentModelToBo(deptList.get(0));
                reginParams.setDepartment(departmentBo);
                reginParams.setCompany(companyBo);
            }
            reginParams.setToken(amosToken);
            reginParams.setUserModel(userModel);
            redisTemplate.opsForValue().set(buildKey(userId, token), JSONObject.toJSONString(reginParams));
            redisTemplate.opsForValue().set(buildKey(userId, amosToken), JSONObject.toJSONString(reginParams));
        }
        return reginParams;
    }
    private DepartmentBo convertDepartmentModelToBo(DepartmentModel departmentModel){
        DepartmentBo departmentBo = new DepartmentBo();
        if(departmentModel != null) {
            departmentBo.setCompanySeq(departmentModel.getCompanySeq());
            departmentBo.setDepartmentDesc(departmentModel.getDepartmentDesc());
            departmentBo.setDepartmentName(departmentModel.getDepartmentName());
            departmentBo.setLevel(departmentModel.getLevel());
            departmentBo.setOrgCode(departmentModel.getOrgCode());
            departmentBo.setParentId(departmentModel.getParentId());
            departmentBo.setDeptOrgCode(departmentModel.getDeptOrgCode());
            departmentBo.setSequenceNbr(departmentModel.getSequenceNbr());
        }
        return departmentBo;
    }

    /**
     * 	Model 转 Bo
     */
    private CompanyBo convertCompanyModelToBo(CompanyModel companyModel){
        CompanyBo companyBo = new CompanyBo();
        if(companyModel != null) {
            companyBo.setAddress(companyModel.getAddress());
            companyBo.setCompanyName(companyModel.getCompanyName());
            companyBo.setCompanyOrgCode(companyModel.getCompanyOrgCode());
            companyBo.setEmail(companyModel.getEmail());
            companyBo.setLandlinePhone(companyModel.getLandlinePhone());
            companyBo.setLongitude(companyModel.getLongitude());
            companyBo.setLatitude(companyModel.getLatitude());
            companyBo.setLevel(companyModel.getLevel());
            companyBo.setOrgCode(companyModel.getOrgCode());
            companyBo.setSequenceNbr(companyModel.getSequenceNbr());
            companyBo.setParentId(companyModel.getParentId());
        }
        return companyBo;
    }

    private RoleBo convertRoleModelToBo(RoleModel roleModel) {
        RoleBo roleBo = new RoleBo();
        if(roleModel != null){
            roleBo.setRoleName(roleModel.getRoleName());
            roleBo.setRoleType(roleModel.getRoleType());
            roleBo.setSequenceNbr(roleModel.getSequenceNbr());
        }
        return roleBo;
    }

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

    }
}
