package com.cftech.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.StringUtils;
import com.cftech.product.model.Product;
import com.cftech.product.dao.ProductMapper;
import com.cftech.product.model.ProductVO;
import com.cftech.product.service.ProductService;
import com.cftech.core.generic.GenericDao;
import com.cftech.core.generic.GenericServiceImpl;
import com.cftech.core.sql.Conds;
import com.cftech.productdetail.dao.ProductDetailMapper;
import com.cftech.productdetail.model.ProductDetail;
import com.cftech.productintowareroom.dao.ProductIntoWareroomMapper;
import com.cftech.productintowareroom.model.ProductIntoWareroom;
import com.esotericsoftware.minlog.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品ServiceImpl
 *
 * @author Buyj
 * @date: 2020-09-24 15:07
 */
@Service("productService")
public class ProductServiceImpl extends GenericServiceImpl<Product> implements ProductService {


    @Autowired
    @Qualifier("productMapper")
    private ProductMapper productMapper;

    @Autowired
    private ProductIntoWareroomMapper productIntoWareroomMapper;

    @Autowired
    private ProductDetailMapper productDetailMapper;

    @Autowired
    private CodingruleUtils codingruleUtils;

    @Override
    public GenericDao<Product> getGenericMapper() {
        return productMapper;
    }


    /**
     * 保存导入商品信息并生成商品入库单记录和商品明细记录
     *
     * @param product
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveProduct(Product product) {
        // 1、保存商品实体 根据商品编码判断该商品是否存在 存在则更新  不存在则新增
        Map<String, Object> params = new HashMap<>();
        Conds conds = new Conds();
        conds.equal("a.product_number", product.getProductNumber());
        conds.equal("a.del_flag", 0);
        params.put("conds", conds);
        List<Product> listProduct = productMapper.fetchSearchByPage(params);
        if (listProduct.size() > 0) {
            Product productEntity = listProduct.get(0);
            if (StringUtils.isNotBlank(product.getClassifyNumber())) {
                productEntity.setClassifyNumber(product.getClassifyNumber());
            }
            if (StringUtils.isNotBlank(product.getProductName())) {
                productEntity.setProductName(product.getProductName());
            }
            if (StringUtils.isNotBlank(product.getCommonName())) {
                productEntity.setCommonName(product.getCommonName());
            }
            if (StringUtils.isNotBlank(product.getDosagaFrom())) {
                productEntity.setDosagaFrom(product.getDosagaFrom());
            }
            if (StringUtils.isNotBlank(product.getFormat())) {
                productEntity.setFormat(product.getFormat());
            }
            if (StringUtils.isNotBlank(product.getApproveNumber())) {
                productEntity.setApproveNumber(product.getApproveNumber());
            }
            if (StringUtils.isNotBlank(product.getManufacturer())) {
                productEntity.setManufacturer(product.getManufacturer());
            }
            if (StringUtils.isNoneBlank(product.getRecommendMeasure())) {
                productEntity.setRecommendMeasure(product.getRecommendMeasure());
            }
            if (StringUtils.isNoneBlank(product.getDescription())) {
                productEntity.setDescription(product.getDescription());
            }
            if (StringUtils.isNoneBlank(product.getTips())) {
                productEntity.setTips(product.getTips());
            }
            if (StringUtils.isNoneBlank(product.getTakeType())) {
                productEntity.setTakeType(product.getTakeType());
            }
            if (StringUtils.isNotBlank(product.getTakeFrequency())) {
                productEntity.setTakeFrequency(product.getTakeFrequency());
            }
            if (StringUtils.isNotBlank(product.getTakeAmount())) {
                productEntity.setTakeAmount(product.getTakeAmount());
            }
            if (StringUtils.isNotBlank(String.valueOf(product.getStock()))) {
                productEntity.setStock((new BigDecimal(productEntity.getStock()).add(new BigDecimal(product.getStock()))).longValue());
            }
            if (StringUtils.isNotBlank(String.valueOf(product.getPrice()))) {
                productEntity.setPrice(product.getPrice());
            }
            if (StringUtils.isNotBlank(product.getIsRs())) {
                productEntity.setIsRs(product.getIsRs());
            }
            productMapper.update(productEntity);
        } else {
            productMapper.save(product);
        }

        System.out.println(Product.class.getName());


        // 2、 生成入库单
        ProductIntoWareroom productIntoWareroom = new ProductIntoWareroom();
        productIntoWareroom.setAccountsId(product.getAccountsId());
        productIntoWareroom.setIntoWareroomNumber(product.getRuKuNumber());
        productIntoWareroom.setProductSkuNumber("SKU");
        productIntoWareroom.setProductNumber(product.getProductNumber());
        productIntoWareroom.setProductName(product.getProductName());
        productIntoWareroom.setProductAmount(product.getStock());
        productIntoWareroom.setProductClassifyNumber(product.getClassifyNumber());
        productIntoWareroom.setCreateBy(product.getCreateBy());
        productIntoWareroom.setUpdateBy(product.getUpdateBy());
        productIntoWareroomMapper.save(productIntoWareroom);

        // 3、生成商品明细表
        ProductDetail productDetail = null;
        if (product.getStock() != null && product.getStock() > 0) {
            for (int i = 0; i < product.getStock().intValue(); i++) {
                productDetail = new ProductDetail();
                productDetail.setAccountsId(product.getAccountsId());
                productDetail.setProductDetailNumber(codingruleUtils.getNumber(product.getAccountsId(), ProductDetail.class.getName()));
                productDetail.setMaterielNumber(codingruleUtils.getNumber(product.getAccountsId(), "com.cftech.productmaterie.model.Materie"));
                productDetail.setProductNumber(product.getProductNumber());
                productDetail.setProductName(product.getProductName());
                productDetail.setProductClassifyNumber(product.getClassifyNumber());
                productDetail.setIntoWareroomNumber(product.getRuKuNumber());
                productDetail.setWhetherSell("否");
                productDetail.setCreateBy(product.getCreateBy());
                productDetail.setUpdateBy(product.getUpdateBy());
                productDetailMapper.save(productDetail);
            }
        }


        return true;
    }

    @Override
    public JSONObject productId(Long ID) {
         JSONObject rtnJson = new JSONObject();
         try {
             if (ID.equals("")){
                rtnJson.put("errorNO","1");
                rtnJson.put("errorMsg","id不能为空");
             }
             List<ProductVO> product = productMapper.product(ID);
             if (product==null){
                 rtnJson.put("errorNO","1");
                 rtnJson.put("errorMsg","查询失败");
             }
             Log.info("返回结果:"+product);
             rtnJson.put("errorNO","0");
             rtnJson.put("data",product);
         }catch (Exception e){
             e.printStackTrace();
             rtnJson.put("errorNO","1");
         }
        return rtnJson;
    }

    @Override
    public List<Product> selectProduct(Conds conds, Sort sort, int page, int pageSize, List<String> classifyId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("conds", conds);
        params.put("offset", page > 0 ? page : 0);
        params.put("limit", pageSize > 0 ? pageSize : 0);
        params.put("sort", sort);
        params.put("classifyId",classifyId);
        return productMapper.selectProduct(params);
    }


}