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

import com.uas.platform.b2b.manage.controller.support.ResultBean;
import com.uas.platform.b2b.manage.core.util.StringUtils;
import com.uas.platform.b2b.manage.dao.DeputyOrderDao;
import com.uas.platform.b2b.manage.dao.EnterpriseBaseInfoDao;
import com.uas.platform.b2b.manage.model.DeputyOrder;
import com.uas.platform.b2b.manage.model.EnterpriseBaseInfo;
import com.uas.platform.b2b.manage.page.PageInfo;
import com.uas.platform.b2b.manage.page.criteria.CriterionExpression;
import com.uas.platform.b2b.manage.page.criteria.LogicalExpression;
import com.uas.platform.b2b.manage.page.criteria.SimpleExpression;
import com.uas.platform.b2b.manage.service.DeputyOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 * 代采订单实现接口
 *
 * @author hejq
 * @date 2018-11-29 9:40
 */
@Service
public class DeputyOrderServiceImpl extends BaseService implements DeputyOrderService {

    @Autowired
    private DeputyOrderDao orderDao;

    @Autowired
    private EnterpriseBaseInfoDao enterpriseBaseInfoDao;

    /**
     * 分页获取代采订单信息
     *
     * @param info    分页信息
     * @param keyword 关键字
     * @return 搜索结果
     */
    @Override
    public Page<DeputyOrder> findByPageInfo(PageInfo info, String keyword) {
        if (!StringUtils.isEmpty(keyword)) {
            SimpleExpression code = new SimpleExpression("code", keyword, CriterionExpression.Operator.LIKE, true);
            SimpleExpression saleCode = new SimpleExpression("salecode", keyword, CriterionExpression.Operator.LIKE, true);
            SimpleExpression[] expressions = new SimpleExpression[]{code, saleCode};
            LogicalExpression logical = new LogicalExpression(expressions, CriterionExpression.Operator.OR);
            info.expression(logical);
        }
        Page<DeputyOrder> orderPage = orderDao.findAll((Root<DeputyOrder> root, CriteriaQuery<?> query, CriteriaBuilder builder)
                -> query.where(info.getPredicates(root, query, builder)).getRestriction(), info);
        orderPage.getContent().stream().filter(order -> null != order.getEnuu())
                .forEach(order -> {
                    EnterpriseBaseInfo baseInfo = enterpriseBaseInfoDao.findOne(order.getEnuu());
                    order.setEnName(baseInfo.getEnName());
        });
        return orderPage;
    }

    /**
     * 更新代采订单状态，重新下载到ERP
     *
     * @param id 单据id
     * @return 操作结果
     */
    @Override
    public ResultBean reDownOrder(Long id) {
        try {
            orderDao.updateStatus(id, REPEAT_CODE, NOT_SEND_STATUS);
        } catch (RuntimeException e) {
            return new ResultBean(e);
        }
        return ResultBean.success();
    }
}
