package com.liquidnet.client.admin.zhengzai.merchant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.client.admin.common.utils.bean.BeanUtils;
import com.liquidnet.client.admin.zhengzai.merchant.service.IMerchantSponsorsAdminService;
import com.liquidnet.client.admin.zhengzai.merchant.utils.MerchantMongoUtil;
import com.liquidnet.client.admin.zhengzai.merchant.utils.MerchantRedisUtil;
import com.liquidnet.common.exception.LiquidnetServiceException;
import com.liquidnet.service.merchant.dto.param.admin.MerchantSponsorEditParam;
import com.liquidnet.service.merchant.dto.vo.MerchantSponsorsVo;
import com.liquidnet.service.merchant.entity.MerchantSponsors;
import com.liquidnet.service.merchant.mapper.MerchantSponsorsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j
@Service
public class MerchantSponsorsAdminServiceImpl extends ServiceImpl<MerchantSponsorsMapper, MerchantSponsors> implements IMerchantSponsorsAdminService {

    @Autowired
    MerchantRedisUtil merchantRedisUtil;

    @Autowired
    MerchantMongoUtil merchantMongoUtil;

    @Override
    public boolean sponsorEdit(MerchantSponsorEditParam parameter) {
        LocalDateTime now = LocalDateTime.now();

        // 查询主办 entity
        LambdaQueryWrapper<MerchantSponsors> sponsorsLambdaQueryWrapper = Wrappers.lambdaQuery(MerchantSponsors.class);
        sponsorsLambdaQueryWrapper.eq(MerchantSponsors::getSponsorId, parameter.getSponsorId());
        MerchantSponsors sponsorsEntity = getOne(sponsorsLambdaQueryWrapper);
        if (null == sponsorsEntity) {
            // todo error
            throw new LiquidnetServiceException();
        }

        // 主办 entity
        BeanUtils.copyProperties(parameter, sponsorsEntity);
        sponsorsEntity.setUpdatedAt(now);

        // 主办 mysql
        updateById(sponsorsEntity);

        // 主办 vo
        MerchantSponsorsVo sponsorsVo = MerchantSponsorsVo.getNew();
        sponsorsVo.copy(sponsorsEntity);

        // 主办 mongo
        merchantMongoUtil.setSponsorsVoBySponsorId(sponsorsVo.getSponsorId(), sponsorsVo);

        // 主办 redis
        merchantRedisUtil.setSponsorsVoBySponsorId(sponsorsVo.getSponsorId(), sponsorsVo);

        return true;
    }
}
