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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.client.admin.common.utils.ShiroUtils;
import com.liquidnet.client.admin.zhengzai.goblin.service.IGoblinSelfGoodsCategoryService;
import com.liquidnet.common.cache.redis.util.RedisDataSourceUtil;
import com.liquidnet.common.exception.LiquidnetServiceException;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.goblin.constant.GoblinRedisConst;
import com.liquidnet.service.goblin.dto.GoblinSelfGoodsCategoryDto;
import com.liquidnet.service.goblin.dto.vo.GoblinSelfGoodsCategoryVo;
import com.liquidnet.service.goblin.entity.GoblinSelfGoodsCategory;
import com.liquidnet.service.goblin.mapper.GoblinSelfGoodsCategoryMapper;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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 org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 平台商品分类 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-12-27
 */
@Slf4j
@Service
public class GoblinSelfGoodsCategoryServiceImpl extends ServiceImpl<GoblinSelfGoodsCategoryMapper, GoblinSelfGoodsCategory> implements IGoblinSelfGoodsCategoryService {
    @Autowired
    private GoblinSelfGoodsCategoryMapper goblinSelfGoodsCategoryMapper;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisDataSourceUtil redisDataSourceUtil;

    @Override
    public int countForMatchName(String cateFid, String name) {
        return goblinSelfGoodsCategoryMapper.countForMatchName(cateFid, name);
    }

    @Override
    public List<GoblinSelfGoodsCategoryDto> listForMultiGrade() {
        goblinSelfGoodsCategoryMapper.statsForForMultiGrade();
        List<GoblinSelfGoodsCategoryDto> dtos = goblinSelfGoodsCategoryMapper.listForMultiGrade();
        if (!CollectionUtils.isEmpty(dtos)) {
            dtos.forEach(dto -> {
                if (StringUtils.isNotEmpty(dto.getTcateId())) {
                    dto.setFcounts(dto.getTcounts());
                } else if (StringUtils.isNotEmpty(dto.getScateId())) {
                    dto.setFcounts(dto.getScounts());
                }
            });
        }
        return dtos;
    }

    @Transactional
    @Override
    public boolean addSave(GoblinSelfGoodsCategory selfGoodsCategory) {
        if (this.save(selfGoodsCategory)) {
            mongoTemplate.insert(GoblinSelfGoodsCategoryVo.getNew().copy(selfGoodsCategory), GoblinSelfGoodsCategoryVo.class.getSimpleName());

            redisDataSourceUtil.getRedisGoblinUtil().del(GoblinRedisConst.BASIC_SELF_GOODS_CATEGORY);

            return true;
        }
        return false;
    }

    @Transactional
    @Override
    public boolean remove(String[] cateIdArr) {
        List<String> cateIdList = goblinSelfGoodsCategoryMapper.listForMultiGradeCateId(cateIdArr);

        if (CollectionUtils.isEmpty(cateIdList)) {
            log.warn("店铺管理:商品分类:删除失败[cateIdArr={}]", JsonUtils.toJson(cateIdArr));
            return false;
        }

        String loginName = ShiroUtils.getLoginName();
        LocalDateTime now = LocalDateTime.now();

        boolean rmvResultFlg = this.update(Wrappers.lambdaUpdate(GoblinSelfGoodsCategory.class)
                .in(GoblinSelfGoodsCategory::getCateId, cateIdList.toArray())
                .set(GoblinSelfGoodsCategory::getDelFlg, "1")
                .set(GoblinSelfGoodsCategory::getUpdatedBy, loginName)
                .set(GoblinSelfGoodsCategory::getUpdatedAt, now)
                .set(GoblinSelfGoodsCategory::getDeletedBy, loginName)
                .set(GoblinSelfGoodsCategory::getDeletedAt, now)
        );

        if (rmvResultFlg) {
            UpdateResult updateResult = mongoTemplate.updateMulti(Query.query(Criteria.where("cateId").in(cateIdList.toArray())),
                    Update.update("delFlg", "1").set("updatedBy", loginName).set("updatedAt", now).set("deletedBy", loginName).set("deletedAt", now),
                    GoblinSelfGoodsCategoryVo.class.getSimpleName()
            );
//            log.info("店铺管理:商品分类:删除[cateIdArr={},MONGO.UpdateResult={}]", JsonUtils.toJson(cateIdArr), JsonUtils.toJson(updateResult));
            if (updateResult.getModifiedCount() <= 0) {
                log.error("店铺管理:商品分类:删除:MDB更新失败[cateIdArr={}]", JsonUtils.toJson(cateIdArr));
                throw new LiquidnetServiceException();
            }

            redisDataSourceUtil.getRedisGoblinUtil().del(GoblinRedisConst.BASIC_SELF_GOODS_CATEGORY);
        }
        return rmvResultFlg;
    }
}
