package com.yeejoin.amos.boot.module.tcm.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.tcm.api.entity.TzBaseEnterpriseInfo;
import com.yeejoin.amos.boot.module.tcm.biz.service.impl.StartPlatformTokenService;
import com.yeejoin.amos.boot.module.tcm.biz.service.impl.TzBaseEnterpriseInfoServiceImpl;
import com.yeejoin.amos.boot.module.tcm.biz.utils.RedisUtil;
import com.yeejoin.amos.boot.module.tcm.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.stereotype.Component;
import org.typroject.tyboot.component.emq.EmqxListener;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

@Component
@Slf4j
public class PrivilegeCompanyUpdateAddListener extends EmqxListener {

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

    @Autowired
    TzBaseEnterpriseInfoServiceImpl tzBaseEnterpriseInfoService;

    @Autowired
    AccessFeignService accessFeignService;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    StartPlatformTokenService platformTokenService;

    @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("公司同步消息解析失败");
        }
        platformTokenService.setRequestContext();

        //判断库中业务tz_base_enterprise_info是否存在
        QueryWrapper<TzBaseEnterpriseInfo> queryWrapper = new QueryWrapper<TzBaseEnterpriseInfo>();
        queryWrapper.eq("use_code", object.getString("unit_code"));
        TzBaseEnterpriseInfo tzBaseEnterprisePrivilegeInfo = tzBaseEnterpriseInfoService.getOne(queryWrapper);
        if (!ValidationUtil.isEmpty(tzBaseEnterprisePrivilegeInfo)) {
            accessFeignService.updateSyncCompanyState(object.getString("sequence_nbr"));
            return;
        }


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


        //业务表更新条件构造器
        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());

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


        try {
            if (tzBaseEnterprisePrivilegeInfo == null) {
                tzBaseEnterpriseInfoService.save(tzBaseEnterpriseInfo);
                accessFeignService.updateSyncCompanyState(object.getString("sequence_nbr"));
                return;
            }
        } 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;
    }
}
