package com.ghy.goods.service.impl;

import com.ghy.common.constant.UserConstants;
import com.ghy.common.core.text.Convert;
import com.ghy.common.exception.ServiceException;
import com.ghy.common.utils.StringUtils;
import com.ghy.goods.domain.Goods;
import com.ghy.goods.domain.GoodsStandard;
import com.ghy.goods.mapper.GoodsMapper;
import com.ghy.goods.request.AppGoodsRequest;
import com.ghy.goods.service.GoodsAreaService;
import com.ghy.goods.service.GoodsImgsService;
import com.ghy.goods.service.GoodsService;
import com.ghy.goods.service.GoodsStandardService;
import com.ghy.goods.service.DeptGoodsCategoryService;
import com.ghy.goods.domain.DeptGoodsCategory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.stream.Collectors;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 商品模块实现类
 *
 * @author clunt
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private GoodsAreaService goodsAreaService;
    @Resource
    private GoodsImgsService goodsImgsService;
    @Resource
    private GoodsStandardService goodsStandardService;
    @Resource
    private DeptGoodsCategoryService deptGoodsCategoryService;

    @Override
    @Transactional
    public int addGoods(Goods goods) {
        // 添加商品主体
        int result = goodsMapper.insertGoods(goods);

        // 给各组件插入商品主体id
        goods.getGoodsAreaList().forEach(goodsArea -> {
            goodsArea.setGoodsId(goods.getGoodsId());
        });
        goods.getGoodsImgsList().forEach(goodsImg -> {
            goodsImg.setGoodsId(goods.getGoodsId());
        });
        goods.getGoodsStandardList().forEach(goodsStandard -> {
            goodsStandard.setGoodsId(goods.getGoodsId());
            if (goodsStandard.getExtMoney() == null) {
                goodsStandard.setExtMoney(BigDecimal.ZERO);
            }
        });

        // 批量插入各组件
        goodsAreaService.batchInsert(goods.getGoodsAreaList());
        goodsImgsService.batchInsert(goods.getGoodsImgsList());
        goodsStandardService.batchInsert(goods.getGoodsStandardList());

        return result;
    }

    @Override
    public boolean checkStore(List<AppGoodsRequest> requests) {
        for (AppGoodsRequest request : requests) {
            List<GoodsStandard> list = goodsStandardService.checkStore(request);
            if (list.size() == 0) {
                return false;
            }
        }
        return true;
    }

    @Override
    public BigDecimal calculate(List<AppGoodsRequest> goodsList) {
        BigDecimal totalPay = BigDecimal.ZERO;
        for (AppGoodsRequest appGoodsRequest : goodsList) {
            GoodsStandard goodsStandard = goodsStandardService.selectById(appGoodsRequest.getGoodsStandardId());
            totalPay = totalPay.add(goodsStandard.getGoodsPrice().multiply(BigDecimal.valueOf(appGoodsRequest.getNum())));
            //修改已售数量
            goodsStandard.setSaleNum(goodsStandard.getSaleNum() + appGoodsRequest.getNum());
            goodsStandardService.updateSaleNum(goodsStandard);
        }
        return totalPay;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertGoods(Goods goods) {
        goodsMapper.insertGoods(goods);
        Assert.notNull(goods.getGoodsId(), "操作失败");
        String code = String.format("GD%019d", goods.getGoodsId());
        return goodsMapper.setCode(goods.getGoodsId(), code);
    }

    @Override
    public int updateGoods(Goods goods) {
        return goodsMapper.updateGoods(goods);
    }

    @Override
    public List<Goods> selectGoodsList(Goods goods) {
        return goodsMapper.selectGoodsList(goods);
    }

    @Override
    public Goods selectById(Long goodsId) {
        return goodsMapper.selectById(goodsId);
    }

    @Override
    public int deleteGoodsByIds(String ids) {
        Long[] goodsIds = Convert.toLongArray(ids);
        for (Long goodsId : goodsIds) {
            Goods goods = selectById(goodsId);
            if (countUserGoodsById(goods) > 0) {
                throw new ServiceException(String.format("%1$s正在使用,不能删除", goods.getGoodsName()));
            }
        }
        return goodsMapper.deleteGoodsByIds(goodsIds);
    }

    @Override
    public String checkGoodsNameUnique(Goods goods) {
        Long goodsId = StringUtils.isNull(goods.getGoodsId()) ? -1L : goods.getGoodsId();
        Goods info = goodsMapper.checkGoodsNameUnique(goods.getGoodsName());
        if (StringUtils.isNotNull(info) && info.getGoodsId().longValue() != goodsId.longValue()) {
            return UserConstants.GOODS_NAME_NOT_UNIQUE;
        }
        return UserConstants.GOODS_NAME_UNIQUE;
    }

    @Override
    public String checkGoodsCodeUnique(Goods goods) {
        Long goodsId = StringUtils.isNull(goods.getGoodsId()) ? -1L : goods.getGoodsId();
        Goods info = goodsMapper.checkGoodsCodeUnique(goods.getGoodsCode());
        if (StringUtils.isNotNull(info) && info.getGoodsId().longValue() != goodsId.longValue()) {
            return UserConstants.GOODS_CODE_NOT_UNIQUE;
        }
        return UserConstants.GOODS_CODE_UNIQUE;
    }

    @Override
    public List<Goods> selectByIds(Collection<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return new ArrayList<>(0);
        }
        return goodsMapper.selectByIds(ids);
    }

    @Override
    public List<Goods> selectByCategoryIds(Collection<Long> ids) {
        return goodsMapper.selectByCategoryIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int edit(Goods goods) {
        // 添加商品主体
        int result = goodsMapper.updateGoods(goods);

        // 给各组件插入商品主体id
        goods.getGoodsAreaList().forEach(goodsArea -> {
            goodsArea.setGoodsId(goods.getGoodsId());
        });
        goods.getGoodsImgsList().forEach(goodsImg -> {
            goodsImg.setGoodsId(goods.getGoodsId());
        });
        goods.getGoodsStandardList().forEach(goodsStandard -> {
            goodsStandard.setGoodsId(goods.getGoodsId());
            if (goodsStandard.getExtMoney() == null) {
                goodsStandard.setExtMoney(BigDecimal.ZERO);
            }
            if (goodsStandard.getGroupPrice() == null) {
                goodsStandard.setGroupPrice(BigDecimal.ZERO);
            }
        });

        // 批量删除各组件
        goodsAreaService.deleteByGoodsId(goods.getGoodsId());
        goodsImgsService.deleteByGoodsId(goods.getGoodsId());

        // 批量插入各组件
        goodsAreaService.batchInsert(goods.getGoodsAreaList());
        goodsImgsService.batchInsert(goods.getGoodsImgsList());
        goods.getGoodsStandardList().forEach(goodsStandard -> {
            if(goodsStandard.getGoodsStandardId() != null){
                goodsStandardService.update(goodsStandard);
            }else {
                List<GoodsStandard> goodsStandards = new ArrayList<>();
                goodsStandards.add(goodsStandard);
                goodsStandardService.batchInsert(goodsStandards);
            }

        });
        return result;
    }

    public int countUserGoodsById(Goods goods) {
        //TODO 校验商品是否上架
        return 0;
    }

    @Override
    public List<Goods> selectGoodsByServiceCategory(Long goodsId) {
        // Get goods info by goodsId
        Goods goods = selectById(goodsId);
        if (goods == null || goods.getDeptGoodsCategoryId() == null) {
            return new ArrayList<>();
        }
        
        // Get DeptGoodsCategory by deptGoodsCategoryId to obtain serviceCategory
        DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.selectOneByGoodsCategoryId(goods.getDeptGoodsCategoryId());
        if (deptGoodsCategory == null || deptGoodsCategory.getServiceCategoryId() == null) {
            return new ArrayList<>();
        }
        
        // Query all goods using this service category ID
        Goods queryGoods = new Goods();
        queryGoods.setDeptGoodsCategoryId(deptGoodsCategory.getServiceCategoryId());
        queryGoods.setStatus(0); // Only query active goods
        List<Goods> goodsList = selectGoodsList(queryGoods);
        
        // If no goods found, try using fourth-level category query
        if (goodsList.isEmpty()) {
            DeptGoodsCategory serviceDeptCategory = deptGoodsCategoryService.selectOneByGoodsCategoryId(deptGoodsCategory.getServiceCategoryId());
            if (serviceDeptCategory != null) {
                // Use GoodsStandardService method to get goods list
                goodsList = goodsStandardService.selectGoodsByDeptGoodsCategoryId(serviceDeptCategory.getDeptGoodsCategoryId());
                // Filter to keep only active goods
                goodsList = goodsList.stream()
                    .filter(item -> item.getStatus() != null && item.getStatus() == 0)
                    .collect(Collectors.toList());
            }
        }
        
        return goodsList;
    }

}
