package com.czg.service.account.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.czg.account.dto.pad.*;
import com.czg.account.entity.PadLayout;
import com.czg.account.entity.PadProductCategory;
import com.czg.account.entity.PadProductCategoryDetail;
import com.czg.account.service.*;
import com.czg.constants.SystemConstants;
import com.czg.exception.CzgException;
import com.czg.product.entity.ProdSku;
import com.czg.product.entity.Product;
import com.czg.product.entity.ShopProdCategory;
import com.czg.product.service.ProdSkuService;
import com.czg.product.service.ProductRpcService;
import com.czg.product.service.ProductService;
import com.czg.product.service.ShopProdCategoryService;
import com.czg.product.vo.ProductVO;
import com.czg.service.account.mapper.PadProductCategoryDetailMapper;
import com.czg.utils.PageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.TextStyle;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * @author Administrator
 */
@Service
public class PadProdServiceImpl implements PadProdService {
    @Resource
    private PadProductCategoryDetailMapper padProductCategoryDetailMapper;
    @Resource
    private PadProductCategoryService padProductCategoryService;
    @DubboReference
    private ProductService productService;
    @DubboReference
    private ProductRpcService productRpcService;
    @DubboReference
    private ProdSkuService prodSkuService;
    @DubboReference
    private ShopProdCategoryService shopProdCategoryService;
    @Resource
    private PadLayoutService padLayoutService;
    @Resource
    private PadProductCategoryDetailService padProductCategoryDetailService;

    @Override
    public Page<PadProductCategoryDTO> pageInfo(Page<PadProductCategoryDTO> objectPage, Long productCategoryId, Long shopId) {
        PageHelper.startPage(PageUtil.buildPageHelp());
        return PageUtil.convert(new PageInfo<>(padProductCategoryDetailMapper.selectPageByKeyAndShopId(shopId, productCategoryId)));
    }

    /**
     * 计算是否在可售时间内
     *
     * @param days      星期几，例如 "Monday,Tuesday"
     * @param startTime 起售时间
     * @param endTime   停售时间
     * @return 是否可售时间 1-是，0-否
     */
    public Integer calcIsSaleTime(String days, LocalTime startTime, LocalTime endTime) {
        if (StrUtil.isBlank(days) || ObjUtil.isNull(startTime) || ObjUtil.isNull(endTime)) {
            return SystemConstants.OneZero.ZERO;
        }
        String today = getWeekDayEnName();
        List<String> dayList = StrUtil.split(days, ",");
        LocalTime now = LocalTime.now().withNano(0);
        if (CollUtil.contains(dayList, today) && now.isAfter(startTime) && now.isBefore(endTime)) {
            return SystemConstants.OneZero.ONE;
        }
        return SystemConstants.OneZero.ZERO;
    }

    /**
     * 获取当前日期是星期几的英文名称
     *
     * @return 星期几的英文名称，例如 "Monday" 或 "Friday"
     */
    private String getWeekDayEnName() {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 获取当前日期是星期几，返回一个 DayOfWeek 枚举类型的实例
        DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
        return dayOfWeek.getDisplayName(TextStyle.FULL, Locale.ENGLISH);
    }

    @Override
    public PadDetailDTO detail(Long shopId, Long padProductCategory) {
        PadProductCategory padCategory = padProductCategoryService.getOne(new QueryWrapper().eq(PadProductCategory::getShopId, shopId).eq(PadProductCategory::getId, padProductCategory));
        if (padCategory == null) {
            throw new CzgException("pad商品分类不存在");
        }

        PadDetailDTO padDetailDTO = new PadDetailDTO();
        padDetailDTO.setId(padProductCategory);
        padDetailDTO.setPadLayoutId(padCategory.getPadLayoutId());
        List<Long> productIds = padProductCategoryDetailMapper.selectListByQuery(new QueryWrapper()
                .eq(PadProductCategoryDetail::getPadProductCategoryId, padProductCategory)).stream().map(PadProductCategoryDetail::getProductId).toList();
        padDetailDTO.setProductIdList(productIds);
        if (!productIds.isEmpty()) {
            List<ProductVO> products = productRpcService.listAndLowPrice(shopId, productIds);
            products.parallelStream().forEach(item -> {
                List<ProdSku> skuList = prodSkuService.list(new QueryWrapper().eq(ProdSku::getProductId, item.getId()));
                item.setSkuList(skuList);
                item.setIsSaleTime(calcIsSaleTime(item.getDays(), item.getStartTime(), item.getEndTime()));
//                Optional<BigDecimal> lowMemberPriceIsPresent = skuList.stream().map(obj -> NumberUtil.nullToZero(obj.getMemberPrice())).min(BigDecimal::compareTo);
//                lowMemberPriceIsPresent.ifPresent(item::setLowMemberPrice);
            });
            padDetailDTO.setProductList(products);
        }


        return padDetailDTO;
    }


