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

import com.uas.platform.b2b.dao.CommonDao;
import com.uas.platform.b2b.erp.model.OrderSendStatusColumn;
import com.uas.platform.b2b.erp.model.Role;
import com.uas.platform.b2b.erp.service.OrderSendStatusService;
import com.uas.platform.b2b.erp.support.ErpBufferedLogger;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.logging.BufferedLoggerManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by hejq on 2017-12-18.
 */
@Service
public class OrderSendStatusServiceImpl implements OrderSendStatusService {

    private final static ErpBufferedLogger logger = BufferedLoggerManager.getLogger(ErpBufferedLogger.class);

    @Autowired
    private CommonDao commonDao;

    @Override
    public List<OrderSendStatusColumn> getOrderInfo(List<OrderSendStatusColumn> columns, String tableName, String role) throws UnsupportedEncodingException {
        List<OrderSendStatusColumn> columnList = new ArrayList<OrderSendStatusColumn>();
        for (OrderSendStatusColumn column : columns) {
            List<OrderSendStatusColumn> statusColumnList = new ArrayList<OrderSendStatusColumn>();
            String sql = "select code,b2b_id,erp_id id from v$erp$orderid where code = '" + column.getCode()
                    + "' and sourcetable = '" + URLDecoder.decode(tableName, "UTF-8") + "' ";
            if (role.equals(Role.BUYER.name())) {
                sql = sql + "and custuu = " + SystemSession.getUser().getEnterprise().getUu();
            } else if (role.equals(Role.SELLER.name())) {
                sql = sql + "and venduu = " + SystemSession.getUser().getEnterprise().getUu();
            }
            sql = sql + " group by custuu,code,b2b_id,erp_id having count(1) = 1";
            statusColumnList =  commonDao.query(sql, OrderSendStatusColumn.class);
            if (!CollectionUtils.isEmpty(statusColumnList)) {
                statusColumnList.get(0).setId(column.getId());
                columnList.add(statusColumnList.get(0));
            }
        }
        return columnList;
    }
}
