package com.yeejoin.amos.boot.module.jg.biz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.module.jg.api.entity.JgUseRegistrationEq;
import com.yeejoin.amos.boot.module.jg.api.mapper.CommonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.util.List;

@Slf4j
public class FillingUseRegisterResult extends BaseUseRegisterResultData {

    private final ApplicationContext applicationContext;

    /**
     * 使用登记主键
     */
    private final Long userRegisterId;

    public FillingUseRegisterResult(Long sequenceNbr, JSONObject data, ApplicationContext applicationContext) {
        super(data);
        this.applicationContext = applicationContext;
        this.userRegisterId = sequenceNbr;
    }


    @Override
    public JSONObject getData() {
        JSONObject data = super.getData();
        fillingEditPermission(data);
        return data;
    }

    /**
     * 判断设备在做过后续业务：移转变更、改造变更、更名变更、单位变更【使用单位未提交、已作废不包括统计内】
     *
     * @param jsonObject 返回的数据
     */
    private void fillingEditPermission(JSONObject jsonObject) {
        jsonObject.put(HAPPEN_AFTER_BIZ, false);
        List<JgUseRegistrationEq> useRegistrationEqs = getJgUseRegistrationEqService().list(new LambdaQueryWrapper<JgUseRegistrationEq>()
                .eq(JgUseRegistrationEq::getEquipTransferId, userRegisterId)
                .select(JgUseRegistrationEq::getEquId, BaseEntity::getSequenceNbr));
        for (JgUseRegistrationEq useRegistrationEq : useRegistrationEqs) {
            Integer useTimes = getCommonMapper().countBizNumAfterUseReg(useRegistrationEq.getEquId());
            if (useTimes > 0) {
                log.warn("设备：{}做过后续业务, 此使用登记：{}不可再变更设备信息", useRegistrationEq.getEquId(), userRegisterId);
                jsonObject.put(HAPPEN_AFTER_BIZ, true);
                break;
            }
        }
    }

    private JgUseRegistrationEqServiceImpl getJgUseRegistrationEqService() {
        return applicationContext.getBean(JgUseRegistrationEqServiceImpl.class);
    }

    private CommonMapper getCommonMapper() {
        return applicationContext.getBean(CommonMapper.class);
    }

}
