package com.fs.erp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fs.erp.domain.FsJstCodPush;
import com.fs.erp.dto.ErpOrderResponseDTO;
import com.fs.erp.dto.ShopOrderDTO;
import com.fs.erp.http.JstErpHttpService;
import com.fs.erp.mapper.FsJstCodPushMapper;
import com.fs.erp.service.FsJstCodPushService;
import com.fs.express.enums.TaskStatusEnum;
import com.hc.openapi.tool.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class FsJstCodPushServiceImpl implements FsJstCodPushService {
    @Autowired
    private FsJstCodPushMapper fsJstCodPushMapper;

    @Autowired
    private JstErpHttpService jstErpHttpService;

    @Override
    public void jstCodPush() {
        List<FsJstCodPush> fsJstCodPushes = fsJstCodPushMapper.queryPenddingData();
        for (FsJstCodPush fsJstCodPush : fsJstCodPushes) {
            fsJstCodPush.setTaskStatus(TaskStatusEnum.PROCESSING.getCode());
            int lock = fsJstCodPushMapper.updateById(fsJstCodPush);
            if(lock <= 0) {
                log.info("获取当前记录锁失败! 已跳过");
                continue;
            }

            try{
                String params = fsJstCodPush.getParams();
                ShopOrderDTO shopOrderDTO = JSONObject.parseObject(params, ShopOrderDTO.class);
                ErpOrderResponseDTO upload = jstErpHttpService.upload(shopOrderDTO);
                fsJstCodPush.setResult(JSON.toJSONString(upload));
                fsJstCodPush.setTaskStatus(TaskStatusEnum.SUCCESS.getCode());

            }catch (Exception e) {
                fsJstCodPush.setErrorMessage(JSON.toJSONString(e));
                fsJstCodPush.setRetryCount(fsJstCodPush.getRetryCount()+1);
            }

            fsJstCodPushMapper.updateById(fsJstCodPush);
        }
    }
}
