package com.uas.platform.b2b.erp.controller;

import com.uas.platform.b2b.erp.model.Prod;
import com.uas.platform.b2b.erp.support.ErpBufferedLogger;
import com.uas.platform.b2b.model.NotExistProduct;
import com.uas.platform.b2b.service.NotExistProductService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.logging.BufferedLoggerManager;
import com.uas.platform.core.model.Status;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * 对ERP的数据接口<br> -- B2B物料传输都使用物料传输公共服务，禁用物料仍调用本接口。--dongbw 2018年1月31日 13:46:45
 * 产品处理
 *
 * @author yingp
 *
 */
@Controller
@RequestMapping("/erp/product")
public class ProdController {

	@Autowired
    private NotExistProductService notExistProductService;

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

    /**
     * 获取未下载的物料信息
     * @return
     */
    @RequestMapping(value = "/notExistProds", method = RequestMethod.GET)
	@ResponseBody
	public List<Prod> findNotExistProducts() {
        List<Prod> prods = covert(notExistProductService.findByEnuuAndStatus(SystemSession.getUser().getEnterprise().getUu(), Status.NOT_UPLOAD.value()));
        logger.log("物料资料", "ERP获取平台未上传的物料信息", prods.size());
        return prods;
	}

    private List<Prod> covert(List<NotExistProduct> productList) {
        List<Prod> prods = new ArrayList<Prod>();
        if (!CollectionUtils.isEmpty(productList)) {
            for (NotExistProduct product : productList) {
                Prod prod = new Prod();
                prod.setB2b_id(product.getId());
                prod.setPr_code(product.getCode());
                prods.add(prod);
            }
        }
        return prods;
    }

    /**
     * 获取数据后更新下载状态
     *
     * @param data 封装的id串
     * @throws Exception
     */
    @RequestMapping(value = "/notExistProds/back", method = RequestMethod.POST)
    @ResponseBody
    public void updateNotExistProdsStatus(@RequestParam("data") String data) throws Exception {
        notExistProductService.updateDownloadStatus(URLDecoder.decode(data, "UTF-8").split(","));
        logger.log("物料资料", "ERP获取平台未上传的物料信息返回更新下载状态", URLDecoder.decode(data, "UTF-8").split(",").length);
    }
}
