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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.injector.methods.Update;
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.boot.module.tzs.flc.api.feign.AccessFeignService;
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.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class PrivilegeCompanyUpdateAddListener extends EmqxListener {

    @Autowired
    TzBaseEnterpriseInfoServiceImpl tzBaseEnterpriseInfoService;

    @Autowired
    AccessFeignService accessFeignService;

    @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);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        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")));

        //判断库中company是否重复
        CompanyModel companyPrivilegeModel = Privilege.companyClient.queryByCompanyCode(object.getString("unit_code")).getResult();

        QueryWrapper<TzBaseEnterpriseInfo> queryWrapper = new QueryWrapper<TzBaseEnterpriseInfo>();
        queryWrapper.eq("use_code",object.getString("unit_code"));
        TzBaseEnterpriseInfo tzBaseEnterprisePrivilegeInfo = tzBaseEnterpriseInfoService.getOne(queryWrapper);

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

        Date syncDate = sdf.parse(object.getString("sync_date"));
        Date recDate = sdf.parse(object.getString("issue_date"));

        String unitType = object.getString("cert_type");


        tzBaseEnterpriseInfo.setSequenceNbr(object.getLong("sequence_nbr"));
        tzBaseEnterpriseInfo.setAddress(object.getString("reg_address"));
        tzBaseEnterpriseInfo.setUnitType(unitType);
        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(syncDate);
        tzBaseEnterpriseInfo.setSyncState(object.getInteger("sync_state"));
        tzBaseEnterpriseInfo.setRecDate(recDate);

        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(unitType);
        companyModel.setAddress(object.getString("reg_address"));

        //业务表更新条件构造器
        UpdateWrapper<TzBaseEnterpriseInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("Use_code",object.getString("unit_code"));



        String regCode = object.getString("reg_code");
        CompanyModel privilegeCompanyModel = Privilege.companyClient.queryByCompanyCode(regCode).getResult();

        if(ValidationUtil.isEmpty(privilegeCompanyModel)){
            privilegeCompanyModel = Privilege.companyClient.queryByCompanyCode("610000").getResult();
        }
        if(ValidationUtil.isEmpty(tzBaseEnterpriseInfo.getUnitType())){
            tzBaseEnterpriseInfo.setUnitType("");
        }
        if(ValidationUtil.isEmpty(companyModel.getCompanyType())){
            companyModel.setCompanyType("");
        }

        try {
            tzBaseEnterpriseInfo.setSuperviseOrgCode(privilegeCompanyModel.getOrgCode());
            tzBaseEnterpriseInfo.setSuperviseOrgName(privilegeCompanyModel.getCompanyName());
            companyModel.setParentId(privilegeCompanyModel.getSequenceNbr());
        } catch (Exception e) {
            System.out.println("名称为"+object.getString("unit_name")+"的许可企业同步企业信息时出错："+e.getMessage());
        }

        try {
            if (tzBaseEnterprisePrivilegeInfo == null && companyPrivilegeModel == null) {
                //当企业表、平台表 中没有时
                tzBaseEnterpriseInfoService.save(tzBaseEnterpriseInfo);
                Privilege.companyClient.create(companyModel);
                accessFeignService.updateSyncCompanyState(object.getString("sequence_nbr"));
            } else if(tzBaseEnterprisePrivilegeInfo == null){
                //企业表没有，平台表有
                if(!ValidationUtil.isEmpty(companyPrivilegeModel.getCompanyType())){
                    if(!companyPrivilegeModel.getCompanyType().contains(companyModel.getCompanyType())){
                        companyModel.setCompanyType(companyPrivilegeModel.getCompanyType()+","+companyModel.getCompanyType());
                    }else {
                        companyModel.setCompanyType(companyPrivilegeModel.getCompanyType());
                    }
                }
                tzBaseEnterpriseInfoService.save(tzBaseEnterpriseInfo);
                Privilege.companyClient.update(companyModel, companyPrivilegeModel.getSequenceNbr());
                accessFeignService.updateSyncCompanyState(object.getString("sequence_nbr"));
            } else if(companyPrivilegeModel == null){
                //平台表没有，企业表有
                if(!ValidationUtil.isEmpty(tzBaseEnterprisePrivilegeInfo.getUnitType())){
                    if(!tzBaseEnterprisePrivilegeInfo.getUnitType().contains(tzBaseEnterpriseInfo.getUnitType())){
                        tzBaseEnterpriseInfo.setUnitType(tzBaseEnterprisePrivilegeInfo.getUnitType()+","+tzBaseEnterpriseInfo.getUnitType());
                    }else {
                        tzBaseEnterpriseInfo.setUnitType(tzBaseEnterprisePrivilegeInfo.getUnitType());
                    }
                }

                Privilege.companyClient.create(companyModel);
                tzBaseEnterpriseInfoService.update(tzBaseEnterpriseInfo,updateWrapper);
                accessFeignService.updateSyncCompanyState(object.getString("sequence_nbr"));
            }
            else {
                //当企业表、平台表 中有时
                if(ValidationUtil.isEmpty(tzBaseEnterprisePrivilegeInfo.getRecDate())){
                    //如果库中没有存时间，则默认为1990-01-01
                    SimpleDateFormat sdft = new SimpleDateFormat("yyyy-MM-dd");
                    tzBaseEnterprisePrivilegeInfo.setRecDate(sdft.parse("1990-01-01"));
                }
                if (tzBaseEnterprisePrivilegeInfo.getRecDate().compareTo(object.getDate("issue_date")) < 1) {
                    if(!ValidationUtil.isEmpty(tzBaseEnterprisePrivilegeInfo.getUnitType())){
                        if(!tzBaseEnterprisePrivilegeInfo.getUnitType().contains(tzBaseEnterpriseInfo.getUnitType())){
                            tzBaseEnterpriseInfo.setUnitType(tzBaseEnterprisePrivilegeInfo.getUnitType()+","+tzBaseEnterpriseInfo.getUnitType());
                        }else {
                            tzBaseEnterpriseInfo.setUnitType(tzBaseEnterprisePrivilegeInfo.getUnitType());
                        }
                    }
                    if(!ValidationUtil.isEmpty(companyPrivilegeModel.getCompanyType())){
                        if(!companyPrivilegeModel.getCompanyType().contains(companyModel.getCompanyType())){
                            companyModel.setCompanyType(companyPrivilegeModel.getCompanyType()+","+companyModel.getCompanyType());
                        }else {
                            companyModel.setCompanyType(companyPrivilegeModel.getCompanyType());
                        }
                    }
                    tzBaseEnterpriseInfoService.update(tzBaseEnterpriseInfo,updateWrapper);
                    Privilege.companyClient.update(companyModel, companyPrivilegeModel.getSequenceNbr());
                    accessFeignService.updateSyncCompanyState(object.getString("sequence_nbr"));
                } else {
                    if(!ValidationUtil.isEmpty(tzBaseEnterprisePrivilegeInfo.getUnitType())){
                        if(!tzBaseEnterprisePrivilegeInfo.getUnitType().contains(tzBaseEnterpriseInfo.getUnitType())){
                            tzBaseEnterprisePrivilegeInfo.setUnitType(tzBaseEnterprisePrivilegeInfo.getUnitType()+","+tzBaseEnterpriseInfo.getUnitType());
                            tzBaseEnterpriseInfoService.update(tzBaseEnterprisePrivilegeInfo,updateWrapper);
                        }
                    }
                    if(!ValidationUtil.isEmpty(companyPrivilegeModel.getCompanyType())){
                        if(!companyPrivilegeModel.getCompanyType().contains(companyModel.getCompanyType())){
                            companyPrivilegeModel.setCompanyType(companyPrivilegeModel.getCompanyType()+","+companyModel.getCompanyType());
                            Privilege.companyClient.update(companyPrivilegeModel, companyPrivilegeModel.getSequenceNbr());
                        }
                    }
                    System.out.println("该数据不是最新的数据 不用更新");
                    accessFeignService.updateSyncCompanyState(object.getString("sequence_nbr"));
                }
            }
        } catch(Exception e) {
            System.out.println("名称为"+object.getString("unit_name")+"的公司:"+e.getMessage());
        }
    }

    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;
    }
}
