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

import com.uas.platform.b2b.ps.dao.PersonalProductDao;
import com.uas.platform.b2b.ps.model.PersonalProduct;
import com.uas.platform.b2b.ps.service.PersonalProductService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.model.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Date;
import java.util.List;

/**
 * 待处理个人物料
 *
 * Created by hejq on 2018-06-05.
 */
@Service
public class PersonalProductServiceImpl implements PersonalProductService {

    @Autowired
    private PersonalProductDao personlProductDao;

    /**
     * 通过分页信息查询待处理个人物料
     *
     * @param pageInfo 分页信息
     * @return
     */
    @Override
    public List<PersonalProduct> findByPageInfo(final PageInfo pageInfo) {
        return personlProductDao.findAll(new Specification<PersonalProduct>() {
            @Override
            public Predicate toPredicate(Root<PersonalProduct> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                query.where(pageInfo.getPredicates(root, query, builder));
                return null;
            }
        });
    }

    /**
     * 通过id更新处理状态
     *
     * @param status 状态
     * @param id     id
     */
    @Override
    public void updateStatusById(Integer status, Long id, Date date) {
        personlProductDao.updateStatusById(status, id, date);
    }

    /**
     * 通过物料id和方法进行待处理个人物料信息
     *
     * @param prId   物料id
     * @param method 方法
     */
    @Override
    public void covertPersonalProduct(Long prId, String method) {
        final Long enUU = SystemSession.getUser().getEnterprise().getUu();
        final Long userUU = SystemSession.getUser().getUserUU();
        Integer count = personlProductDao.countByUserUUAndEnUUAndPrId(userUU, enUU, prId);
        if (count == 0) {
            personlProductDao.save(new PersonalProduct(prId, enUU, userUU, method));
        }
    }
}
