package cn.iocoder.foodnexus.module.operations.service.inquiresupplierpush;

import cn.iocoder.foodnexus.framework.common.util.CommonUtil;
import cn.iocoder.foodnexus.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.foodnexus.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.foodnexus.module.operations.controller.admin.inquiresupplierpush.vo.AppInquireSupplierPushConfirmReqVO;
import cn.iocoder.foodnexus.module.operations.controller.admin.inquiresupplierpush.vo.AppInquireSupplierPushPageReqVO;
import cn.iocoder.foodnexus.module.operations.controller.admin.inquiresupplierpush.vo.AppInquireSupplierPushRespVO;
import cn.iocoder.foodnexus.module.operations.dal.dataobject.inquirepriceitem.InquirePriceItemDO;
import cn.iocoder.foodnexus.module.operations.service.inquirepriceitem.InquirePriceItemService;
import cn.iocoder.foodnexus.module.system.dal.redis.RedisKeyConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.*;
import cn.iocoder.foodnexus.module.operations.controller.admin.inquiresupplierpush.vo.*;
import cn.iocoder.foodnexus.module.operations.dal.dataobject.inquiresupplierpush.InquireSupplierPushDO;
import cn.iocoder.foodnexus.framework.common.pojo.PageResult;
import cn.iocoder.foodnexus.framework.common.util.object.BeanUtils;

import cn.iocoder.foodnexus.module.operations.dal.mysql.inquiresupplierpush.InquireSupplierPushMapper;

import static cn.iocoder.foodnexus.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.foodnexus.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.foodnexus.module.operations.enums.ErrorCodeConstants.*;

/**
 * 询价推送 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class InquireSupplierPushServiceImpl implements InquireSupplierPushService {

    @Resource
    private InquireSupplierPushMapper inquireSupplierPushMapper;

    @Autowired
    private InquirePriceItemService inquirePriceItemService;

    @Override
    public Long createInquireSupplierPush(InquireSupplierPushSaveReqVO createReqVO) {
        // 插入
        InquireSupplierPushDO inquireSupplierPush = BeanUtils.toBean(createReqVO, InquireSupplierPushDO.class);
        inquireSupplierPushMapper.insert(inquireSupplierPush);

        // 返回
        return inquireSupplierPush.getId();
    }

    @Override
    public void updateInquireSupplierPush(InquireSupplierPushSaveReqVO updateReqVO) {
        // 校验存在
        validateInquireSupplierPushExists(updateReqVO.getId());
        // 更新
        InquireSupplierPushDO updateObj = BeanUtils.toBean(updateReqVO, InquireSupplierPushDO.class);
        inquireSupplierPushMapper.updateById(updateObj);
    }

    @Override
    public void deleteInquireSupplierPush(Long id) {
        // 校验存在
        validateInquireSupplierPushExists(id);
        // 删除
        inquireSupplierPushMapper.deleteById(id);
    }

    @Override
        public void deleteInquireSupplierPushListByIds(List<Long> ids) {
        // 删除
        inquireSupplierPushMapper.deleteByIds(ids);
        }


    private void validateInquireSupplierPushExists(Long id) {
        if (inquireSupplierPushMapper.selectById(id) == null) {
            throw exception(INQUIRE_SUPPLIER_PUSH_NOT_EXISTS);
        }
    }

    @Override
    public InquireSupplierPushDO getInquireSupplierPush(Long id) {
        return inquireSupplierPushMapper.selectById(id);
    }

    @Override
    public PageResult<InquireSupplierPushDO> getInquireSupplierPushPage(InquireSupplierPushPageReqVO pageReqVO) {
        return inquireSupplierPushMapper.selectPage(pageReqVO);
    }

    /**
     * 确认询价推送
     *
     * @param updateReqVO
     */
    @Override
    @CacheEvict(cacheNames = RedisKeyConstants.CUSTOMER_VISIBLE_PRODUCT, allEntries = true)
    public void confirm(AppInquireSupplierPushConfirmReqVO updateReqVO) {
        List<InquireSupplierPushDO> inquireSupplierPushDOS = inquireSupplierPushMapper.selectList(new LambdaQueryWrapperX<InquireSupplierPushDO>()
                .eq(InquireSupplierPushDO::getSupplierId, updateReqVO.getSupplierId())
                .eq(InquireSupplierPushDO::getInquirePriceId, updateReqVO.getInquirePriceId()));
        if (CommonUtil.isEmpty(inquireSupplierPushDOS)) {
            return ;
        }

        Map<Long, Integer> itemsMap = CommonUtil.listConvertMap(updateReqVO.getItems(),
                AppInquireSupplierPushConfirmReqVO.Item::getProductId,
                AppInquireSupplierPushConfirmReqVO.Item::getSupplierQuote);

        // 更新数据
        List<InquireSupplierPushDO> updateBatch = CommonUtil.listConvert(inquireSupplierPushDOS, push -> {
            InquireSupplierPushDO update = new InquireSupplierPushDO();
            update.setId(push.getId());
            update.setConfirm(Boolean.TRUE);
            update.setConfirmUser(SecurityFrameworkUtils.getLoginUserId());
            update.setConfirmTime(LocalDateTime.now());
            if (itemsMap.containsKey(push.getProductId())) {
                update.setSupplierQuote(itemsMap.get(push.getProductId()));
            } else {
                update.setSupplierQuote(Optional.ofNullable(inquirePriceItemService.getInquirePriceItem(push.getInquirePriceItemId()))
                        .map(InquirePriceItemDO::getFloatingPrice).orElse(null));
            }
            return update;
        });

        inquireSupplierPushMapper.updateBatch(updateBatch);
    }

    @Override
    public PageResult<AppInquireSupplierPushRespVO> getAppInquireSupplierPushPage(AppInquireSupplierPushPageReqVO pageReqVO) {
        return inquireSupplierPushMapper.selectPage(pageReqVO);
    }

    @Override
    public List<InquireSupplierPushDO> queryByInquireId(Long inquirePriceId, Long supplierId) {
        return inquireSupplierPushMapper.selectList(InquireSupplierPushDO::getInquirePriceId, inquirePriceId,
                InquireSupplierPushDO::getSupplierId, supplierId);
    }

    @Override
    public List<InquireSupplierPushDO> queryByInquireId(Long inquirePriceId) {
        return inquireSupplierPushMapper.selectList(InquireSupplierPushDO::getInquirePriceId, inquirePriceId);
    }
}