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

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.client.admin.zhengzai.goblin.service.IGoblinStoreInfoService;
import com.liquidnet.common.exception.LiquidnetServiceException;
import com.liquidnet.service.goblin.dto.vo.GoblinStoreInfoVo;
import com.liquidnet.service.goblin.entity.GoblinStoreInfo;
import com.liquidnet.service.goblin.mapper.GoblinStoreInfoMapper;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 店铺基础信息 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-12-27
 */
@Slf4j
@Service
public class GoblinStoreInfoServiceImpl extends ServiceImpl<GoblinStoreInfoMapper, GoblinStoreInfo> implements IGoblinStoreInfoService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    @Transactional
    public boolean audit(String storeId, String status, String operator) {
        LocalDateTime now = LocalDateTime.now();
        LambdaUpdateWrapper<GoblinStoreInfo> lambdaUpdateWrapper = Wrappers.lambdaUpdate(GoblinStoreInfo.class);
        lambdaUpdateWrapper.eq(GoblinStoreInfo::getStoreId, storeId);
        lambdaUpdateWrapper.eq(GoblinStoreInfo::getStatus, 1);

        lambdaUpdateWrapper.set(GoblinStoreInfo::getStatus, status);
        lambdaUpdateWrapper.set(GoblinStoreInfo::getUpdatedBy, operator);
        lambdaUpdateWrapper.set(GoblinStoreInfo::getUpdatedAt, now);

        if (this.update(lambdaUpdateWrapper)) {
            Query query = Query.query(Criteria.where("storeId").is(storeId));
            Update update = Update.update("status", status);
            update.set("updatedBy", operator);
            update.set("updatedAt", now);
            UpdateResult updateResult = mongoTemplate.updateFirst(query, update, GoblinStoreInfoVo.class.getSimpleName());
            if (updateResult.getModifiedCount() <= 0) {
                log.error("店铺管理:店铺审核:MDB更新失败[storeId={},status={},operator={}]", storeId, status, operator);
                throw new LiquidnetServiceException();
            }
            // TODO: 2021/12/29 zhanggb 同步REDIS

            return true;
        }
        return false;
    }
}
