package com.yeejoin.amos.api.openapi.face.service;


import cn.hutool.core.map.MapUtil;
import com.yeejoin.amos.api.openapi.constant.Constant;
import com.yeejoin.amos.api.openapi.face.model.BizTokenModel;
import com.yeejoin.amos.api.openapi.face.model.OpenapiBizTokenModel;
import com.yeejoin.amos.api.openapi.face.orm.dao.OpenapiBizTokenMapper;
import com.yeejoin.amos.api.openapi.face.orm.entity.OpenapiBizToken;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import com.yeejoin.amos.component.robot.SystemUserInfo;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.IdPasswordAuthModel;
import com.yeejoin.amos.feign.privilege.util.DesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.component.cache.Redis;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;

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


/**
 * 
 * <pre>
 * 服务类
 * </pre>
 *
 * @author gwb
 * @version $Id: OpenapiLogService.java, v 0.1 2021年11月10日 下午5:55:31 gwb Exp $
 */
@Component
public class OpenapiBizTokenService extends BaseService<OpenapiBizTokenModel, OpenapiBizToken, OpenapiBizTokenMapper> {
    @Autowired
    private RedisTemplate redisTemplate;

	@Autowired
	AmosRequestContext amosRequestContext;

	@Autowired
	SystemUserInfo systemUserInfo;

	public static final String DEFAULT_PASSWORD = "a1234560";

    public List<String> getServiceList() {
    	return baseMapper.getServiceList();
	}
    
	public String getByAppId(String appId) {
		// 先从iot_openapi_biz_token表中查询（手动创建不需要在平台注册的对接方的appId信息），如果未找到则从业务库企业表查询
		OpenapiBizToken openapiBizToken = baseMapper.getByAppId(appId);
		Map<String, String> unitInfo = MapUtil.newHashMap();
		if (!ValidationUtil.isEmpty(openapiBizToken)) {
			unitInfo.put("use_unit_code", openapiBizToken.getApiCompanyCode());
			unitInfo.put("use_unit", openapiBizToken.getApiCompanyName());
		}
		if (ValidationUtil.isEmpty(unitInfo)) {
			unitInfo = baseMapper.queryUnitInfoByAppId(appId);
		}
		if (ValidationUtil.isEmpty(unitInfo)) {
			throw new RuntimeException("未找到对接单位信息");
		}
		String unitCode = MapUtil.getStr(unitInfo, "use_unit_code");
		String unitName = MapUtil.getStr(unitInfo, "use_unit");

		IdPasswordAuthModel idPasswordAuthModel = new IdPasswordAuthModel();
		// 使用机器人登录：采用不同的product获取token
		idPasswordAuthModel.setLoginId(amosRequestContext.getUserName());
		idPasswordAuthModel.setPassword(DesUtil.encode(systemUserInfo.getPassword(), Constant.PASSWORD_ENCODE_KEY));
		BizTokenModel bizTokenModel = new BizTokenModel();
		bizTokenModel.setAppId(appId);
		bizTokenModel.setProduct(appId);

		RequestContext.setProduct(appId);
	    RequestContext.setAppKey(bizTokenModel.getAppKey());
		FeignClientResult<HashMap<String, Object>> responseModel = Privilege.authClient.idpassword(idPasswordAuthModel);
		HashMap<String, Object> authModel = responseModel.getResult();
		String token = (String) authModel.get("token");
		bizTokenModel.setToken(token);
		RequestContext.setToken(token);
		// 调整为从业务表根据appId查询单位信息
		bizTokenModel.setApiCompanyCode(unitCode);
		bizTokenModel.setApiCompanyName(unitName);
		String tokenKey = Redis.genKey(Constant.TOKEN_PREFIX, token);
		this.redisTemplate.opsForValue().set(tokenKey, bizTokenModel);
		return token;
	}


//	private ObjectMapper objectMapper = new ObjectMapper();
//    /**
//     * 分页查询
//     */
//    @SuppressWarnings("unchecked")
//	public Page<OpenapiLogModel> queryForOpenserviceOperateLogPage(Page page, String agencyCode, @Condition(Operator.like) String methodLabel) throws Exception {
//    	
//    	Page<OpenapiLogModel> openserviceOperateLogModelPage = this.queryForPage(page, "CREATE_TIME", false,agencyCode, methodLabel);
//    	List<OpenapiLogModel> openserviceOperateLogModelList = openserviceOperateLogModelPage.getRecords();
//    	Map<String, AgencyUserModel> userMap = new HashMap<String, AgencyUserModel>();
//    	for (OpenapiLogModel openserviceOperateLogModel : openserviceOperateLogModelList)
//		{
//    		//填充操作人信息
//    		AgencyUserModel agencyUserModel = userMap.get(openserviceOperateLogModel.getRecUserId());
//    		if (ValidationUtil.isEmpty(agencyUserModel))
//			{
//    			openserviceOperateLogModel.setUserName(openserviceOperateLogModel.getRecUserId());
//				openserviceOperateLogModel.setUserRealName(openserviceOperateLogModel.getRecUserId());
//    			FeignClientResult<AgencyUserModel> responseModel = Privilege.agencyUserClient.queryByUserId(openserviceOperateLogModel.getRecUserId());
//    			AgencyUserModel userModel = responseModel.getResult();
//    			if (!ValidationUtil.isEmpty(userModel))
//				{
//    				userMap.put(openserviceOperateLogModel.getRecUserId(), userModel);
//    				openserviceOperateLogModel.setUserName(userModel.getUserName());
//    				openserviceOperateLogModel.setUserRealName(userModel.getRealName());
//				}
//			}else 
//			{
//				openserviceOperateLogModel.setUserName(agencyUserModel.getUserName());
//				openserviceOperateLogModel.setUserRealName(agencyUserModel.getRealName());
//			}
//    		//填充操作状态
//    		String result = openserviceOperateLogModel.getResult();
//			Map<String, Object> mapJson  = objectMapper.readValue(result,Map.class);
//            String status = mapJson.get("status").toString();
//            if (status.equals("200"))
//			{
//            	openserviceOperateLogModel.setResultStatus("成功");
//			}else 
//			{
//				openserviceOperateLogModel.setResultStatus("失败");
//			}
//		}
//    	openserviceOperateLogModelPage.setRecords(openserviceOperateLogModelList);
//        return openserviceOperateLogModelPage;
//    }
//
//    /**
//     * 列表查询 示例
//     */
//    public List<OpenapiLogModel> queryForOpenserviceOperateLogList(String agencyCode) throws Exception {
//        return this.queryForList("", false, agencyCode);
//    }


}
