package cn.iocoder.yudao.module.visit.service.product;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.validation.ValidationUtils;
import cn.iocoder.yudao.framework.datapermission.core.util.DataPermissionUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.validation.ConstraintViolationException;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.visit.controller.admin.product.vo.*;
import cn.iocoder.yudao.module.visit.dal.dataobject.product.ProductDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.visit.dal.mysql.product.ProductMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;
import static cn.iocoder.yudao.module.visit.enums.ErrorCodeConstants.*;

/**
 * 产品 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class ProductServiceImpl implements ProductService {

    @Resource
    private ProductMapper productMapper;

    @Override
    public Long createProduct(ProductSaveReqVO createReqVO) {
        // 插入
        ProductDO product = BeanUtils.toBean(createReqVO, ProductDO.class);
        productMapper.insert(product);
        // 返回
        return product.getId();
    }

    @Override
    public void updateProduct(ProductSaveReqVO updateReqVO) {
        // 校验存在
        validateProductExists(updateReqVO.getId());
        //按id查，取出归属companyId
        ProductDO productDO = productMapper.selectById(updateReqVO.getId());
        // 更新
        ProductDO updateObj = BeanUtils.toBean(updateReqVO, ProductDO.class);
        if (productDO != null){
            updateObj.setCompanyId(productDO.getCompanyId());
        }
        productMapper.updateById(updateObj);
    }

    @Override
    public void deleteProduct(Long id) {
        // 校验存在
        validateProductExists(id);
        // 删除
        productMapper.deleteById(id);
    }



    @Override
    public void deleteProductByIds(List<Long> idList) {
        //  校验存在
        if(productMapper.selectByIds(idList).size()  != idList.size()){
            throw exception(PRODUCT_LIST_NOT_EXISTS);
        }
        // 删除
        productMapper.deleteByIds(idList);
    }

    private void validateProductExists(Long id) {
        if (productMapper.selectById(id) == null) {
            throw exception(PRODUCT_NOT_EXISTS);
        }
    }

    @Override
    public ProductDO getProduct(Long id) {
        return productMapper.selectById(id);
    }

    @Override
    public PageResult<ProductDO> getProductPage(ProductPageReqVO pageReqVO) {
        Long companyId = SecurityFrameworkUtils.getLoginUserDeptId();
        pageReqVO.setCompanyId(companyId);
        return productMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务，异常则回滚所有导入
    public ProductImportRespVO importProductList(List<ProductImportExcelVO> importProducts, Boolean isUpdateSupport) {
        // 1 参数校验
        if (CollUtil.isEmpty(importProducts)) {
            throw exception(PRODUCT_IMPORT_LIST_IS_EMPTY);
        }

        // 2. 遍历，逐个创建 or 更新
        ProductImportRespVO respVO = ProductImportRespVO.builder().createProductNames(new ArrayList<>())
                .updateProductNames(new ArrayList<>()).failureProductNames(new LinkedHashMap<>()).build();
        importProducts.forEach(importProduct -> {

            // 2.1.1 校验，判断是否有不符合的原因
            try {
                validateProductUnique(importProduct.getProductName(), importProduct.getSpecification(), importProduct.getPackageName());
            } catch (ServiceException ex) {
                respVO.getFailureProductNames().put(importProduct.getProductName()+importProduct.getSpecification()+importProduct.getPackageName(), ex.getMessage());
                return;
            }

            // 2.2.1 判断如果不存在，在进行插入
            ProductDO existProduct = productMapper.selectByProductParam(importProduct.getProductName(),importProduct.getSpecification(), importProduct.getPackageName());
            if (existProduct == null) {
                productMapper.insert(BeanUtils.toBean(importProduct, ProductDO.class));
                respVO.getCreateProductNames().add(importProduct.getProductName()+importProduct.getSpecification()+importProduct.getPackageName());
            }
        });
        return respVO;
    }

    @Override
    public List<ProductSimpleReqVO> getProductByIds(String productIds) {
        //1.判断productIds是否为空
        if (StrUtil.isEmpty(productIds)) {
            return new ArrayList<>();
        }
        //2.按逗号切分成数组
        String[] ids = productIds.split(",");
        //3.判断数组长度
        if (ids.length > 0) {
            Long companyId = SecurityFrameworkUtils.getLoginUserDeptId();
            List<ProductDO> productDOS = productMapper.selectByIds(Arrays.asList(ids), companyId);
            return BeanUtils.toBean(productDOS, ProductSimpleReqVO.class);
        }
        return new ArrayList<>();
    }


    private void validateProductUnique(String productName, String specification, String packageName) {
        ProductPageReqVO productPageReqVO = new ProductPageReqVO();
        productPageReqVO.setProductName(productName);
        productPageReqVO.setSpecification(specification);
        productPageReqVO.setPackageName(packageName);
        Long companyId = SecurityFrameworkUtils.getLoginUserDeptId();
        productPageReqVO.setCompanyId(companyId);
        PageResult<ProductDO> productDOPageResult = productMapper.selectPage(productPageReqVO);
        if (productDOPageResult.getTotal() > 0) {
            throw exception(PRODUCT_PRODUCT_EXISTS);
        }
    }

}