package cn.ysk.cashier.cons.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.ysk.cashier.cons.domain.TbConsInfo;
import cn.ysk.cashier.cons.domain.TbConsSuppFlow;
import cn.ysk.cashier.cons.domain.TbProskuCon;
import cn.ysk.cashier.cons.repository.TbConsInfoRepository;
import cn.ysk.cashier.cons.service.dto.ProskuInfo;
import cn.ysk.cashier.exception.BadRequestException;
import cn.ysk.cashier.pojo.product.TbProduct;
import cn.ysk.cashier.pojo.product.TbProductSku;
import cn.ysk.cashier.repository.product.TbProductRepository;
import cn.ysk.cashier.repository.product.TbProductSkuRepository;
import cn.ysk.cashier.utils.*;
import lombok.RequiredArgsConstructor;
import cn.ysk.cashier.cons.repository.TbProskuConRepository;
import cn.ysk.cashier.cons.service.TbProskuConService;
import cn.ysk.cashier.cons.service.dto.TbProskuConDto;
import cn.ysk.cashier.cons.service.dto.TbProskuConQueryCriteria;
import cn.ysk.cashier.cons.service.mapstruct.TbProskuConMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author admin
* @date 2024-06-22
**/
@Service
@RequiredArgsConstructor
@Slf4j
public class TbProskuConServiceImpl implements TbProskuConService {

    private final TbProskuConRepository tbProskuConRepository;
    private final TbProskuConMapper tbProskuConMapper;

    private final TbProductRepository tbProductRepository;

    private final TbProductSkuRepository tbProductSkuRepository;

    private final TbConsInfoRepository tbConsInfoRepository;