    @Override
    public Boolean add(Long shopId, PadDetailAddDTO padDetailAddDTO) {
        long count = shopProdCategoryService.count(new QueryWrapper().eq(ShopProdCategory::getId, padDetailAddDTO.getProductCategoryId()));
        if (count == 0) {
            throw new CzgException("商品分类不存在");
        }

        checkInfo(shopId, padDetailAddDTO.getPadLayoutId(), padDetailAddDTO.getProductIdList());

        PadProductCategory padProductCategory = new PadProductCategory().setPadLayoutId(padDetailAddDTO.getPadLayoutId()).setProductCategoryId(padDetailAddDTO.getProductCategoryId())
                .setShopId(shopId);
        padProductCategory.setSort(0);
        padProductCategoryService.save(padProductCategory);

        ArrayList<PadProductCategoryDetail> details = new ArrayList<>();
        padDetailAddDTO.getProductIdList().forEach(item -> details.add(new PadProductCategoryDetail().setPadProductCategoryId(padProductCategory.getId()).setProductId(item)));
        return padProductCategoryDetailService.saveBatch(details);
    }

    @Override
    public Boolean edit(Long shopId, PadDetailEditDTO padDetailEditDTO) {
        PadProductCategory category = padProductCategoryService.getOne(new QueryWrapper().eq(PadProductCategory::getShopId, shopId).eq(PadProductCategory::getId, padDetailEditDTO.getId()));
        if (category == null) {
            throw new CzgException("pad商品不存在");
        }

        checkInfo(shopId, padDetailEditDTO.getPadLayoutId(), padDetailEditDTO.getProductIdList());

        category.setPadLayoutId(padDetailEditDTO.getPadLayoutId());
        category.setSort(padDetailEditDTO.getSort());
        padProductCategoryService.updateById(category);

        if (padDetailEditDTO.getProductIdList() != null && !padDetailEditDTO.getProductIdList().isEmpty()) {
            padProductCategoryDetailService.remove(new QueryWrapper().eq(PadProductCategoryDetail::getPadProductCategoryId, padDetailEditDTO.getId()));
            ArrayList<PadProductCategoryDetail> details = new ArrayList<>();
            padDetailEditDTO.getProductIdList().forEach(item -> details.add(new PadProductCategoryDetail().setPadProductCategoryId(padDetailEditDTO.getId()).setProductId(item)));
            return padProductCategoryDetailService.saveBatch(details);
        }
        return true;
    }

    private void checkInfo(Long shopId, Long padLayoutId, List<Long> productIdList) {
        long layOutCount = padLayoutService.count(new QueryWrapper().eq(PadLayout::getId, padLayoutId).eq(PadLayout::getIsDel, 0));
        if (layOutCount == 0) {
            throw new CzgException("pad布局不存在");
        }

        if (productIdList != null && !productIdList.isEmpty()) {
            long proCount = productService.count(new QueryWrapper().eq(Product::getShopId, shopId).in(Product::getId, productIdList));
            if (proCount != productIdList.size()) {
                throw new CzgException("存在错误商品id");
            }
        }
    }

    @Override
    public Boolean del(Long shopId, PadDetailDelDTO delDTO) {
        PadProductCategory category = padProductCategoryService.getOne(new QueryWrapper().eq(PadProductCategory::getShopId, shopId).eq(PadProductCategory::getId, delDTO.getId()));
        if (category == null) {
            throw new CzgException("pad商品不存在");
        }
        padProductCategoryService.removeById(delDTO.getId());

        return padProductCategoryDetailService.remove(new QueryWrapper().eq(PadProductCategoryDetail::getPadProductCategoryId, delDTO.getId()));
    }
}
