package cn.com.taiji.beidou.ship.archives;

import cn.com.taiji.beidou.ship.archives.domain.ShipArchivesData;
import cn.com.taiji.beidou.ship.archives.domain.ShipInfoParam;
import cn.com.taiji.beidou.ship.archives.mapper.ShipArchivesMapper;
import cn.com.taiji.beidou.ship.feign.OpenServiceFeign;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

//@Component
@Slf4j
public class BeiDouShipInfo {

    @Autowired(required = false)
    private OpenServiceFeign openServiceFeign;

    @Resource
    private ShipArchivesMapper shipArchivesMapper;

    /**
     * 每日4：00执行一次
     */

    //@Scheduled(cron = "0 0 4 1/1 * ?")
    public void beidouShipInfo(){

        log.info("start update ship info message 。。。");
        int page = 1 ;
        int pageSize = 100;
        int pageCount;
        ShipInfoParam param = new ShipInfoParam();
        param.setPage(page);
        param.setPageSize(pageSize);

        try {
            do {
                String result = this.openServiceFeign.shipInfo(JSONObject.toJSONString(param)).toJSONString();
                JSONObject resultData = JSON.parseObject(result);
                JSONObject data = JSON.parseObject(resultData.getString("data"));
                Integer totalSize = data.getInteger("totalSize");
                JSONArray shipInfoData = JSON.parseArray(data.getString("data"));
                for (int n=0;n<shipInfoData.size();n++){
                    String shipInfo = shipInfoData.get(n).toString();
                    ShipArchivesData shipArchivesData = JSON.parseObject(shipInfo,ShipArchivesData.class);
                    ShipArchivesData shipArchives = shipArchivesMapper.selectByDevideNo(shipArchivesData.getDevideNo());
                    if(shipArchives!=null && shipArchives.getDevideNo()!=null){
                        shipArchivesMapper.updateById(shipArchivesData);
                    }else {
                        shipArchivesMapper.insertShip(shipArchivesData);
                    }

                }
                pageCount = totalSize/pageSize + 1;
                page++;
                param.setPage(page);
            }while (page<=pageCount);
            log.info("count ："+page+"time；  successful！");
        }catch (Exception e){
            e.printStackTrace();
            log.info("sql insert exception："+e.getMessage());
        }

    }
}
