package com.ruoyi.mall.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.mall.domain.*;
import com.ruoyi.mall.domain.query.ProductQuery;
import com.ruoyi.mall.domain.vo.ProductDetailVO;
import com.ruoyi.mall.domain.vo.ProductVO;
import com.ruoyi.mall.mapper.BrandMapper;
import com.ruoyi.mall.mapper.ProductCategoryMapper;
import com.ruoyi.mall.mapper.ProductMapper;
import com.ruoyi.mall.mapper.SkuMapper;
import com.ruoyi.system.domain.AppUser;
import com.ruoyi.system.service.YjAppUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品信息Service业务层处理
 *
 *
 * @author zcc
 */
@Service
@Slf4j
public class ProductService extends ServiceImpl<ProductMapper, Product> implements IService<Product> {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductCategoryMapper productCategoryMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private YjAppUserService userService;

    @Autowired
    private OrderItemService orderItemService;



    /**
     * 查询商品信息
     *
     * @param id 商品信息主键
     * @return 商品信息
     */
    public ProductVO selectById(Long id) {
        Product product = productMapper.selectById(id);
        ProductVO productVO = BeanUtil.toBean(product,ProductVO.class);
        getProductManager(productVO,product);
        QueryWrapper<Sku> qw = new QueryWrapper<>();
        qw.eq("product_id", product.getId());
        List<Sku> skus = skuMapper.selectList(qw);
        productVO.setSkuList(skus);
        return productVO;
    }

    /**
     * 查询商品信息列表
     *
     * @param query 查询条件
     * @param page 分页条件
     * @return 商品信息
     */
    public List<Product> selectList(ProductQuery query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        SysUser loginUser=SecurityUtils.getLoginUser().getUser();



        //租户管理员 查全部商品
        if (loginUser.getRoles().stream().anyMatch(it -> it.getRoleId().equals(new Long(100)))){
            query.setTenantId(loginUser.tenantId);
        }else {
            //店员 查本店
            query.setStoreId(SecurityUtils.getDeptId());
        }

        return productMapper.selectByEntity(query);
    }

    public void getIds(ProductQuery query){

        if (ObjectUtil.isNotEmpty(query.getBrandNameLike())){

            List<Brand> brands= brandMapper.selectList(new QueryWrapper<Brand>()
                    .eq("store_id",SecurityUtils.getDeptId())
                    .like("name","%".concat(query.getBrandNameLike()).concat("%")));
            if (brands.size()>0){
                List<Long> brandsIds =  brands.stream()
                        .map(it -> it.getId()).collect(Collectors.toList());
                query.setBrandIds(brandsIds);
            }

        }
        if (ObjectUtil.isNotEmpty(query.getProductCategoryNameLike())){

            List<ProductCategory> categories= productCategoryMapper.selectList(new QueryWrapper<ProductCategory>()
                    .eq("store_id",SecurityUtils.getDeptId())
                    .like("type_name","%".concat(query.getProductCategoryNameLike()).concat("%")));
            if (categories.size()>0){
                List<Long> ids =  categories.stream()
                        .map(it -> it.getId()).collect(Collectors.toList());
                query.setCategoryIds(ids);
            }

        }


    }
    /**
     * 新增商品信息
     *
     * @param productVO 商品信息
     * @return 结果
     */
    @Transactional
    public int insert(ProductVO productVO) {
        LoginUser loginUser= SecurityUtils.getLoginUser();
        Product product = BeanUtil.toBean(productVO,Product.class);
        product.setCreateTime(LocalDateTime.now());
        product.setStoreId(SecurityUtils.getDeptId());
        product.setTenantId(SecurityUtils.getLoginUser().getNowTenantId());
        setProductManager(productVO,product);

        List<Sku> skuList = productVO.getSkuList();
        if(loginUser.getPermissions().contains("pms:review:list")
                ||loginUser.getPermissions().contains("*:*:*")){
             if (ObjectUtil.isEmpty(productVO.getCategoryId())){
                 throw new RuntimeException("请选择商品分类");
             }
        }else {
            product.setCategoryId(1l);//默认为场馆商品
        }

        productMapper.insert(product);
        if(skuList!=null){
            skuList.forEach(sku -> {
                sku.setProductId(product.getId());
                sku.setUnit(product.getUnit());
                sku.setCreateTime(LocalDateTime.now());
                skuMapper.insert(sku);
            });
        }
        return 1;
    }

