package com.sinosig.mongodb;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.math.BigInteger;
import java.util.UUID;
import java.util.HashMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoBulkWriteException;
import com.mongodb.WriteResult;
import com.mongodb.bulk.BulkWriteResult;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.BulkOperations;
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.Repository;
import org.springframework.util.ObjectUtils;

import com.sinosig.core.repository.CIDRepository;
import com.sinosig.core.repository.po.CID;
import com.sinosig.mongodb.po.HCIDImpl;
import com.sinosig.core.module.filter.CIDSearchContext;

/**
 * 关系型数据实体表[CID] 对象
 */
@Repository
@ConditionalOnProperty(prefix = "cid", value="store" , havingValue = "nosql", matchIfMissing = false)
public class HCIDRepositoryImpl implements CIDRepository{

    @Autowired
    private MongoTemplate mongoTemplate;

    public CID createPO() {
		return new HCIDImpl();
	}

	public CID get(String key) {
        Query query = new Query(Criteria.where("cidid").is(key));
		return mongoTemplate.findOne(query, HCIDImpl.class,"hcid");
	}

	public boolean create(CID po) {
        if(po.getCIDId()==null){
			po.setCIDId(UUID.randomUUID().toString());
		}
		mongoTemplate.save(po,"hcid");
		return true;
	}

	public boolean update(CID po) {
		Query query = new Query(Criteria.where("cidid").is(po.getCIDId()));
        Update update = new Update();
        String str = JSON.toJSONString(po);
        JSONObject jQuery = JSON.parseObject(str);
        jQuery.forEach((key, value) -> {
            if (!key.equals("cidid")) {
                update.set(key, value);
            }
        });
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, CID.class, "hcid");
        if(updateResult!=null && updateResult.getMatchedCount()>0)
        	return true ;
		return false;
	}

	public boolean remove(String key) {
		Query query = new Query(Criteria.where("cidid").is(key));
        DeleteResult deleteResult = mongoTemplate.remove(query,CID.class,"hcid");
        if(deleteResult != null && deleteResult.getDeletedCount()>0)
        	return true ;
        return false ;
	}

    public Page<CID> searchDefault(CIDSearchContext context){
        List<CID> list = new ArrayList<CID>() ;
        Map<String, String> conditions = null ;
    	if (ObjectUtils.isEmpty(conditions)) {
            List<HCIDImpl> listImpl = mongoTemplate.findAll(HCIDImpl.class,"hcid");
            for (HCIDImpl hcidImpl : listImpl) {
				list.add(hcidImpl);
			}
        } else {
            //设置分页参数
            Query query = new Query();
            query.limit(100);
            query.skip(1);
            // 往query中注入查询条件
            conditions.forEach((key, value) -> query.addCriteria(Criteria.where(key).is(value)));
            list = mongoTemplate.find(query, CID.class,"hcid");
        }
        return new PageImpl<CID>(list, context.getPageable(), 10000);
    }


    public com.sinosig.core.module.domain.CID convert2Domain( CID po ,com.sinosig.core.module.domain.CID domain){
              if(po == null)
                     return domain ;
              if(domain == null){
                     domain = new com.sinosig.core.module.domain.CID();
              }
              BeanCopier copier=BeanCopier.create(po.getClass(), domain.getClass(), false);
              copier.copy(po, domain, null);
              return domain ;
    }

    public CID convert2PO(com.sinosig.core.module.domain.CID domain , CID po){
        if(domain == null)
            return po ;
        if(po==null){
            po = createPO() ;
        }
        BeanCopier copier=BeanCopier.create(domain.getClass(), po.getClass(), false);
        copier.copy(domain, po, null);
        return po ;
    }

}

