package com.yeejoin.amos.boot.module.jg.biz.handler.strategy;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.common.api.dao.ESEquipmentCategory;
import com.yeejoin.amos.boot.module.common.api.dto.ESEquipmentCategoryDto;
import com.yeejoin.amos.boot.module.jg.api.entity.SafetyProblemTracing;
import com.yeejoin.amos.boot.module.jg.api.enums.SafetyProblemStatusEnum;
import com.yeejoin.amos.boot.module.jg.api.enums.SafetyProblemTypeEnum;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.IdxBizJgOtherInfoServiceImpl;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.SafetyProblemTracingServiceImpl;
import com.yeejoin.amos.boot.module.ymt.api.entity.IdxBizJgOtherInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

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

@Component("equipmentProblemStrategy")
@RequiredArgsConstructor
public class EquipmentProblemStrategy implements ProblemHandleStrategy {

    private final SafetyProblemTracingServiceImpl safetyProblemTracingService;
    private final IdxBizJgOtherInfoServiceImpl idxBizJgOtherInfoService;
    private final ESEquipmentCategory esEquipmentCategory;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void handleProblem(JSONArray jsonArray, SafetyProblemTypeEnum problemTypeEnum) {
        List<String> equipRecords = jsonArray.stream().map(obj -> JSONObject.parseObject(obj.toString()).getString("record")).collect(Collectors.toList());
        if (!ValidationUtil.isEmpty(equipRecords)) {
            safetyProblemTracingService.lambdaUpdate()
                    .set(SafetyProblemTracing::getProblemStatusCode, SafetyProblemStatusEnum.HANDLED.getCode())
                    .set(SafetyProblemTracing::getProblemStatus, SafetyProblemStatusEnum.HANDLED.getName())
                    .in(SafetyProblemTracing::getSourceId, equipRecords)
                    .eq(SafetyProblemTracing::getProblemTypeCode, problemTypeEnum.getCode()).update();
            idxBizJgOtherInfoService.lambdaUpdate().set(IdxBizJgOtherInfo::getStatus, SafetyProblemStatusEnum.HANDLED.getCode())
                    .in(IdxBizJgOtherInfo::getRecord, equipRecords).update();
            Iterable<ESEquipmentCategoryDto> equipEsDtoIter = esEquipmentCategory.findAllById(equipRecords);
            for (ESEquipmentCategoryDto equipEsDto : equipEsDtoIter) {
                equipEsDto.setProblemStatus(SafetyProblemStatusEnum.HANDLED.getCode());
            }
            esEquipmentCategory.saveAll(equipEsDtoIter);
        }
    }
}

