package com.liangjian.dataplatform.member.service.impl;

import com.liangjian.dataplatform.member.dao.tertiary.OrdersRepository;
import com.liangjian.dataplatform.member.entity.po.tertiary.Orders;
import com.liangjian.dataplatform.member.service.IQueryOrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;

/**
 * @Author: 黄子奇
 * @Date: 2019/11/26
 */
@Service
public class QueryOrdersService implements IQueryOrdersService {
    @Autowired
    private OrdersRepository ordersRepository;

    @Override
    public Page<Orders> queryBySecretPhoneAndStatus(String secretPhone, Integer status, Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page,size, Sort.Direction.DESC, "creationDate");

        Specification<Orders> specification = (root, criteriaQuery, criteriaBuilder) -> {
            Predicate phone1 = criteriaBuilder.equal(root.get("aConsigneePhone1").as(String.class), secretPhone);
            Predicate phone2 = criteriaBuilder.equal(root.get("aConsigneePhone2").as(String.class), secretPhone);
            Predicate phone3 = criteriaBuilder.equal(root.get("aConsigneePhone3").as(String.class), secretPhone);
            Predicate phones = criteriaBuilder.or(phone1,phone2,phone3);
            if(status == null) {
                return phones;
            } else {
                if(status == 1) {
                    //待发货
                    return criteriaBuilder.and(phones, criteriaBuilder.equal(root.get("orderStatus"),40));
                } else if(status == 2) {
                    //待收货
                    return criteriaBuilder.and(phones, criteriaBuilder.equal(root.get("orderStatus"),140));
                } else if(status == 3) {
                    //已完成
                    Predicate os = criteriaBuilder.or(
                            criteriaBuilder.equal(root.get("orderStatus"),50),
                            criteriaBuilder.equal(root.get("orderStatus"),70),
                            criteriaBuilder.equal(root.get("orderStatus"),150)
                    );
                    return criteriaBuilder.and(phones, os);
                } else {
                    return criteriaBuilder.and(phones, criteriaBuilder.equal(root.get("orderStatus"),status));
                }
            }
        };
        Page<Orders> ordersPage = ordersRepository.findAll(specification,pageable);
        return ordersPage;
    }
}
