package com.yeejoin.amos.boot.module.tzs.biz.listener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.component.emq.EmqxListener;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.exception.BaseException;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.tzs.biz.utils.DesUtil;
import com.yeejoin.amos.boot.module.tzs.biz.utils.RedisUtil;
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.RoleModel;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description: mqtt监听服务
 * @Author: duanwei
 * @Date: 2020/9/15
 */
@Component
@Slf4j
public class CarcylUnitInspectMqTtlListener extends EmqxListener {
	@Value("${amos.secret.key}")
	String secretKey;

	@Value("${admin.product}")
	String product;

	@Value("${admin.appkey}")
	String appkey;
	@Autowired
	RedisUtil redisUtil;

	@Value("${org.filter.group.seq}")
	private Long groupSeq;
	
	@Override 
	public void processMessage(String topic, MqttMessage message) throws Exception {
		System.out.println(message);
		JSONObject object = null;
		try {
			object = JSONObject.parseObject(message.toString());
		} catch (Exception e) {
			throw new Exception("公司同步消息解析失败");
		}
		RequestContext.setAppKey(appkey);
		RequestContext.setProduct(product);
		RequestContext.setToken(String.valueOf(redisUtil.get("platform_token")));
		FeignClientResult<List<ApplicationModel>> aResult = Privilege.applicationClient.queryAgencyApplications();
		List<ApplicationModel> aList = aResult.getResult();
		List<String> appCodes = aList.stream().filter(i -> "监管端,企业端".indexOf(i.getAppName()) != -1)
				.map(i -> i.getAppCode()).collect(Collectors.toList());
        String uuid = object.getString("id");
        Long id = Long.valueOf(uuid.replaceAll("-","").hashCode());
        
		FeignClientResult<CompanyModel> cResult = Privilege.companyClient.seleteOne(id);
		if (cResult.getResult() == null) {
			CompanyModel companyModel = new CompanyModel();
			companyModel.setCompanyName(object.getString("inspect_unit_name"));
			companyModel.setParentId(0L);
			companyModel.setLevel("company");
			companyModel.setSequenceNbr(id);
			companyModel.setCompanyCode(object.getString("org_unit_name"));
			companyModel.setCompanyType("检验单位");
			Privilege.companyClient.create(companyModel);
		}

		String unitCode = object.getString("org_unit_name");
		if (unitCode == null || unitCode.length() < 6) {
			log.error("公司统一信用代码长度不够6位");
			throw new Exception("公司统一信用代码长度不够6位");
		}
		String userName = unitCode.substring(unitCode.length() - 6, unitCode.length());
		FeignClientResult<AgencyUserModel> uResult = Privilege.agencyUserClient.queryByUserName(userName);
		if (uResult.getResult() == null) {
			AgencyUserModel userModel = new AgencyUserModel();
			userModel.setUserName(userName);
			userModel.setRealName(userName);
			userModel.setPassword(DesUtil.encode(userName, secretKey));
			userModel.setRePassword(DesUtil.encode(userName, secretKey));
			// userModel.setMobile(vo.getPhoneNo());
			userModel.setLockStatus("UNLOCK");
			FeignClientResult<List<RoleModel>> list = Privilege.roleClient.queryRoleList("检验单位", "admin");
			Map<Long, List<Long>> orgRoles = new HashMap<>();
			List<Long> roleIds = new ArrayList<>();
			roleIds.add(list.getResult().get(0).getSequenceNbr());
			orgRoles.put(id, roleIds);
			userModel.setAppCodes(appCodes);
			userModel.setOrgRoleSeqs(orgRoles);
			FeignClientResult<AgencyUserModel> userResult  =Privilege.agencyUserClient.create(userModel);
			String[] userIds = {userResult.getResult().getUserId()};
			if (groupSeq != null) {
				Privilege.groupUserClient.create(groupSeq, Arrays.asList(userIds));
			}
		}
	}
}
