package com.czg.service.product.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.czg.account.entity.ShopUser;
import com.czg.account.service.ShopUserService;
import com.czg.exception.CzgException;
import com.czg.product.dto.storage.CountStorageDTO;
import com.czg.product.dto.storage.ShopStorageAddDTO;
import com.czg.product.dto.storage.ShopStorageEditDTO;
import com.czg.product.entity.ShopStorageGood;
import com.czg.product.entity.ShopStorageRecord;
import com.czg.product.service.ShopStorageGoodService;
import com.czg.product.service.ShopStorageRecordService;
import com.czg.service.product.mapper.ShopStorageMapper;
import com.czg.utils.PageUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.czg.product.entity.ShopStorage;
import com.czg.product.service.ShopStorageService;
import jakarta.annotation.Resource;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.mybatisflex.core.query.QueryMethods.column;

/**
 * 用户存酒 服务层实现。
 *
 * @author zs
 * @since 2025-02-27
 */
@Service
public class ShopStorageServiceImpl extends ServiceImpl<ShopStorageMapper, ShopStorage> implements ShopStorageService{
    @DubboReference
    private ShopUserService shopUserService;

    @Resource
    private ShopStorageGoodService shopStorageGoodService;
    @Resource
    private ShopStorageRecordService storageRecordService;

    @Override
    public Page<ShopStorage> pageInfo(Long shopId, String key, String phone, Integer status) {
        QueryWrapper queryWrapper = new QueryWrapper().eq(ShopStorage::getShopId, shopId).eq(ShopStorage::getStatus, status);
        if (StrUtil.isNotBlank(key)) {
            queryWrapper.and(column(ShopStorage::getName).like(key).or(column(ShopStorage::getNickName).like(key)));
        }

        if (StrUtil.isNotBlank(phone)) {
            queryWrapper.eq(ShopStorage::getPhone, phone);
        }
        queryWrapper.orderBy(ShopStorage::getId, false);
        Page<ShopStorage> shopStoragePage = page(PageUtil.buildPage(), queryWrapper);
        shopStoragePage.getRecords().forEach(item -> {
            if (item.getNum() == 0) {
                item.setStatus(0);
            }

            if (item.getExpTime().isBefore(DateUtil.date().toLocalDateTime())) {
                item.setStatus(2);
            }
        });
        updateBatch(shopStoragePage.getRecords());
        return shopStoragePage;
    }

    @Override
    public Boolean add(Long shopId, ShopStorageAddDTO shopStorageAddDTO) {
        ShopUser shopUser = shopUserService.getOne(new QueryWrapper().eq(ShopUser::getUserId, shopStorageAddDTO.getUserId()).eq(ShopUser::getSourceShopId, shopId));
        if (shopUser == null) {
            throw new CzgException("店铺用户不存在");
        }

        ShopStorageGood shopStorageGood = shopStorageGoodService.getOne(new QueryWrapper().eq(ShopStorageGood::getShopId, shopId).eq(ShopStorageGood::getId, shopStorageAddDTO.getShopStorageGoodId()));
        if (shopStorageGood == null) {
            throw new CzgException("存酒商品不存在");
        }

        ShopStorage shopStorage = new ShopStorage().setName(shopStorageGood.getName())
                .setImgUrl(shopStorageGood.getImgUrl())
                .setUnit(shopStorageGood.getUnit())
                .setNum(shopStorageAddDTO.getNum())
                .setSavTime(DateUtil.date().toLocalDateTime())
                .setExpTime(DateUtil.offsetDay(DateUtil.date(), shopStorageAddDTO.getExpDay()).toLocalDateTime())
                .setShopId(shopId)
                .setUserId(shopStorageAddDTO.getUserId())
                .setHeadImg(shopUser.getHeadImg())
                .setNickName(shopUser.getNickName())
                .setPhone(shopUser.getPhone());
        boolean save = save(shopStorage);

        if (save) {
            ShopStorageRecord record = new ShopStorageRecord();
            record.setStorageId(shopStorage.getId());
            record.setTime(DateUtil.date().toLocalDateTime());
            record.setContent("存入"+ shopStorage.getNum() + shopStorage.getUnit() + shopStorage.getName());
            return storageRecordService.save(record);
        }
        throw new CzgException("保存失败");
    }

    @Override
    public Boolean edit(Long shopId, ShopStorageEditDTO shopStorageEditDTO) {
        ShopStorage shopStorage = getOne(new QueryWrapper().eq(ShopStorage::getShopId, shopId).eq(ShopStorage::getId, shopStorageEditDTO.getId()));
        if (shopStorage == null) {
            throw new CzgException("存酒记录不存在");
        }

        if (shopStorageEditDTO.getNum() < 0 && shopStorage.getNum() + shopStorageEditDTO.getNum() < 0) {
            throw new CzgException("可取酒数量不足");
        }

        shopStorage.setNum(shopStorage.getNum() + shopStorageEditDTO.getNum());
        if (shopStorage.getNum() == 0) {
            shopStorage.setStatus(0);
        }
        boolean b = updateById(shopStorage);

        if (b) {

            ShopStorageRecord record = new ShopStorageRecord();
            record.setStorageId(shopStorage.getId());
            record.setTime(DateUtil.date().toLocalDateTime());
            record.setContent(((shopStorageEditDTO.getNum() > 0) ? "存入" : "取出") + Math.abs(shopStorageEditDTO.getNum()) + shopStorage.getUnit() + shopStorage.getName());
            return storageRecordService.save(record);
        }

        return false;
    }

    @Override
    public List<ShopStorageRecord> getRecord(Long shopId, Integer id) {
        ShopStorage shopStorage = getOne(new QueryWrapper().eq(ShopStorage::getShopId, shopId).eq(ShopStorage::getId, id));
        if (shopStorage == null) {
            throw new CzgException("存酒记录不存在");
        }
        return storageRecordService.list(new QueryWrapper().eq(ShopStorageRecord::getStorageId, id));
    }

    @Override
    public List<CountStorageDTO> countRecord(Long shopId) {
        return mapper.countRecord(shopId);
    }
}
