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.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.stereotype.Component;

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;

    @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.setEquipCategory(RefreshDataUtils.castStrList2String(enterpriseInfo.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());
                esBaseEnterpriseInfo.setLicenses(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());
                });
                if (userInfosEs.iterator().hasNext()) {
                    esUserInfoDao.saveAll(userInfosEs);
                }
                break;
            default:
                log.error("unknown operation: {}", message.getOperation());
                break;
        }
    }
}
