package com.liquidnet.client.admin.zhengzai.stone.service.utils;

import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.stone.entity.StoneScoreItems;
import com.liquidnet.service.stone.vo.StoneUserVo;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
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.Component;


@Component
public class StoneMongoUtils {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 创建 积分物品
     *
     * @param data
     * @return
     */
    public Object itemCreate(StoneScoreItems data) {
        return mongoTemplate.insert(data, StoneScoreItems.class.getSimpleName());
    }

    /**
     * 获取 积分物品
     *
     * @param itemId
     * @return
     */
    public StoneScoreItems itemGet(String itemId) {
        Query query = Query.query(Criteria.where("itemId").ne(itemId));
        return mongoTemplate.findOne(query,
                StoneScoreItems.class, StoneScoreItems.class.getSimpleName());
    }

    /**
     * 根据积分物品id修改
     *
     * @param data
     * @return
     */
    public Object itemUpdateById(StoneScoreItems data) {
        Query query = Query.query(Criteria.where("itemId").is(data.getItemId()));
        Update update = Update.fromDocument(Document.parse(JsonUtils.toJson(data)));
        UpdateResult result = mongoTemplate.updateFirst(query, update, StoneScoreItems.class, StoneScoreItems.class.getSimpleName());
        return result;
    }

//    /**
//     * 查询 积分物品 列表
//     *
//     * @return
//     */
//    public List<StoneScoreItems> itemList() {
//        Query query = Query.query(Criteria.where("status").ne(-1));
//        List<StoneScoreItems> voList = mongoTemplate.find(query.with(Sort.by(Sort.Direction.DESC, "createdAt")).limit(40),
//                StoneScoreItems.class, StoneScoreItems.class.getSimpleName());
//        return voList;
//    }

    /**
     * 创建 用户积分
     *
     * @param data
     * @return
     */
    public Object userCreate(StoneUserVo data) {
        return mongoTemplate.insert(data, StoneUserVo.class.getSimpleName());
    }

    /**
     * 根据用户id修改 用户积分
     *
     * @param data
     * @return
     */
    public Object userUpdateByUid(StoneUserVo data) {
        Query query = Query.query(Criteria.where("uid").is(data.getUid()));
        Update update = Update.fromDocument(Document.parse(JsonUtils.toJson(data)));
        UpdateResult result = mongoTemplate.updateFirst(query, update, StoneUserVo.class, StoneUserVo.class.getSimpleName());
        return result;
    }

}