    public void setProductManager(ProductVO productVO,Product product){
        if (ObjectUtil.isEmpty(productVO.getCustomerService())){
            throw new RuntimeException("请选择客服/顾问");
        }
        if (productVO.getIsCourse().equals(new Integer(1))){
            if (ObjectUtil.isEmpty(productVO.getInstructor())){
                throw new RuntimeException("请选择教练");
            }else {
                AppUser instructor=  userService.getOne(new QueryWrapper<AppUser>().eq("manage_account_id",productVO.getInstructor()));
                product.setInstructor(instructor.getId());
            }

        }
        AppUser customerService=  userService.getOne(new QueryWrapper<AppUser>().eq("manage_account_id",productVO.getCustomerService()));
        product.setCustomerService(customerService.getId());
    }
    public void getProductManager(ProductVO productVO,Product product){
        if (ObjectUtil.isNotEmpty(product.getCustomerService())){
            AppUser customerService=  userService.getById(product.getCustomerService());
            productVO.setCustomerService(customerService.getManageAccountId());
        }
        if (ObjectUtil.isNotEmpty(product.getInstructor())){
            AppUser instructor=  userService.getById(product.getInstructor());
            productVO.setInstructor(instructor.getManageAccountId());
        }
    }

    /**
     * 修改商品信息
     *
     * @param productVO 商品信息
     * @return 结果
     */
    @Transactional
    public int update(ProductVO productVO) {
        Product dbProduct = productMapper.selectById(productVO.getId());
        List<Long> idList = productVO.getSkuList().stream().filter(it -> it.getId() != null).map(it -> it.getId()).collect(Collectors.toList());
        if (dbProduct == null) {
            return 0;
        }
        Long userId = SecurityUtils.getUserId();
        Product product = BeanUtil.toBean(productVO,Product.class);
        List<Sku> skuList = productVO.getSkuList();
        product.setUpdateBy(userId);
        product.setUpdateTime(LocalDateTime.now());
        product.setStoreId(SecurityUtils.getDeptId());
        setProductManager(productVO,product);
        productMapper.updateById(product);
        //查找库中所有的sku
        Map<String,Object> map = new HashMap<>();
        map.put("product_id", product.getId());
        Map<Long, Sku> skuMap = skuMapper.selectByMap(map).stream().collect(Collectors.toMap(it -> it.getId(), it -> it));
        //针对已有的进行编辑
        List<Sku> updateList = productVO.getSkuList().stream().filter(it -> it.getId() != null).collect(Collectors.toList());
        if (!CollectionUtil.isEmpty(updateList)) {
            log.info("共有{}个sku需要修改，{}，productId：{}",updateList.size(), JSONUtil.toJsonStr(updateList),productVO.getId());
            updateList.forEach(it->{
                Sku sku = skuMap.get(it.getId());
                sku.setUpdateBy(SecurityUtils.getUserId());
                sku.setUpdateTime(LocalDateTime.now());
                sku.setUnit(it.getUnit());
                sku.setPrice(it.getPrice());
                sku.setSpData(it.getSpData());
                sku.setPic(it.getPic());
                sku.setOutSkuId(it.getOutSkuId());
                sku.setStock(it.getStock());
                skuMapper.updateById(sku);
            });
        }
        //针对没有的进行新增
        List<Sku> addList = productVO.getSkuList().stream().filter(it -> it.getId() == null).collect(Collectors.toList());
        if (!CollectionUtil.isEmpty(addList)) {
            log.info("共有{}个sku需要新增，{}，productId：{}",addList.size(), JSONUtil.toJsonStr(addList),productVO.getId());
            addList.forEach(sku -> {
                sku.setProductId(product.getId());
                sku.setCreateTime(LocalDateTime.now());
                skuMapper.insert(sku);
            });
        }
        //删除
        List<Long> deleteIds = skuMap.keySet().stream().filter(it -> !idList.contains(it)).collect(Collectors.toList());
        if (!CollectionUtil.isEmpty(deleteIds)) {
            log.info("共有{}个sku需要删除，{}，productId：{}",deleteIds.size(), JSONUtil.toJsonStr(deleteIds),productVO.getId());
            skuMapper.deleteBatchIds(deleteIds);
        }
        return 1;
    }

    /**
     * 删除商品信息信息
     *
     * @param id 商品信息主键
     * @return 结果
     */
    public int deleteById(Long id) {
       int orderCount= orderItemService.count(new QueryWrapper<OrderItem>().eq("product_id",id));
       if (orderCount>0){
           throw new RuntimeException("商品已生成订单，无法删除！");
       }
       //sku product_show 数据库级联删除
        return productMapper.deleteById(id);
    }

    public ProductDetailVO queryDetail(Long id) {
        ProductDetailVO res = new ProductDetailVO();
        Product d = productMapper.selectById(id);
        res.setProduct(d);
        LambdaQueryWrapper<Sku> qw = new LambdaQueryWrapper<>();
        qw.eq(Sku::getProductId, id);
        res.setSkus(skuMapper.selectList(qw));
        if (d.getBrandId() != null) {
            res.setBrand(brandMapper.selectById(d.getBrandId()));
        }
        return res;
    }
}
