package com.hwrj.cloud.portal.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageHelper;
import com.hwrj.cloud.common.exception.Asserts;
import com.hwrj.cloud.portal.dao.*;
import com.hwrj.cloud.portal.domain.PmsProductVo;
import com.hwrj.cloud.portal.mapper.*;
import com.hwrj.cloud.portal.model.*;
import com.hwrj.cloud.portal.service.PortalProductPulishService;
import com.hwrj.cloud.portal.service.UmsMemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PortalProductPulishServiceImpl implements PortalProductPulishService {


    @Autowired
    private PmsProductMapper productMapper;
    @Autowired
    private PmsMemberPriceDao memberPriceDao;
    @Autowired
    private PmsMemberPriceMapper memberPriceMapper;
    @Autowired
    private PmsProductLadderDao productLadderDao;
    @Autowired
    private PmsProductLadderMapper productLadderMapper;
    @Autowired
    private PmsProductFullReductionDao productFullReductionDao;
    @Autowired
    private PmsProductFullReductionMapper productFullReductionMapper;
    @Autowired
    private PmsSkuStockDao skuStockDao;
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    @Autowired
    private PmsProductAttributeValueDao productAttributeValueDao;
    @Autowired
    private PmsProductAttributeValueMapper productAttributeValueMapper;

    @Autowired
    private UmsMemberService memberService;


    @Autowired
    private UmsCompanyInfoMapper umsCompanyInfoMapper;

    private void checkData(PmsProduct product) {
        //商品价格
        BigDecimal price = product.getPrice();
        if (StringUtils.isEmpty(price)) {
            throw new RuntimeException("商品价格不能空!");
        }
        if (price.compareTo(BigDecimal.ZERO) == -1) {
            throw new RuntimeException("商品价格不能小于0!");
        }
        BigDecimal originalPrice = product.getOriginalPrice();
        if (StringUtils.isEmpty(originalPrice)) {
            throw new RuntimeException("市场价格不能空!");
        }
        if (originalPrice.compareTo(BigDecimal.ZERO) == -1) {
            throw new RuntimeException("市场价格不能小于0!");
        }

    }


    @Override
    @Transactional
    public int create(PmsProductVo productVo) {
        int count;
        //检查数据
        checkData(productVo);
        //创建商品
        long compId = productVo.getCompId();
        if (StringUtils.isEmpty(compId)) {
            throw new RuntimeException("没有绑定供应商无法新增!");
        }
        UmsCompanyInfo umsCompanyInfo = umsCompanyInfoMapper.selectByPrimaryKey(compId);
        if(StringUtils.isEmpty(umsCompanyInfo)){
            throw new RuntimeException("供应商不存在!");
        }
        Integer compStatus = umsCompanyInfo.getCompStatus();
        if(compStatus!=0){
            throw new RuntimeException("供应商不可用!");
        }
        Map<String, Object> map = memberService.getCurrentWxUser();
        UmsMemberPlatform wxUsers = memberService.getWxUser();
        if (wxUsers == null) {
            Asserts.fail("登录异常");
        }
//        UmsCompanyShare umsCompanyShare = (UmsCompanyShare) map.get("company");
//        if (umsCompanyShare == null) {
//            Asserts.fail("没有进行供应商认证");
//        }
//        productVo.setCompId(umsCompanyShare.getCompId());
//        productVo.setCompName(umsCompanyShare.getCompName());
        productVo.setCreateId(wxUsers.getId());
        productVo.setCreateType(1);
        productVo.setCreateTime(new Date());
        productVo.setDeleteStatus(0);
        //设置销量为0
        productVo.setSale(0);
        //库存为0
        productVo.setStock(0);
        //库存预警为0
        productVo.setLowStock(0);
        //设置不是新品
        productVo.setNewStatus(0);
        //设置为不推荐
        productVo.setRecommandStatus(0);
        //活动限制数量
        productVo.setPromotionPerLimit(0);
        //设置为原价购买
        productVo.setPromotionType(0);
        //设置批发价
        productVo.setTradePrice(productVo.getPrice());
        //设置促销价格
        productVo.setPromotionPrice(productVo.getPrice());
        //限制使用的积分数
        productVo.setUsePointLimit(0);
        //是否为预告商品：0->不是；1->是
        productVo.setPreviewStatus(0);
        productVo.setVerifyStatus(0);
        PmsProduct product = productVo;
        product.setId(null);
        productMapper.insertSelective(product);
        //根据促销类型设置价格：会员价格、阶梯价格、满减价格
        Long productId = product.getId();
        //会员价格
        relateAndInsertList(memberPriceDao, productVo.getMemberPriceList(), productId);
        //阶梯价格
        relateAndInsertList(productLadderDao, productVo.getProductLadderList(), productId);
        //满减价格
        relateAndInsertList(productFullReductionDao, productVo.getProductFullReductionList(), productId);
        //处理sku的编码
        handleSkuStockCode(productVo.getSkuStockList(), productId);
        //添加sku库存信息
        relateAndInsertList(skuStockDao, productVo.getSkuStockList(), productId);
        //添加商品参数,添加自定义商品规格
        relateAndInsertList(productAttributeValueDao, productVo.getProductAttributeValueList(), productId);
//        //关联专题
//        subjectService.relateAndInsertList(productParam.getSubjectProductRelationList(), productId);
//        //关联优选
//        prefrenceAreaService.relateAndInsertList(productParam.getPrefrenceAreaProductRelationList(), productId);
        count = 1;
        return count;
    }

    @Override
    public int update(Long id, PmsProductVo productParam) {
        //检验供应商
        //check(productParam);
        int count;
        //更新商品信息
        PmsProduct product = productParam;
        product.setId(id);
//        product.setCompId(CurrUserUtil.getCompId());
        productMapper.updateByPrimaryKeySelective(product);
        //会员价格
        PmsMemberPriceExample pmsMemberPriceExample = new PmsMemberPriceExample();
        pmsMemberPriceExample.createCriteria().andProductIdEqualTo(id);
        memberPriceMapper.deleteByExample(pmsMemberPriceExample);
        relateAndInsertList(memberPriceDao, productParam.getMemberPriceList(), id);
        //阶梯价格
        PmsProductLadderExample ladderExample = new PmsProductLadderExample();
        ladderExample.createCriteria().andProductIdEqualTo(id);
        productLadderMapper.deleteByExample(ladderExample);
        relateAndInsertList(productLadderDao, productParam.getProductLadderList(), id);
        //满减价格
        PmsProductFullReductionExample fullReductionExample = new PmsProductFullReductionExample();
        fullReductionExample.createCriteria().andProductIdEqualTo(id);
        productFullReductionMapper.deleteByExample(fullReductionExample);
        relateAndInsertList(productFullReductionDao, productParam.getProductFullReductionList(), id);
        //修改sku库存信息
        handleUpdateSkuStockList(id, productParam);
        //修改商品参数,添加自定义商品规格
        PmsProductAttributeValueExample productAttributeValueExample = new PmsProductAttributeValueExample();
        productAttributeValueExample.createCriteria().andProductIdEqualTo(id);
        productAttributeValueMapper.deleteByExample(productAttributeValueExample);
        relateAndInsertList(productAttributeValueDao, productParam.getProductAttributeValueList(), id);
//        //关联专题
//        subjectService.relateAndUpdateList(productParam.getSubjectProductRelationList(), id);
//        //关联优选
//        prefrenceAreaService.relateAndUpdateList(productParam.getPrefrenceAreaProductRelationList(), id);
        count = 1;
        return count;
    }

    @Override
    public List<PmsProduct> list(Integer pageSize, Integer pageNo) {
        UmsMemberPlatform wxUsers = memberService.getWxUser();
        PmsProductExample example = new PmsProductExample();
        PmsProductExample.Criteria criteria = example.createCriteria();
        criteria.andCreateIdEqualTo(wxUsers.getId());
        criteria.andCreateTypeEqualTo(1);
        criteria.andDeleteStatusEqualTo(0);
        example.setOrderByClause("create_time desc");
        PageHelper.startPage(pageNo, pageSize);
        List<PmsProduct> pmsProducts = productMapper.selectByExample(example);
        return pmsProducts;

    }

    @Override
    public PmsProduct detail(Long id) {
        if (id == null) {
            Asserts.fail("获取详情失败");
        }
        Long memberId = memberService.getMemberId();
        if (memberId == null) {
            Asserts.fail("获取详情失败");
        }
        PmsProductExample example = new PmsProductExample();
        PmsProductExample.Criteria criteria = example.createCriteria();
        criteria.andCreateIdEqualTo(id);
        criteria.andCreateTypeEqualTo(1);
        criteria.andIdEqualTo(id);
        List<PmsProduct> pmsProducts = productMapper.selectByExample(example);
        if (pmsProducts != null && pmsProducts.size() > 0) {
            return pmsProducts.get(0);
        }

        return null;
    }


    /**
     * 建立和插入关系表操作
     *
     * @param dao       可以操作的dao
     * @param dataList  要插入的数据
     * @param productId 建立关系的id
     */
    private void relateAndInsertList(Object dao, List dataList, Long productId) {
        try {
            if (CollectionUtils.isEmpty(dataList)) return;
            for (Object item : dataList) {
                Method setId = item.getClass().getMethod("setId", Long.class);
                setId.invoke(item, (Long) null);
                Method setProductId = item.getClass().getMethod("setProductId", Long.class);
                setProductId.invoke(item, productId);
            }
            Method insertList = dao.getClass().getMethod("insertList", List.class);
            insertList.invoke(dao, dataList);
        } catch (Exception e) {
            log.warn("创建产品出错:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 处理sku编码
     *
     * @param skuStockList
     * @param productId
     */
    private void handleSkuStockCode(List<PmsSkuStock> skuStockList, Long productId) {
        if (CollectionUtils.isEmpty(skuStockList)) return;
        for (int i = 0; i < skuStockList.size(); i++) {
            PmsSkuStock skuStock = skuStockList.get(i);
            if (StringUtils.isEmpty(skuStock.getSkuCode())) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                StringBuilder sb = new StringBuilder();
                //日期
                sb.append(sdf.format(new Date()));
                //四位商品id
                sb.append(String.format("%04d", productId));
                //三位索引id
                sb.append(String.format("%03d", i + 1));
                skuStock.setSkuCode(sb.toString());
            }
        }
    }


    private void handleUpdateSkuStockList(Long id, PmsProductVo productParam) {
        //当前的sku信息
        List<PmsSkuStock> currSkuList = productParam.getSkuStockList();
        //当前没有sku直接删除
        if (CollUtil.isEmpty(currSkuList)) {
            PmsSkuStockExample skuStockExample = new PmsSkuStockExample();
            skuStockExample.createCriteria().andProductIdEqualTo(id);
            skuStockMapper.deleteByExample(skuStockExample);
            return;
        }
        //获取初始sku信息
        PmsSkuStockExample skuStockExample = new PmsSkuStockExample();
        skuStockExample.createCriteria().andProductIdEqualTo(id);
        List<PmsSkuStock> oriStuList = skuStockMapper.selectByExample(skuStockExample);
        //获取新增sku信息
        List<PmsSkuStock> insertSkuList = currSkuList.stream().filter(item -> item.getId() == null).collect(Collectors.toList());
        //获取需要更新的sku信息
        List<PmsSkuStock> updateSkuList = currSkuList.stream().filter(item -> item.getId() != null).collect(Collectors.toList());
        List<Long> updateSkuIds = updateSkuList.stream().map(PmsSkuStock::getId).collect(Collectors.toList());
        //获取需要删除的sku信息
        List<PmsSkuStock> removeSkuList = oriStuList.stream().filter(item -> !updateSkuIds.contains(item.getId())).collect(Collectors.toList());
        handleSkuStockCode(insertSkuList, id);
        handleSkuStockCode(updateSkuList, id);
        //新增sku
        if (CollUtil.isNotEmpty(insertSkuList)) {
            relateAndInsertList(skuStockDao, insertSkuList, id);
        }
        //删除sku
        if (CollUtil.isNotEmpty(removeSkuList)) {
            List<Long> removeSkuIds = removeSkuList.stream().map(PmsSkuStock::getId).collect(Collectors.toList());
            PmsSkuStockExample removeExample = new PmsSkuStockExample();
            removeExample.createCriteria().andIdIn(removeSkuIds);
            skuStockMapper.deleteByExample(removeExample);
        }
        //修改sku
        if (CollUtil.isNotEmpty(updateSkuList)) {
            for (PmsSkuStock pmsSkuStock : updateSkuList) {
                skuStockMapper.updateByPrimaryKeySelective(pmsSkuStock);
            }
        }

    }
}
