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

import com.uas.platform.b2b.dao.NotExistOrdersDao;
import com.uas.platform.b2b.erp.exception.NotFoundUtils;
import com.uas.platform.b2b.model.NotExistOrders;
import com.uas.platform.b2b.service.NotExistOrderService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.model.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 长平台不存在的ERP单据信息
 *
 * Created by hejq on 2018-06-19.
 */
@Service
public class NotExistOrderServiceImpl implements NotExistOrderService {

    @Autowired
    private NotExistOrdersDao ordersDao;

    /**
     * 通过企业UU和下载状态查询单据
     *
     * @param enUU   企业UU
     * @param status 下载状态
     * @param type   单据类型
     * @return
     */
    @Override
    public List<NotExistOrders> findByEnUUAndStatusAndType(Long enUU, Integer status, String type) {
        return ordersDao.findByEnUUAndStatusAndType(enUU, status, type);
    }

    /**
     * 根据返回id更新下载状态
     *
     * @param idArray 返回id串
     */
    @Override
    public void updateDownloadStatus(String[] idArray) {
        if (idArray.length > 0) {
            for (String id : idArray) {
                ordersDao.updateStatus(Long.valueOf(id));
            }
        }
    }

    /**
     * 通过单据编号，单据类型，序号保存未上传订单信息
     *
     * @param orderCode 单据编号
     * @param orderType 单据类型
     * @param detno     序号
     */
    @Override
    public void save(String orderCode, String orderType, Short detno) {
        Long enUU = SystemSession.getUser().getEnterprise().getUu();
        List<NotExistOrders> ordersList = ordersDao.findByEnUUAndStatusAndType(enUU, Status.NOT_UPLOAD.value(), orderType);
        if (CollectionUtils.isEmpty(ordersList)) {
            ordersDao.save(new NotExistOrders(enUU, orderCode, orderType, detno, ""));
        } else {
            NotExistOrders order = ordersList.get(0);
            if (order.getStatus() == Status.DOWNLOADED.value()) {
                order.setStatus(Status.NOT_UPLOAD.value());
                ordersDao.save(order);
            }
        }
    }

    /**
     * 批量存储单据不存在信息
     *
     * @param orders      单据编号
     * @param paramString 异常信息
     * @param sign        标志
     */
    @Override
    public void batchSave(List<NotExistOrders> orders, String paramString, String sign) {
        ordersDao.save(orders);
        NotFoundUtils.OrderNotFound(paramString, sign);
    }
}
