package com.yeejoin.amos.boot.module.tcm.biz.refresh.handler;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.module.common.api.dao.EsBaseEnterpriseInfoDao;
import com.yeejoin.amos.boot.module.common.api.dao.EsUserInfoDao;
import com.yeejoin.amos.boot.module.common.api.entity.EsBaseEnterpriseInfo;
import com.yeejoin.amos.boot.module.common.api.entity.EsUserInfo;
import com.yeejoin.amos.boot.module.common.api.entity.TzsDataRefreshMessage;
import com.yeejoin.amos.boot.module.common.api.service.IDataRefreshHandler;
import com.yeejoin.amos.boot.module.common.biz.refresh.DataRefreshEvent;
import com.yeejoin.amos.boot.module.common.biz.refresh.cm.RefreshCmService;
import com.yeejoin.amos.boot.module.common.biz.utils.RefreshDataUtils;
import com.yeejoin.amos.boot.module.tcm.api.entity.TzBaseEnterpriseInfo;
import com.yeejoin.amos.boot.module.tcm.api.entity.TzBaseUnitLicence;
import com.yeejoin.amos.boot.module.tcm.api.entity.TzsUserInfo;
import com.yeejoin.amos.boot.module.tcm.api.mapper.TzBaseEnterpriseInfoMapper;
import com.yeejoin.amos.boot.module.tcm.api.mapper.TzBaseUnitLicenceMapper;
import com.yeejoin.amos.boot.module.tcm.api.mapper.TzsUserInfoMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
@Slf4j
public class EnterpriseRefreshHandler implements IDataRefreshHandler {

    private final EsBaseEnterpriseInfoDao enterpriseInfoDao;

    private final TzBaseUnitLicenceMapper licenceMapper;

    private final TzBaseEnterpriseInfoMapper tzBaseEnterpriseInfoMapper;

    private final TzsUserInfoMapper userInfoMapper;

    private final EsUserInfoDao esUserInfoDao;

    @Value("${jyjc.open.online:true}")
    private Boolean onlineJyjc;


    @Override
    public String supportType() {
        return "enterprise";
    }

    @Override
    public void doRefresh(TzsDataRefreshMessage message) {
        log.info("三库数据，企业开始刷库：唯一标识：{}", message.getDataId());
        TzBaseEnterpriseInfo enterpriseInfo = Optional.ofNullable(tzBaseEnterpriseInfoMapper.selectById(message.getDataId())).orElse(
                tzBaseEnterpriseInfoMapper.selectOne(new LambdaQueryWrapper<TzBaseEnterpriseInfo>().eq(TzBaseEnterpriseInfo::getUseUnitCode, message.getDataId()))
        );
        if (enterpriseInfo == null) {
            throw new RuntimeException(String.format("刷企业信息es时，企业：%s，未找到", message.getDataId()));
        }
        switch (DataRefreshEvent.Operation.valueOf(message.getOperation())) {
            case DELETE:
                enterpriseInfoDao.deleteById(message.getDataId());
                esUserInfoDao.deleteAllByUnitCode(enterpriseInfo.getUseCode());
                break;
            case INSERT:
            case UPDATE:
                // 企业信息更新
                EsBaseEnterpriseInfo esBaseEnterpriseInfo = new EsBaseEnterpriseInfo();
                BeanUtil.copyProperties(enterpriseInfo, esBaseEnterpriseInfo);
                esBaseEnterpriseInfo.setSequenceNbr(enterpriseInfo.getSequenceNbr() + "");
                esBaseEnterpriseInfo.setContactUser(enterpriseInfo.getUseContact());
                esBaseEnterpriseInfo.setEquipCategory(RefreshDataUtils.castStrList2String(enterpriseInfo.getEquipCategory()));
                esBaseEnterpriseInfo.setEquipCategoryName(RefreshDataUtils.castEquCategory2Name(esBaseEnterpriseInfo.getEquipCategory()));
                List<TzBaseUnitLicence> unitLicences = licenceMapper.selectList(new LambdaQueryWrapper<TzBaseUnitLicence>().eq(TzBaseUnitLicence::getUnitCode, enterpriseInfo.getUseUnitCode()).eq(TzBaseUnitLicence::getIsDelete, false));
                List<EsBaseEnterpriseInfo.License> licenses = unitLicences.stream().map(lis -> {
                    EsBaseEnterpriseInfo.License esLicense = new EsBaseEnterpriseInfo.License();
                    BeanUtil.copyProperties(lis, esLicense);
                    return esLicense;
                }).collect(Collectors.toList());
                if (!ObjectUtils.isEmpty(licenses)) {
                    esBaseEnterpriseInfo.setLicenses(licenses);
                    try {
                        esBaseEnterpriseInfo.setLicenseMinExpiryDate(RefreshCmService.getMinDateFromLicensesEp(licenses));
                    } catch (Exception e) {
                        log.error("企业信息单位类型或者取资质最小日期失败:{}", enterpriseInfo, e);
                    }
                }
                esBaseEnterpriseInfo.setUnitType(onlineJyjc ? enterpriseInfo.getUnitType() : RefreshCmService.updateJyjcUnitType(enterpriseInfo.getUnitType(), licenses));
                enterpriseInfoDao.save(esBaseEnterpriseInfo);
                // 人员更新冗余的单位信息
                List<TzsUserInfo> userOfOneUnit = userInfoMapper.selectList(new LambdaQueryWrapper<TzsUserInfo>().eq(TzsUserInfo::getUnitCode, enterpriseInfo.getUseUnitCode()).eq(BaseEntity::getIsDelete, false).select(BaseEntity::getSequenceNbr));
                Iterable<EsUserInfo> userInfosEs = esUserInfoDao.findAllById(userOfOneUnit.stream().map(u -> String.valueOf(u.getSequenceNbr())).collect(Collectors.toList()));
                userInfosEs.forEach(esUserInfo -> {
                    esUserInfo.setUnitType(esBaseEnterpriseInfo.getUnitType());
                    esUserInfo.setSuperviseOrgName(esBaseEnterpriseInfo.getSuperviseOrgName());
                    esUserInfo.setSuperviseOrgCode(esBaseEnterpriseInfo.getSuperviseOrgCode());
                    esUserInfo.setOfficeRegion(esBaseEnterpriseInfo.getOfficeRegion());
                });
                if (userInfosEs.iterator().hasNext()) {
                    esUserInfoDao.saveAll(userInfosEs);
                }
                break;
            default:
                log.error("unknown operation: {}", message.getOperation());
                break;
        }
    }
}
