package com.sw.mes.yb.check.service.impl;

import com.sw.mes.core.api.system.FbFeignClients;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultCode;
import com.sw.mes.yb.check.service.SynchronousUpdateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.List;

/**
 * @author zhaowenjie
 */
@Slf4j
@Service
public class SynchronousUpdateServiceImpl implements SynchronousUpdateService {

    @Autowired
    private FbFeignClients fbFeignClients;

    @Async
    @Override
    public void synchronousUpdate(String sectionNo, RequestAttributes requestAttributes) {
        RequestContextHolder.setRequestAttributes(requestAttributes);
        synchronousFbServer(sectionNo);
    }

    @Async
    @Override
    public void synchronousUpdates(List<String> sectionNos, RequestAttributes requestAttributes) {
        if (sectionNos.size() > 0) {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            sectionNos.forEach(this::synchronousFbServer);
        }
    }

    private void synchronousFbServer(String sectionNo) {
        try {
            Result result = fbFeignClients.synchronousUpdate(sectionNo);
            if (result.getCode() == ResultCode.SUCCESS.getCode()) {
                log.info("样片数据变动，触发方棒评级：" + sectionNo + "成功");
            } else {
                log.error("样片数据变动，触发方棒评级：" + sectionNo + "失败：" + result.getMessage());
            }
        } catch (Exception e) {
            log.error("样片数据变动，触发方棒评级：" + sectionNo + "失败：" + e.getMessage());
        } finally {
            RequestContextHolder.resetRequestAttributes();
        }
    }
}
