package com.hzs.sale.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.domain.sale.ext.BdProductExt;
import com.hzs.common.domain.sale.product.BdProduct;
import com.hzs.common.domain.sale.product.BdProductExtend;
import com.hzs.common.domain.sale.product.BdProductSpecs;
import com.hzs.common.domain.sale.wares.BdUnit;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.sale.product.vo.BdProductSpecsInfo;
import com.hzs.sale.product.vo.ProductSpecsVo;
import com.hzs.sale.product.controller.manage.params.ProductParams;
import com.hzs.sale.product.mapper.BdProductMapper;
import com.hzs.sale.product.service.IBdProductExtendService;
import com.hzs.sale.product.service.IBdProductService;
import com.hzs.sale.product.service.IBdProductSpecsService;
import com.hzs.sale.product.vo.ProductVo;
import com.hzs.sale.unit.service.IBdUnitService;
import com.hzs.system.base.ITransactionServiceApi;
import com.hzs.system.sys.dto.LoginUser;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 产品 服务实现类
 */
@Service
public class BdProductServiceImpl extends ServiceImpl<BdProductMapper, BdProduct> implements IBdProductService {

    @Autowired
    private IBdProductSpecsService productSpecsService;
    @Autowired
    private IBdProductService productService;
    @Autowired
    private IBdProductExtendService productExtendService;
    @Autowired
    private IBdUnitService unitService;
    @Autowired
    private RedisService redisService;

    @DubboReference
    ITransactionServiceApi transactionServiceApi;


    @Override
    public BdProduct getProduct(Integer pkProduct) {
        BdProduct bdProduct = redisService.getCacheObject(CacheConstants.BD_PRODUCT + pkProduct);
        if (bdProduct == null) {
            bdProduct = baseMapper.selectById(pkProduct);
            if (bdProduct != null) {
                redisService.setCacheObject(CacheConstants.BD_PRODUCT + bdProduct.getPkId(), bdProduct);
            }
        }
        return bdProduct;
    }

