package com.liquidnet.client.admin.zhengzai.merchant.utils;

import com.liquidnet.service.merchant.dto.vo.MerchantFieldsVo;
import com.liquidnet.service.merchant.dto.vo.MerchantSponsorsVo;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MongoConverter;
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 MerchantMongoUtil {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private MongoConverter mongoConverter;


    public MerchantFieldsVo getFieldsVoByFieldId(String fieldId) {
        return mongoTemplate.findOne(Query.query(Criteria.where("fieldId").is(fieldId)), MerchantFieldsVo.class, MerchantFieldsVo.class.getSimpleName());
    }

    public void setFieldsVoByFieldId(String fieldId, MerchantFieldsVo vo) {
        Query query = Query.query(Criteria.where("fieldId").is(fieldId));
        Document document = (Document)mongoConverter.convertToMongoType(vo);
        Update update = Update.fromDocument(document);
        mongoTemplate.upsert(query, update, MerchantFieldsVo.class, MerchantFieldsVo.class.getSimpleName());
    }

    public MerchantSponsorsVo getSponsorsVoBySponsorId(String sponsorId) {
        return mongoTemplate.findOne(Query.query(Criteria.where("sponsorId").is(sponsorId)), MerchantSponsorsVo.class, MerchantSponsorsVo.class.getSimpleName());
    }

    public void setSponsorsVoBySponsorId(String sponsorId, MerchantSponsorsVo vo) {
        Query query = Query.query(Criteria.where("sponsorId").is(sponsorId));
        Document document = (Document)mongoConverter.convertToMongoType(vo);
        Update update = Update.fromDocument(document);
        mongoTemplate.upsert(query, update, MerchantSponsorsVo.class, MerchantSponsorsVo.class.getSimpleName());
    }
}
