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.controller.BaseController;
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.TzsUserInfo;
import com.yeejoin.amos.boot.module.tcm.api.mapper.TzBaseEnterpriseInfoMapper;
import com.yeejoin.amos.boot.module.tcm.api.mapper.TzsUserInfoMapper;
import com.yeejoin.amos.boot.module.tcm.biz.refresh.CommonRefreshService;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Optional;

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

    private final TzBaseEnterpriseInfoMapper enterpriseInfoMapper;

    private final TzsUserInfoMapper userInfoMapper;

    private final EsUserInfoDao esUserInfoDao;

    private final EsBaseEnterpriseInfoDao esBaseEnterpriseInfoDao;

    private final CommonRefreshService commonRefreshService;


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

    @Override
    public void doRefresh(TzsDataRefreshMessage message) {
        log.info("三库数据，人员开始刷库：唯一标识：{}", message.getDataId());
        switch (DataRefreshEvent.Operation.valueOf(message.getOperation())) {
            case DELETE:
                esUserInfoDao.deleteById(message.getDataId());
                break;
            case INSERT:
            case UPDATE:
                TzsUserInfo userInfo = userInfoMapper.selectById(message.getDataId());
                TzBaseEnterpriseInfo unit = enterpriseInfoMapper.selectOne(new LambdaQueryWrapper<TzBaseEnterpriseInfo>()
                        .select(BaseEntity::getSequenceNbr,
                                TzBaseEnterpriseInfo::getUseCode,
                                TzBaseEnterpriseInfo::getUseUnit,
                                TzBaseEnterpriseInfo::getUnitType,
                                TzBaseEnterpriseInfo::getSuperviseOrgCode,
                                TzBaseEnterpriseInfo::getSuperviseOrgName
                        ).eq(BaseEntity::getIsDelete, false).eq(TzBaseEnterpriseInfo::getUseCode, userInfo.getUnitCode()));
                EsUserInfo esUserInfo = new EsUserInfo();
                BeanUtil.copyProperties(userInfo, esUserInfo);
                esUserInfo.setPost(RefreshDataUtils.castStrList2String(userInfo.getPost()));
                esUserInfo.setNewPost(RefreshDataUtils.castStrList2String(userInfo.getNewPost()));
                esUserInfo.setSubPost(RefreshDataUtils.castStrList2String(userInfo.getSubPost()));
                esUserInfo.setEquipType(RefreshDataUtils.castStrList2String(userInfo.getEquipType()));
                esUserInfo.setEquipTypeName(RefreshDataUtils.castEquCategory2Name(esUserInfo.getEquipType()));
                // 绑定设备状态
                esUserInfo.setBindEquStatus(commonRefreshService.queryUserBindEquStatus(userInfo.getSequenceNbr()));
                // 监管机构
                if (userInfo.getCompanyType().equals(BaseController.COMPANY_TYPE_SUPERVISION)) {
                    CompanyModel result = userInfoMapper.selectPrivilegeCompanyByCompanyCode(userInfo.getUnitCode());
                    esUserInfo.setUnitType(result.getCompanyType());
                    esUserInfo.setSuperviseOrgName(result.getCompanyName());
                    esUserInfo.setSuperviseOrgCode(result.getOrgCode());
                } else {
                    // 企业
                    Optional<EsBaseEnterpriseInfo> esBaseEnterpriseInfo = esBaseEnterpriseInfoDao.findById(unit.getSequenceNbr() + "");
                    // 人员类型暂时取esBaseEnterpriseInfo按照资质分开后的，等检验和检测分开后，按照实际情况取就即可：unit.getUnitType()
                    String unitType = esBaseEnterpriseInfo.map(EsBaseEnterpriseInfo::getUnitType).orElse(unit.getUnitType());
                    esUserInfo.setUnitType(unitType);
                    esUserInfo.setSuperviseOrgName(unit.getSuperviseOrgName());
                    esUserInfo.setSuperviseOrgCode(unit.getSuperviseOrgCode());
                    esUserInfo.setOfficeRegion(unit.getOfficeRegion());
                }
                esUserInfo.setLicenses(commonRefreshService.buildUserLicenses(userInfo.getSequenceNbr()));
                esUserInfo.setLicenseMinExpiryDate(RefreshCmService.getMinDateFromLicensesUser(esUserInfo.getLicenses()));
                esUserInfoDao.save(esUserInfo);
                break;
            default:
                log.error("unknown operation: {}", message.getOperation());
                break;
        }
    }
}
