package com.github.wxiaoqi.security.common.biz;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.util.EntityUtils;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * Created by Mr.AG
 * Date: 17/1/13
 * Time: 15:13
 * Version 1.0.0
 */
public abstract class BaseBiz<M extends Mapper<T>, T> {
    @Autowired
    protected M mapper;

    public void setMapper(M mapper) {
        this.mapper = mapper;
    }

    public T selectOne(T entity) {
        return mapper.selectOne(entity);
    }


    public T selectById(Object id) {
        return mapper.selectByPrimaryKey(id);
    }


    public List<T> selectList(T entity) {
        return mapper.select(entity);
    }


    public List<T> selectListAll() {
        return mapper.selectAll();
    }


    public Long selectCount(T entity) {
        return new Long(mapper.selectCount(entity));
    }


    public void insert(T entity) {
        EntityUtils.setCreatAndUpdatInfo(entity);
        mapper.insert(entity);
    }


    public void insertSelective(T entity) {
        insertSelectiveRe(entity);
    }

    public void insertMultiSelective(List<T> entitys) {
        for(T entity : entitys) {
            insertSelectiveRe(entity);
        }
    }


    public int insertSelectiveRe(T entity) {
        EntityUtils.setCreatAndUpdatInfo(entity);
        return mapper.insertSelective(entity);
    }

    public void delete(T entity) {
        mapper.delete(entity);
    }


    public void deleteById(Object id) {
        mapper.deleteByPrimaryKey(id);
    }


    public void updateById(T entity) {
        updateByIdRe(entity);
    }

    public void updateSelectiveById(T entity) {
        updateSelectiveByIdRe(entity);
    }

    public int updateByIdRe(T entity) {
        EntityUtils.setUpdatedInfo(entity);
        return mapper.updateByPrimaryKey(entity);
    }

    public int updateSelectiveByIdRe(T entity) {
        EntityUtils.setUpdatedInfo(entity);
        return mapper.updateByPrimaryKeySelective(entity);
    }

    public List<T> selectByExample(Object example) {
        return mapper.selectByExample(example);
    }

    public int selectCountByExample(Object example) {
        return mapper.selectCountByExample(example);
    }

    public TableResultResponse<T> selectByQuery(Query query) {
        Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
        Example example = new Example(clazz);
        if(query.entrySet().size()>0) {
            Example.Criteria criteria = example.createCriteria();
            for (Map.Entry<String, Object> entry : query.entrySet()) {
                criteria.andLike(entry.getKey(), "%" + entry.getValue().toString() + "%");
            }
        }
        Page<Object> result = PageHelper.startPage(query.getPage(), query.getLimit());
        List<T> list = mapper.selectByExample(example);
        return new TableResultResponse<T>(result.getTotal(), list);
    }

    public TableResultResponse<T> selectPageByQuery(Query query) {
        Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
        Example example = new Example(clazz);
        Example.Criteria criteria=null;

        if (checkFieldName(clazz,"isDel")){
            criteria=example.createCriteria();
            criteria.andEqualTo("isDel",0);
        }
        if (checkFieldName(clazz,"isDelete")){
            criteria=example.createCriteria();
            criteria.andEqualTo("isDelete",0);
        }
        if(query.entrySet().size()>0) {
            if (criteria==null){
                criteria=example.createCriteria();
            }
            for (Map.Entry<String, Object> entry : query.entrySet()) {
                if(null != entry.getValue()) {
                    criteria.andLike(entry.getKey(), "%" + entry.getValue().toString() + "%");
                }
            }
        }
        if (checkFieldName(clazz,"sortOrder")) {
            example.setOrderByClause("sort_order desc");
        }else if(checkFieldName(clazz,"rank")){
            example.setOrderByClause("rank desc");
        }else {
            example.setOrderByClause("id desc");
        }
        Page<Object> result = PageHelper.startPage(query.getPage(), query.getLimit());
        List<T> list = mapper.selectByExample(example);
        return new TableResultResponse<T>(result.getTotal(), list);
    }

    public ObjectRestResponse selectAll(){
        List<T> list = selectListAlls();
        return ObjectRestResponse.succ(list);
    }

    public List<T> selectListAlls(){
        Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
        Example example = new Example(clazz);
        Example.Criteria criteria=example.createCriteria();
        if (checkFieldName(clazz,"isDel")){
            criteria.andEqualTo("isDel",0);
        }
        if (checkFieldName(clazz,"sortOrder")){
            example.setOrderByClause("sort_order desc");
        }else if(checkFieldName(clazz,"rank")){
            example.setOrderByClause("rank desc");
        }else {
            example.setOrderByClause("id desc");
        }
        return mapper.selectByExample(example);
    }


    public List<T> getList(String appId)throws  Exception{
        Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
        Example example = new Example(clazz);
        Example.Criteria criteria=example.createCriteria();
        if (checkFieldName(clazz,"isDel")){
            criteria.andEqualTo("isDel",0);
        }
        example.setOrderByClause("id desc");
        return mapper.selectByExample(example);
    }

    public  boolean checkFieldName(Class<T> clazz,String fieldname){
        Field[] fields=clazz.getDeclaredFields();
        boolean flag=false;
        for (int i = 0; i < fields.length; i++) {
            if(fields[i].getName().equals(fieldname))
            {
                flag=true;
                break;
            }
        }
        return  flag;
    }



}
