package com.uas.platform.b2b.task;

import com.uas.platform.b2b.ps.model.PersonalProduct;
import com.uas.platform.b2b.ps.service.PersonalProductService;
import com.uas.platform.b2b.service.ProductUsersService;
import com.uas.platform.core.model.PageInfo;
import com.uas.platform.core.model.Status;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 数据同步任务
 *
 * Created by hejq on 2018-06-05.
 */
@Component
public class SyncTask {

    @Autowired
    private PersonalProductService personalProductService;

    @Autowired
    private ProductUsersService productUsersService;

    /**
     * 单据操作时将物料信息同步到个人物料
     * <note>
     *     因为这一块耗费时间比较长，如果放在业务操作中进行，会很大程度上影响客户操作体验
     * </note>
     */
    @Scheduled(cron = "0 0/2 * * * ?")
    public void SyncPersonalProduct() {
        PageInfo pageInfo = new PageInfo(1, 10);
        pageInfo.setSort(new Sort(Sort.Direction.ASC, "id"));
        pageInfo.filter("status", Status.NOT_UPLOAD.value());
        List<PersonalProduct> products = personalProductService.findByPageInfo(pageInfo);
        if (!CollectionUtils.isEmpty(products)) {
            for (PersonalProduct product : products) {
                try {
                    productUsersService.coverToMyProduct(product.getPrId(), product.getEnUU(), product.getUserUU(), product.getMethod());
                    personalProductService.updateStatusById(Status.DOWNLOADED.value(), product.getId(), new Date(System.currentTimeMillis()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
