package cn.iocoder.yudao.module.member.service.storesalegoods;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.member.controller.admin.storesalegoods.vo.StoreSaleGoodsPageReqVO;
import cn.iocoder.yudao.module.member.controller.admin.storesalegoods.vo.StoreSaleGoodsSaveBatchVO;
import cn.iocoder.yudao.module.member.controller.admin.storesalegoods.vo.StoreSaleGoodsSaveReqVO;
import cn.iocoder.yudao.module.member.controller.app.store.dto.StoreGoodsDto;
import cn.iocoder.yudao.module.member.controller.app.store.dto.StoreSaleGoodsDto;
import cn.iocoder.yudao.module.member.dal.dataobject.storesalegoods.StoreSaleGoodsDO;
import cn.iocoder.yudao.module.member.dal.mysql.storesalegoods.StoreSaleGoodsMapper;
import cn.iocoder.yudao.module.system.api.cashregisterinfo.CashregisterinfoApi;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.STORE_SALE_GOODS_NOT_EXISTS;

/**
 * 售卖商品 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class StoreSaleGoodsServiceImpl implements StoreSaleGoodsService {

    @Resource
    private StoreSaleGoodsMapper storeSaleGoodsMapper;
    @Resource
    private CashregisterinfoApi cashregisterinfoApi;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer createStoreSaleGoods(StoreSaleGoodsSaveBatchVO createReqVO) {
        List<StoreSaleGoodsDO> addList = new ArrayList<>();

        List<Long> carteenIds = createReqVO.getCarteenIds();
        List<Integer> goodsIds = createReqVO.getGoodsIds();
        for (Long carteenId : carteenIds) {
            List<StoreSaleGoodsDO> storeSaleGoodsDOS = storeSaleGoodsMapper.selectList(Wrappers.<StoreSaleGoodsDO>lambdaQuery()
                    .eq(StoreSaleGoodsDO::getCarteenId, carteenId));
            List<Integer> saleGoods = storeSaleGoodsDOS.stream().map(StoreSaleGoodsDO::getGoodsId).collect(Collectors.toList());
            for (Integer goodsId : goodsIds) {
                if (saleGoods.contains(goodsId)) {
                    continue;
                }
                // 插入
                StoreSaleGoodsDO storeSaleGoods = new StoreSaleGoodsDO();
                storeSaleGoods.setCarteenId(carteenId);
                storeSaleGoods.setGoodsId(goodsId);
                addList.add(storeSaleGoods);
            }
        }
        storeSaleGoodsMapper.insertBatch(addList);
        return addList.size();
    }

    @Override
    public void updateStoreSaleGoods(StoreSaleGoodsSaveReqVO updateReqVO) {
        // 校验存在
        validateStoreSaleGoodsExists(updateReqVO.getId());
        // 更新
        StoreSaleGoodsDO updateObj = BeanUtils.toBean(updateReqVO, StoreSaleGoodsDO.class);
        storeSaleGoodsMapper.updateById(updateObj);
    }

    @Override
    public void deleteStoreSaleGoods(String id) {
        String[] split = id.split(",");
        LambdaQueryWrapper<StoreSaleGoodsDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(StoreSaleGoodsDO::getId, Arrays.asList(split));
        // 删除
        storeSaleGoodsMapper.delete(wrapper);
    }

    private void validateStoreSaleGoodsExists(Long id) {
        if (storeSaleGoodsMapper.selectById(id) == null) {
            throw exception(STORE_SALE_GOODS_NOT_EXISTS);
        }
    }

    @Override
    public StoreSaleGoodsDO getStoreSaleGoods(Long id) {
        return storeSaleGoodsMapper.selectById(id);
    }

    @Override
    public PageResult<StoreSaleGoodsDO> getStoreSaleGoodsPage(StoreSaleGoodsPageReqVO pageReqVO) {
        return storeSaleGoodsMapper.selectPage(pageReqVO);
    }

    @Override
    public Boolean bindGoods(StoreSaleGoodsDto dto) {
        Long storeId = cashregisterinfoApi.getStoreId(dto.getEquipmentCode());
        //清空
        storeSaleGoodsMapper.delete(new LambdaQueryWrapper<StoreSaleGoodsDO>().eq(StoreSaleGoodsDO::getCarteenId, storeId));
        Boolean b = true;
        if (CollectionUtil.isNotEmpty(dto.getEquipmentGoodsCustoms())) {
            ArrayList<StoreSaleGoodsDO> list = new ArrayList<>();
            List<Integer> goodsIds = new ArrayList<>();
            for (StoreGoodsDto storeGoodsDto : dto.getEquipmentGoodsCustoms()) {
                if(goodsIds.contains(storeGoodsDto.getGoodsId())){
                    continue;
                }
                goodsIds.add(storeGoodsDto.getGoodsId());
                StoreSaleGoodsDO storeSaleGoodsDO = new StoreSaleGoodsDO();
                BeanUtil.copyProperties(storeGoodsDto, storeSaleGoodsDO);
                storeSaleGoodsDO.setEquipmentCode(dto.getEquipmentCode());
                storeSaleGoodsDO.setCarteenId(storeId);
                list.add(storeSaleGoodsDO);
            }
            b = storeSaleGoodsMapper.insertBatch(list);
        }

        return b;
    }

    @Override
    public List<Integer> getGoodsIds(Long storeId) {

        List<StoreSaleGoodsDO> storeSaleGoodsDOS = storeSaleGoodsMapper.selectList(new LambdaQueryWrapper<StoreSaleGoodsDO>().eq(StoreSaleGoodsDO::getCarteenId, storeId));
        if (CollectionUtil.isEmpty(storeSaleGoodsDOS)) {
            return Collections.emptyList();
        } else {
            return storeSaleGoodsDOS.stream().map(StoreSaleGoodsDO::getGoodsId).collect(Collectors.toList());
        }
    }
}