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

import com.liquidnet.service.merchant.dto.vo.*;
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;

import java.util.List;

@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());
    }

    public List<MerchantFieldAppliesVo> getFieldAppliesVosByUid(String uid) {
        return mongoTemplate.find(Query.query(Criteria.where("uid").is(uid).and("deletedAt").is(null)), MerchantFieldAppliesVo.class, MerchantFieldAppliesVo.class.getSimpleName());
    }

    public List<MerchantSponsorAppliesVo> getSponsorAppliesVosByUid(String uid) {
        return mongoTemplate.find(Query.query(Criteria.where("uid").is(uid).and("deletedAt").is(null)), MerchantSponsorAppliesVo.class, MerchantSponsorAppliesVo.class.getSimpleName());
    }

    public List<MerchantAuthorizationRecordsVo> getCheckersAuthorizationRecordsVosByCuid(String cuid, String performanceId) {
        return mongoTemplate.find(Query.query(Criteria.where("uidRole").is("checker").and("cuid").is(cuid).and("performanceId").is(performanceId).and("deletedAt").is(null)), MerchantAuthorizationRecordsVo.class, MerchantAuthorizationRecordsVo.class.getSimpleName());
    }
}
