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.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yeejoin.amos.boot.module.tzs.api.entity.TzBaseEnterpriseInfo;
import com.yeejoin.amos.boot.module.tzs.biz.service.impl.TzBaseEnterpriseInfoServiceImpl;
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.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.*;

@Component
@Slf4j
public class PrivilegeCompanyUpdateAddListener extends EmqxListener {

    Logger logger = LoggerFactory.getLogger(PrivilegeCompanyUpdateAddListener.class);

    @Autowired
    TzBaseEnterpriseInfoServiceImpl tzBaseEnterpriseInfoService;

    @Autowired
    AccessFeignService accessFeignService;

    @Autowired
    RedisUtil redisUtil;

    @Value("${amos.system.user.product:AMOS_STUDIO_WEB}")
    String product;

    @Value("${amos.system.user.app-key:AMOS_STUDIO}")
    String appKey;

    @Override
    public void processMessage(String s, MqttMessage message) throws Exception {
        logger.info("received mqtt message: " + 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 supervisePrivilegeCompanyModel;
        if (!ValidationUtil.isEmpty(regCode)) {
            supervisePrivilegeCompanyModel = Privilege.companyClient.queryByCompanyCode(regCode).getResult();

            if(ValidationUtil.isEmpty(supervisePrivilegeCompanyModel)){
                supervisePrivilegeCompanyModel = Privilege.companyClient.queryByCompanyCode("610000").getResult();

                if (ValidationUtil.isEmpty(supervisePrivilegeCompanyModel)) {
                    logger.error("【" + object.getString("unit_name") + "】对应监管企业为空");
                    return;
                }
            }
        } else {
            supervisePrivilegeCompanyModel = Privilege.companyClient.queryByCompanyCode("610000").getResult();
            if (ValidationUtil.isEmpty(supervisePrivilegeCompanyModel)) {
                logger.error("【" + object.getString("unit_name") + "】对应监管企业为空");
                return;
            }
        }
        tzBaseEnterpriseInfo.setSuperviseOrgCode(supervisePrivilegeCompanyModel.getOrgCode());
        tzBaseEnterpriseInfo.setSuperviseOrgName(supervisePrivilegeCompanyModel.getCompanyName());
        companyModel.setParentId(supervisePrivilegeCompanyModel.getSequenceNbr());

        if(ValidationUtil.isEmpty(tzBaseEnterpriseInfo.getUnitType())){
            tzBaseEnterpriseInfo.setUnitType("");
        }
        if(ValidationUtil.isEmpty(companyModel.getCompanyType())){
            companyModel.setCompanyType("");
        }

        try {
            if (tzBaseEnterprisePrivilegeInfo == null && companyPrivilegeModel == null) {
                //当企业表、平台表 中没有时
                tzBaseEnterpriseInfoService.save(tzBaseEnterpriseInfo);
                Privilege.companyClient.create(companyModel);
                accessFeignService.updateSyncCompanyState(object.getString("sequence_nbr"));
                logger.info("create/update unit license info: " + "企业表、平台表中没有该条数据");
            } 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"));
                logger.info("create/update unit license info: " + "企业表没有、平台表中有该条数据");
            } 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"));
                logger.info("create/update unit license info: " + "企业表有、平台表中没有该条数据");
            }
            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"));
                }
                logger.info("create/update unit license info: " + "企业表有、平台表中有该条数据");
            }
        } catch(Exception e) {
            logger.error("【" + 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;
    }
}
