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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.module.tcm.biz.service.impl.StartPlatformTokenService;
import com.yeejoin.amos.boot.module.tcm.biz.utils.DesUtil;
import com.yeejoin.amos.boot.module.tcm.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;
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 java.util.*;
import java.util.stream.Collectors;

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

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    DataDictionaryServiceImpl iDataDictionaryService;

    @Value("${org.filter.group.seq}")
    private Long groupSeq;

    @Autowired
    StartPlatformTokenService platformTokenService;

    @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("公司同步消息解析失败");
        }
        platformTokenService.setRequestContext();
        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());
        FeignClientResult<CompanyModel> cResult = Privilege.companyClient.seleteOne(object.getLong("sequence_nbr"));
        // FeignClientResult<Collection<CompanyModel>> cResult =
        // Privilege.companyClient.queryAgencyTree(null);
        String useCode = object.getString("use_code");
        // if (useCode == null || !isUse(useCode, cResult.getResult())) {
        if (cResult.getResult() == null) {
            CompanyModel companyModel = new CompanyModel();
            companyModel.setCompanyName(object.getString("use_unit"));
            companyModel.setParentId(0L);
            companyModel.setLevel("company");
            String unitTypes = object.getString("unit_type");
            companyModel.setCompanyType(unitTypes);
            // companyModel.setSequenceNbr(object.getLong("sequence_nbr"));
            companyModel.setCompanyCode(useCode);
            if (object.getString("supervise_org_code") != null) {
                FeignClientResult<HashMap<String, Object>> result = Privilege.companyClient
                        .queryByOrgcode(object.getString("supervise_org_code"));
                // JSONObject parent =
                // JSONObject.parseObject(JSONObject.toJSONString(result.getResult()));
                if (result.getResult().get("sequenceNbr") != null) {
                    companyModel.setParentId(Long.valueOf(result.getResult().get("sequenceNbr").toString()));
                }
            }
            FeignClientResult<CompanyModel> createResult = Privilege.companyClient.create(companyModel);
            Long companySqr = createResult.getResult().getSequenceNbr();
            String unitCode = object.getString("use_code");
            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) {
                FeignClientResult<List<RoleModel>> roleListResult = Privilege.roleClient.queryRoleList(null, null);
                List<RoleModel> allRoleList = roleListResult.getResult();
                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");
                String[] unitTypeArray = unitTypes.split(",");
                List<String> unitTypeList = Arrays.asList(unitTypeArray);
                Set<String> roleNameSet = new HashSet<>();
                Set<String> appCodesSet = new HashSet<>();
                List<RoleModel> userRoleList = new ArrayList<>();
                List<Long> roleIds = new ArrayList<>();
                Map<Long, List<Long>> roleSeqMap = new HashMap<>();
                for (String unitTypeStr : unitTypeList) {
                    DataDictionary unitType = iDataDictionaryService
                            .getOne(new LambdaQueryWrapper<DataDictionary>().eq(DataDictionary::getName, unitTypeStr));
                    String appCode = unitType.getTypeDesc() != null ? unitType.getTypeDesc() : "";
                    String[] appCodes = appCode.split(",");
                    Collections.addAll(appCodesSet, appCodes);
                    roleNameSet.add(unitType.getName());
                    userRoleList = allRoleList.stream().filter(r -> r.getRoleName().equals(unitType.getName()))
                            .collect(Collectors.toList());
                    for (RoleModel r : userRoleList) {
                        if (!roleIds.contains(r.getSequenceNbr())) {
                            roleIds.add(r.getSequenceNbr());
                        }
                    }
                    roleSeqMap.put(companySqr, roleIds);
                }
                userModel.setAppCodes(new ArrayList<>(appCodesSet));
                userModel.setOrgRoleSeqs(roleSeqMap);
                FeignClientResult<AgencyUserModel> userResult = Privilege.agencyUserClient.create(userModel);
                String[] userIds = {userResult.getResult().getUserId()};
//				if (groupSeq != null) {
//					Privilege.groupUserClient.create(groupSeq, Arrays.asList(userIds));
//				}
            }
        }
    }

    private boolean isUse(String useCode, Collection<CompanyModel> companys) {
        for (Object obj : companys) {
            String json = JSONObject.toJSONString(obj);
            CompanyModel companyMode = JSONObject.toJavaObject(JSONObject.parseObject(json), CompanyModel.class);
            if (useCode.equals(companyMode.getCompanyCode())) {
                return true;
            } else if (companyMode.getChildren() != null) {
                return isUse(useCode, companyMode.getChildren());
            }
        }
        return false;
    }
}
