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


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

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

        QueryWrapper<TzBaseEnterpriseInfo> queryWrapper = new QueryWrapper<TzBaseEnterpriseInfo>();
        queryWrapper.eq("use_unit",object.getString("unit_name"));
        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"));

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

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

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

        try {
            if (tzBaseEnterprisePrivilegeInfo == null && companyPrivilegeModel == null) {
                //当企业表、平台表 中没有时
                tzBaseEnterpriseInfoService.save(tzBaseEnterpriseInfo);
                Privilege.companyClient.create(companyModel);
            } else if(tzBaseEnterprisePrivilegeInfo == null){
                //企业表没有，平台表有
                tzBaseEnterpriseInfoService.save(tzBaseEnterpriseInfo);
                Privilege.companyClient.update(companyModel, tzBaseEnterprisePrivilegeInfo.getSequenceNbr());
            } else if(companyPrivilegeModel == null){
                //平台表没有，企业表有
                Privilege.companyClient.create(companyModel);
                tzBaseEnterpriseInfoService.update(tzBaseEnterpriseInfo,updateWrapper);
            }
            else {
                //当企业表、平台表 中有时
                if (tzBaseEnterprisePrivilegeInfo.getRecDate().compareTo(object.getDate("issue_date")) < 1) {
                    tzBaseEnterpriseInfoService.update(tzBaseEnterpriseInfo,updateWrapper);
                    Privilege.companyClient.update(companyModel, tzBaseEnterprisePrivilegeInfo.getSequenceNbr());
                } else {
                    System.out.println("该数据不是最新的数据 不用更新");
                }
            }
        } 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;
    }
}
