package com.zhongshu.card.server.core.dao.payment.impl;

import com.zhongshu.card.server.core.dao.payment.extend.ComplexDaoExtend;
import com.zhongshu.card.server.core.domain.payment.Complex;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

public class ComplexDaoImpl implements ComplexDaoExtend {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public Complex findByAccesser_user_id(String epId) {

        Query query = new Query(Criteria.where("accesser_user_id").is(epId));

        List<Complex> complexes = mongoTemplate.find(query, Complex.class);
        if (complexes.size() == 0) {


            return null;
        }
        return mongoTemplate.find(query, Complex.class).get(0);

    }

    @Override
    public Complex findByAccesser_user_idAndEpId(String accesseId, String epId) {

        Query query = new Query(Criteria.where("accesser_user_id").is(accesseId).and("epId").is(epId));

        List<Complex> complexes = mongoTemplate.find(query, Complex.class);
        if (complexes.size() == 0) {


            return null;
        }
        return mongoTemplate.find(query, Complex.class).get(0);
    }

    @Override
    public void deleteByAccesser_user_id(String epId) {
        Query query = new Query(Criteria.where("accesser_user_id").is(epId));

        mongoTemplate.remove(query, Complex.class);

    }

    @Override
    public List<Complex> findAllFinish(String epId) {
        Criteria criteria = Criteria.where("mer_no").ne(null).and("epId").is(epId);
        Query query = new Query(criteria);
        return mongoTemplate.find(query, Complex.class);
    }

    @Override
    public List<Document> findAllFinish() {
        Criteria criteria = Criteria.where("mer_no").ne(null);

        Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(criteria),
                Aggregation.group("accesser_user_id")
                        .first("shop_name").as("shop_name")
                        .first("accesser_user_id").as("accesser_user_id")
                        .first("externalName").as("externalName")
                        .first("mer_no").as("mer_no")
        );


        return mongoTemplate.aggregate(aggregation, "complex", Document.class).getMappedResults();
    }


    @Override
    public List<Complex> findCommit() {
        Criteria criteria = Criteria.where("ums_reg_id").ne(null);
        criteria.and("apply_status").is("02");
        Query query = new Query(criteria);

        return mongoTemplate.find(query, Complex.class);

    }
}
