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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.tzs.api.dto.TzBaseEnterpriseInfoDto;
import com.yeejoin.amos.boot.module.tzs.api.entity.TzBaseEnterpriseInfo;
import com.yeejoin.amos.boot.module.tzs.api.service.ITzBaseEnterpriseInfoService;
import com.yeejoin.amos.boot.module.tzs.biz.service.impl.TzBaseEnterpriseInfoServiceImpl;
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;
import org.bouncycastle.pqc.math.linearalgebra.PolynomialRingGF2;
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.utils.ValidationUtil;

import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class PrivilegeCompanyUpdateAddListener extends EmqxListener {

    @Autowired
    TzBaseEnterpriseInfoServiceImpl tzBaseEnterpriseInfoService;

    @Autowired
    RedisUtil redisUtil;

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

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

    @Override
    public void processMessage(String s, 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")));


        Collection<CompanyModel> companyModels = Privilege.companyClient.queryAgencyTree(null).getResult();
        Map<String , CompanyModel> companyMap = new HashMap<>();
        getCompanyInfoMap(companyModels,companyMap);

        //判断库中company是否重复
        CompanyModel companyPrivilegeModel = Privilege.companyClient.seleteOne(Long.valueOf(object.getString("sequence_nbr"))).getResult();


        TzBaseEnterpriseInfo tzBaseEnterprisePrivilegeInfo = tzBaseEnterpriseInfoService.getById(object.getLong("sequence_nbr"));

        CompanyModel companyModel = new CompanyModel();
        TzBaseEnterpriseInfo tzBaseEnterpriseInfo = new TzBaseEnterpriseInfo();

        tzBaseEnterpriseInfo.setSequenceNbr(object.getLong("sequence_nbr"));
        tzBaseEnterpriseInfo.setAddress(object.getString("reg_address"));
        tzBaseEnterpriseInfo.setUnitType(object.getString("cert_type"));
        tzBaseEnterpriseInfo.setUseCode(object.getString("unit_code"));
        tzBaseEnterpriseInfo.setUseUnit(object.getString("unit_name"));
        tzBaseEnterpriseInfo.setProvince(object.getString("province"));
        tzBaseEnterpriseInfo.setCity(object.getString("city"));
        tzBaseEnterpriseInfo.setDistrict(object.getString("district"));
        tzBaseEnterpriseInfo.setSyncDate(object.getDate("sync_date"));
        tzBaseEnterpriseInfo.setSyncState(object.getInteger("sync_state"));

        try {
            if(ValidationUtil.isEmpty(object.getString("reg_code")) || ValidationUtil.isEmpty(companyMap.get(object.getString("reg_code")))){
                tzBaseEnterpriseInfo.setSuperviseOrgCode(companyMap.get("610000").getOrgCode());
                tzBaseEnterpriseInfo.setSuperviseOrgName(companyMap.get("610000").getCompanyName());
                companyModel.setParentId(companyMap.get("610000").getSequenceNbr());
            }else{
                tzBaseEnterpriseInfo.setSuperviseOrgCode(companyMap.get(object.getString("reg_code")).getOrgCode());
                tzBaseEnterpriseInfo.setSuperviseOrgName(companyMap.get(object.getString("reg_code")).getCompanyName());
                companyModel.setParentId(companyMap.get(object.getString("reg_code")).getSequenceNbr());
            }
        } catch (Exception e) {
            System.out.println("名称为"+object.getString("unit_name")+"的许可企业同步企业信息时出错："+e.getMessage());
        }
        
        if(tzBaseEnterprisePrivilegeInfo == null){
            //当企业表中没有时
            tzBaseEnterpriseInfoService.save(tzBaseEnterpriseInfo);
        }else{
            //当企业表中有时
            tzBaseEnterpriseInfoService.updateById(tzBaseEnterpriseInfo);
        }


        companyModel.setSequenceNbr(object.getLong("sequence_nbr"));
        companyModel.setCompanyName(object.getString("unit_name"));
        companyModel.setCompanyCode(object.getString("unit_code"));
        companyModel.setLevel("company");
        companyModel.setAgencyCode("tzs");
        companyModel.setCompanyType(object.getString("cert_type"));
        companyModel.setAddress(object.getString("reg_address"));



        if (companyPrivilegeModel == null ) {
            try {
                //平台表新增
                Privilege.companyClient.create(companyModel);
            }catch (Exception e) {
                System.out.println("名称为"+object.getString("unit_name")+"的公司已存在！"+e.getMessage());
            }
        }else{
            //更新
            Privilege.companyClient.update(companyModel,object.getLong("sequence_nbr"));
        }
    }

    public Map<String, CompanyModel> getCompanyInfoMap(Collection companyModels,Map<String, CompanyModel> map){
        if(companyModels == null){
            return map;
        }
        Iterator iter = companyModels.iterator();
        while(iter.hasNext()){
            String json = JSON.toJSONString(iter.next());
            CompanyModel companyModel =  JSON.parseObject(json,CompanyModel.class);

            String code = companyModel.getCompanyCode();
            if(code.length() >=6){
                code = code.substring(0, 6);
            }
            map.put(code,companyModel);
            getCompanyInfoMap(companyModel.getChildren(),map);
        }
        return map;
    }
}
