package com.uas.platform.b2b.service.impl;

import com.uas.platform.b2b.core.util.ThreadTask;
import com.uas.platform.b2b.dao.UserDao;
import com.uas.platform.b2b.dao.UserOrderDao;
import com.uas.platform.b2b.dao.VendorPerformanceAssessDao;
import com.uas.platform.b2b.model.User;
import com.uas.platform.b2b.model.UserOrders;
import com.uas.platform.b2b.model.VendorPerformanceAssess;
import com.uas.platform.b2b.service.VendorPerformanceAssessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 黄诚天 on 2017-10-12.
 */
@Service
public class VendorPerformanceAssessServiceImpl implements VendorPerformanceAssessService {
    @Autowired
    private VendorPerformanceAssessDao vpaDao;

    @Autowired
    private UserOrderDao userOrderDao;

    @Autowired
    private UserDao userDao;

    @Override
    public List<VendorPerformanceAssess> save(List<VendorPerformanceAssess> vpas) {
        //事务
        List<VendorPerformanceAssess> newVpas = vpaDao.save(vpas);
        saveUserOrder(newVpas);
        return newVpas;
    }

    private void saveUserOrder(final List<VendorPerformanceAssess> newVpas) {
        ThreadTask.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                List<UserOrders> list = new ArrayList<>();
                for (VendorPerformanceAssess vpa : newVpas) {
                    List<User> users = userDao.findByEnUU(vpa.getVpaVeuu());
                    UserOrders userOrders;
                    for (User user : users) {
                        if (user == null) {
                            continue;
                        }
                        userOrders = new UserOrders(user.getUserUU(), vpa.getVpaVeuu(), vpa.getId(), "sale", "vendorperformanceassess");
                        list.add(userOrders);
                    }
                }
                userOrderDao.save(list);
            }
        });
    }

    @Override
    public void onVPADownSuccess(String[] idArray) {
        for (String id : idArray) {
            VendorPerformanceAssess vpa = vpaDao.findOne(Long.parseLong(id));
            if (vpa != null) {
                vpaDao.save(vpa);
            }
        }
    }

    @Override
    public VendorPerformanceAssess findById(Long id) {
        return vpaDao.findOne(id);
    }

}