    @Override
    public List<BdProductExt> queryProductExtById(List<BdProductSpecs> productSpecsList, Integer pkCountry) {
        return baseMapper.queryProductExtBySpecsId(productSpecsList, pkCountry);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveProduct(ProductParams productParams, LoginUser loginUser) {
        String productCode = productParams.getProductCode();
        BdProduct bdProduct = BeanUtil.copyProperties(productParams, BdProduct.class);
        R<Integer> transaction = transactionServiceApi.createTransaction(loginUser.getDataCountry(), ETransactionKey.PRODUCT, productParams.getProductName(), EYesNo.NO, EYesNo.NO);
        bdProduct.setProductCode(productCode);
        bdProduct.setPkTransaction(transaction.getData());
        bdProduct.setPkCreator(loginUser.getUserId());
        bdProduct.setCreationTime(new Date());
        bdProduct.setPkCreator(loginUser.getUserId());
        bdProduct.setPkCountry(loginUser.getDataCountry());
        // 删除状态 审核完毕 修改为未删除状态
        bdProduct.setDelFlag(EDelFlag.UN_DELETE.getValue());
        productService.save(bdProduct);
        // 生成拓展表
        BdProductExtend productExtend = BeanUtil.copyProperties(productParams, BdProductExtend.class);
        productExtend.setPkProduct(bdProduct.getPkId());
        productExtend.setPkCreator(loginUser.getUserId());
        productExtend.setCreationTime(new Date());
        productExtend.setPkCountry(loginUser.getDataCountry());
        productExtend.setDelFlag(EDelFlag.UN_DELETE.getValue());
        productExtendService.save(productExtend);
        // 生成规格明细
        if (productParams.getPkSpecsType() != null) {
            for (Integer id : productParams.getPkSpecsType()) {
                BdProductSpecs productSpecs = new BdProductSpecs();
                productSpecs.setPkProduct(bdProduct.getPkId());
                productSpecs.setPkSpecsType(id);
                productSpecs.setPkCountry(loginUser.getDataCountry());
                productSpecs.setPkCreator(loginUser.getUserId());
                productSpecs.setCreationTime(new Date());
                productSpecsService.save(productSpecs);
            }
        }
        removeProductCache(bdProduct.getPkId());
        return productCode;
    }

    /**
     * 删除产品相关缓存
     *
     * @param productId
     */
    public void removeProductCache(Integer productId) {
        redisService.deleteObject(CacheConstants.BD_PRODUCT + productId);
        redisService.deleteObject(CacheConstants.BD_PRODUCT_EXTEND + productId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProduct(ProductParams productParams, LoginUser loginUser) {
        BdProduct bdProduct = BeanUtil.copyProperties(productParams, BdProduct.class);
        R<Integer> transaction = transactionServiceApi.createTransaction(loginUser.getDataCountry(), ETransactionKey.PRODUCT, productParams.getProductName(), EYesNo.NO, EYesNo.NO);
        bdProduct.setPkId(productParams.getPkId());
        bdProduct.setPkTransaction(transaction.getData());
        bdProduct.setPkModified(loginUser.getUserId());
        bdProduct.setModifiedTime(new Date());
        productService.updateById(bdProduct);
        // 生成拓展表
        BdProductExtend productExtend = BeanUtil.copyProperties(productParams, BdProductExtend.class);
        productExtend.setPkProduct(bdProduct.getPkId());
        QueryWrapper<BdProductExtend> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_PRODUCT", productParams.getPkId());
        productExtendService.update(productExtend, queryWrapper);
        // 删除缓存
        removeProductCache(productParams.getPkId());
        // 生成规格明细
        if (productParams.getPkSpecsType() != null) {
            QueryWrapper<BdProductSpecs> removeWrapper = new QueryWrapper<>();
            removeWrapper.eq("PK_PRODUCT", bdProduct.getPkId());
            productSpecsService.remove(removeWrapper);
            for (Integer id : productParams.getPkSpecsType()) {
                BdProductSpecs productSpecs = new BdProductSpecs();
                productSpecs.setPkProduct(bdProduct.getPkId());
                productSpecs.setPkSpecsType(id);
                productSpecs.setPkCountry(loginUser.getDataCountry());
                productSpecs.setPkCreator(loginUser.getUserId());
                productSpecs.setCreationTime(new Date());
                productSpecsService.save(productSpecs);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeProduct(Integer pkId) {
        UpdateWrapper<BdProduct> productWrapper = new UpdateWrapper<BdProduct>();
        productWrapper.eq("PK_ID", pkId);
        productWrapper.set("PK_MODIFIED", SecurityUtils.getUserId());
        productWrapper.set("MODIFIED_TIME", new Date());
        productWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        productService.update(productWrapper);
        // 更新商品拓展表
        UpdateWrapper<BdProductExtend> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("PK_PRODUCT", pkId);
        updateWrapper.set("PK_MODIFIED", SecurityUtils.getUserId());
        updateWrapper.set("MODIFIED_TIME", new Date());
        updateWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        productExtendService.update(updateWrapper);
        // 逻辑删除规格明细表
        BdProductSpecs bdProductSpecs = new BdProductSpecs();
        bdProductSpecs.setDelFlag(EDelFlag.DELETE.getValue());
        bdProductSpecs.setModifiedTime(new Date());
        bdProductSpecs.setPkModified(SecurityUtils.getUserId());
        QueryWrapper<BdProductSpecs> wrapper = new QueryWrapper<BdProductSpecs>();
        wrapper.eq("PK_PRODUCT", pkId);
        productSpecsService.update(bdProductSpecs, wrapper);
    }

    @Override
    public String getLastProductCode() {
        return baseMapper.getLastProductCode();
    }

    @Override
    public List<ProductVo> selectByQueryList(ProductParams productParams) {
        return baseMapper.selectByQueryList(productParams);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void productMove(Integer productId, Integer productMoveType) {
        // BdProduct bdProduct = baseMapper.selectById(productId);
        // 产品上移
        if (productMoveType == EProductMoveType.MOVEUP.getIntValue()) {
            // 产品上移  根据当前商品查找当前商品排序之前一个序号  如是15 则查找 16 存不存在 如果存在 则 16 之前的全部+1
            Integer sort = productExtendService.selectByMoveUpSort(productId);
            if (sort != null) {
                Integer maxSort = sort + 1;
                // 查询该排序号码是否重复
                QueryWrapper<BdProductExtend> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("SORT", maxSort);
                int count = productExtendService.count(queryWrapper);
                if (count > 0) {
                    // 表示该号码已存在 将该号码之前的全都上移一位 并且将产品修改为该号码
                    productExtendService.updateMoveUpBySort(maxSort);
                    UpdateWrapper<BdProductExtend> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("PK_PRODUCT", productId);
                    updateWrapper.set("SORT", maxSort);
                    productExtendService.update(updateWrapper);
                } else {
                    UpdateWrapper<BdProductExtend> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("PK_PRODUCT", productId);
                    updateWrapper.set("SORT", maxSort);
                    productExtendService.update(updateWrapper);
                }
            }
        } else if (productMoveType == EProductMoveType.MOVEDOWN.getIntValue()) {
            // 产品下移
            // 产品下移  根据当前商品查找当前商品排序之后一个序号  如是15 则查找 14 存不存在 如果存在 则 14 之前的全部-1
            Integer sort = productExtendService.selectByMoveDownSort(productId);
            if (sort != null) {
                Integer minSort = sort - 1;
                // 查询该排序号码是否重复
                QueryWrapper<BdProductExtend> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("SORT", minSort);
                int count = productExtendService.count(queryWrapper);
                if (count > 0) {
                    // 表示该号码已存在 将该号码之下的全都下移一位 并且将产品修改为该号码
                    productExtendService.updateMoveDownBySort(minSort);
                    UpdateWrapper<BdProductExtend> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("PK_PRODUCT", productId);
                    updateWrapper.set("SORT", minSort);
                    productExtendService.update(updateWrapper);
                } else {
                    UpdateWrapper<BdProductExtend> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("PK_PRODUCT", productId);
                    updateWrapper.set("SORT", minSort);
                    productExtendService.update(updateWrapper);
                }
            }
        }

    }

    @Override
    public void floatingRoof(Integer productId) {
        Integer sort = productExtendService.getMaxProductSort();
        UpdateWrapper<BdProductExtend> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("PK_PRODUCT", productId);
        updateWrapper.set("SORT", sort + 1);
        productExtendService.update(updateWrapper);
    }

    @Override
    public Map<Integer, BdProduct> queryProductMap(List<Integer> pkProductList, Integer pkCountry) {
        Map<Integer, BdProduct> resultMap = new HashMap<>();

        QueryWrapper<BdProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(SystemFieldConstants.PK_ID, pkProductList);
        if (null != pkCountry) {
            queryWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        }
        List<BdProduct> productList = this.list(queryWrapper);

        if (CollectionUtil.isNotEmpty(productList)) {
            for (BdProduct bdProduct : productList) {
                resultMap.put(bdProduct.getPkId(), bdProduct);
            }
        }

        return resultMap;
    }

    @Override
    public List<BdProductExt> queryProductExistSpecs(Integer pkCountry, String query) {
        return baseMapper.queryProductExistSpecs(pkCountry, query);
    }

    @Override
    public ProductVo getByProductId(Integer productId) {
        return baseMapper.getByProductId(productId);
    }

    @Override
    public ProductVo getByProductCodeInfo(String productCode, Integer pkCountry) {
        BdProduct product = productService.getOne(new QueryWrapper<BdProduct>().eq("PRODUCT_CODE", productCode));
        ProductVo productVo = new ProductVo();
        if (product != null) {

            List<ProductSpecsVo> productSpecsVos = productSpecsService.queryListByProductId(product.getPkId(), pkCountry);
            for (ProductSpecsVo productSpecs : productSpecsVos) {
                List<BdProductSpecsInfo> specsList = productSpecsService.findByPkSpecsType(productSpecs.getPkSpecsType());
                productSpecs.setProductSpecsList(specsList);
            }
            productVo.setProductSpecsList(productSpecsVos);

            productVo.setPkId(product.getPkId());
            productVo.setProductCode(product.getProductCode());
            productVo.setProductName(product.getProductName());
            // 单位
            BdUnit unit = unitService.getById(product.getUnit());
            if (unit != null) {
                productVo.setUnit(product.getUnit());
                productVo.setUnitStr(unit.getName());
            }
        }
        return productVo;
    }

}