    @Override
    public Map<String,Object> queryAll(TbProskuConQueryCriteria criteria, Pageable pageable){
        Page<TbProskuCon> page = tbProskuConRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(tbProskuConMapper::toDto));
    }

    @Override
    public List<TbProskuConDto> queryAll(TbProskuConQueryCriteria criteria){
        return tbProskuConMapper.toDto(tbProskuConRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public TbProskuConDto findById(Integer id) {
        TbProskuCon tbProskuCon = tbProskuConRepository.findById(id).orElseGet(TbProskuCon::new);
        ValidationUtil.isNull(tbProskuCon.getId(),"TbProskuCon","id",id);
        return tbProskuConMapper.toDto(tbProskuCon);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TbProskuConDto create(List<ProskuInfo> resources) throws BadRequestException,Exception {

        log.info("List<ProskuInfo> resources:{}",JSONUtil.toJSONString(resources));
        for (ProskuInfo resource : resources) {
            TbProduct product= tbProductRepository.getById(resource.getProductId());
            if(Objects.isNull(product)){
                throw new BadRequestException("对应的商品信息不存在");
            }
            List<TbProskuCon> list=new ArrayList<>();
            if(product.getIsDistribute().intValue()==1){

                TbConsInfo tbConsInfo= tbConsInfoRepository.findById(resource.getConsInfoId()).orElseGet(TbConsInfo::new);

                log.info("product.getIsDistribute().intValue():{}", JSONUtil.toJSONString(tbConsInfo));
                if(ObjectUtil.isNull(tbConsInfo)||ObjectUtil.isNull(tbConsInfo.getId())){
                    throw new BadRequestException("对应的耗材信息不存在");
                }

                //查询商品对应的所有规格
                List<TbProductSku> skuList= tbProductSkuRepository.searchSku(product.getId().toString());
                if(Objects.nonNull(skuList)&&skuList.size()>0){
                    for (TbProductSku tbProductSku : skuList) {
                        int count=tbProskuConRepository.countByConInfoIdAndProductSkuIdAndShopId(resource.getConsInfoId(), tbProductSku.getId(), Integer.valueOf(tbProductSku.getShopId()), Integer.valueOf(tbProductSku.getProductId()));
                        if(count<=0){
                            TbProskuCon tbProskuCon=new TbProskuCon();

                            tbProskuCon.setShopId(Integer.valueOf(tbProductSku.getShopId()));
                            tbProskuCon.setConInfoId(tbConsInfo.getId());
                            tbProskuCon.setProductId(Integer.valueOf(tbProductSku.getProductId()));
                            tbProskuCon.setProductSkuId(tbProductSku.getId());
                            tbProskuCon.setSurplusStock(resource.getSurplusStock());
                            tbProskuCon.setStatus("1");
                            tbProskuCon.setCreateTime(new Timestamp(System.currentTimeMillis()));
                            list.add(tbProskuCon);
                        }else {
                            throw new BadRequestException(product.getName().concat("对应的耗材信息已存在"));
                        }
                    }
                }

            }else {
                for (ProskuInfo.SkuInfo skuInfo : resource.getSkuInfos()) {


                    TbConsInfo tbConsInfo= tbConsInfoRepository.findById(skuInfo.getConInfoId()).orElseGet(TbConsInfo::new);

                    log.info("skuInfo:{}", JSONUtil.toJSONString(tbConsInfo));

                    if(ObjectUtil.isNull(tbConsInfo)||ObjectUtil.isNull(tbConsInfo.getId())){
                        throw new BadRequestException("对应的耗材信息不存在");
                    }

                    TbProductSku tbProductSku= tbProductSkuRepository.findById(skuInfo.getSkuId()).orElseGet(TbProductSku::new);
                    if(ObjectUtil.isNull(tbProductSku)||ObjectUtil.isNull(tbProductSku.getId())){
                        throw new BadRequestException("规格信息不存在");
                    }

                    int count=tbProskuConRepository.countByConInfoIdAndProductSkuIdAndShopId(resource.getConsInfoId(), skuInfo.getSkuId(), skuInfo.getShopId(), resource.getProductId());
                    if(count<=0){
                        TbProskuCon tbProskuCon=new TbProskuCon();
                        tbProskuCon.setShopId(Integer.valueOf(skuInfo.getShopId()));
                        tbProskuCon.setConInfoId(tbConsInfo.getId());
                        tbProskuCon.setProductId(resource.getProductId());
                        tbProskuCon.setProductSkuId(skuInfo.getSkuId());
                        tbProskuCon.setSurplusStock(skuInfo.getSurplusStock());
                        tbProskuCon.setStatus("1");
                        tbProskuCon.setCreateTime(new Timestamp(System.currentTimeMillis()));
                        list.add(tbProskuCon);
                    }else {
                        TbProductSku sku=  tbProductSkuRepository.getById(skuInfo.getSkuId());
                        throw new BadRequestException(product.getName().concat("商品对应的").concat(Objects.nonNull(sku.getSpecSnap())?sku.getSpecSnap():"").concat("规格已存在"));
                    }
                }

            }
            if(Objects.nonNull(list)&&list.size()>0){
                tbProskuConRepository.saveAll(list);
            }
        }


        return new TbProskuConDto();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TbProskuCon resources) throws Exception {
        TbProskuCon tbProskuCon = tbProskuConRepository.findById(resources.getId()).orElseGet(TbProskuCon::new);
        ValidationUtil.isNull( tbProskuCon.getId(),"TbProskuCon","id",resources.getId());
        tbProskuCon.copy(resources);
        tbProskuConRepository.save(tbProskuCon);


//        TbProduct product= tbProductRepository.getById(resources.getProductId());
//        if(Objects.isNull(product)){
//            throw new Exception("对应的商品信息不存在");
//        }
//
//        TbConsInfo tbConsInfo= tbConsInfoRepository.getById(resources.getConsInfoId());
//        if(Objects.isNull(tbConsInfo)){
//            throw new Exception("对应的耗材信息不存在");
//        }
//
//        List<TbProskuCon> list=new ArrayList<>();
//        if("1".equals(product.getIsDistribute().toString())){
//            //查询商品对应的所有规格
//            List<TbProductSku> skuList= tbProductSkuRepository.searchSku(product.getId().toString());
//            if(Objects.nonNull(skuList)&&skuList.size()>0){
//                for (TbProductSku tbProductSku : skuList) {
//                    TbProskuCon  tbProskuCon=tbProskuConRepository.selectByConInfoIdAndProductSkuIdAndShopId(resources.getConsInfoId(), tbProductSku.getId(), Integer.valueOf(tbProductSku.getShopId()), Integer.valueOf(tbProductSku.getProductId()));
//                    if(Objects.nonNull(tbProskuCon)){
//                        tbProskuCon.setSurplusStock(resources.getSurplusStock());
//                        tbProskuCon.setStatus(resources.getStatus());
//                        tbProskuCon.setCreateTime(new Timestamp(System.currentTimeMillis()));
//                        list.add(tbProskuCon);
//                    }
//                }
//            }
//
//        }else {
//
//            for (ProskuInfo.SkuInfo skuInfo : resources.getSkuInfos()) {
//                TbProskuCon  tbProskuCon=tbProskuConRepository.selectByConInfoIdAndProductSkuIdAndShopId(resources.getConsInfoId(), skuInfo.getSkuId(), skuInfo.getShopId(), resources.getProductId());
//                if(Objects.nonNull(tbProskuCon)){
//                    tbProskuCon.setSurplusStock(skuInfo.getSurplusStock());
//                    tbProskuCon.setStatus(skuInfo.getStatus());
//                    tbProskuCon.setCreateTime(new Timestamp(System.currentTimeMillis()));
//                    list.add(tbProskuCon);
//                }
//            }
//
//        }
//        tbProskuConRepository.saveAll(list);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            tbProskuConRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<TbProskuConDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TbProskuConDto tbProskuCon : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("商品规格id", tbProskuCon.getProductSkuId());
            map.put("耗材id", tbProskuCon.getConInfoId());
            map.put("状态 1 启用 0 禁用", tbProskuCon.getStatus());
            map.put("创建时间", tbProskuCon.getCreateTime());
            map.put("店铺id", tbProskuCon.getShopId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}