package com.hzya.frame.basedao.service.impl;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzya.frame.basedao.dao.IBaseDao;
import com.hzya.frame.basedao.service.IBaseService;
import com.hzya.frame.page.PageAttribute;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
public abstract class BaseService<E extends Serializable, PK extends Serializable> implements IBaseService<E, PK> {

    protected Logger logger = LogManager.getLogger(super.getClass());
    protected IBaseDao<E, PK> dao;
    private Class<?> entityClass;
    private E entity;
    public BaseService() {
        Class c = super.getClass();
        Type t = c.getGenericSuperclass();
        if (t instanceof ParameterizedType) {
            this.entityClass = ((Class) ((ParameterizedType) t).getActualTypeArguments()[0]);
            //this.logger.info("enityClass : " + this.entityClass.toString());
        }
    }

    @Override
    public E get(PK id) {
        return this.dao.get(id);
    }

    @Override
    public int removeById(PK id) throws Exception {
        return this.dao.delete(id);
    }

    @Override
    public int logicRemove(E e) throws Exception {
        return this.dao.logicRemove(e);
    }
    @Override
    public int logicRemoveMultiCondition(E e) {
        return this.dao.logicRemoveMultiCondition(e);
    }
    @Override
    public List<E> getAll() {
        return this.dao.getAll();
    }

    @Override
    @DS("#o.dataSourceCode")
    public List<E> query(E o) {
        return this.dao.query(o);
    }

    @Override
    public E queryOne(E o) {
        List tempList = this.dao.query(o);
        if ((tempList != null) && (tempList.size() > 0)) {
            return (E) tempList.get(0);
        }

        return null;
    }

    @Override
    public List<E> queryByLike(E o) {
        return this.dao.queryByLike(o);
    }
    /**
     * @Author lvleigang
     * @Description  获取对象转换成jsonobj
     * @Date 11:51 下午 2023/7/10
     * @param key
     * @param object
     * @return com.alibaba.fastjson.JSONObject
     **/
    public JSONObject getstrObj(String key, JSONObject object) {
        if (checkStr(object.getString(key)) ) {
            return object.getJSONObject(key);
        }
        return new JSONObject();
    }
    @Override
    public List<E> queryByOr(E o) {
        return this.dao.queryByOr(o);
    }

    @Override
    public E saveOrUpdate(E o) {
        Serializable result = this.dao.saveOrUpdate(o);
        return (E) result;
    }

    @Override
    public E save(E o) throws Exception {
        Serializable result = this.dao.save(o);
        return (E) result;
    }

    @Override
    public E update(E o) throws Exception {
        Serializable result = this.dao.update(o);
        return (E) result;
    }

    public PageAttribute<E> queryPaged(String statement, Map<String, Object> parameterMap) {
        return this.dao.queryPaged(statement, parameterMap);
    }

    @Override
    public PageAttribute<E> queryPaged(String statement, E baseEntity) {
        return this.dao.queryPaged(statement, baseEntity);
    }

    @Override
    public PageAttribute<E> queryPaged(E baseEntity) {
        return this.dao.queryPaged(baseEntity);
    }

    @Override
    public JsonResultEntity queryPagedJson(JSONObject object) {
        E entity = (E)getData("jsonStr", object,this.entityClass);
        Class entityClass = entity.getClass();
        Method[] methods =  entityClass.getMethods();
        int pageNum = 1;
        int pageSize = 10;
        for (Method f : methods) {
            String fieldName = f.getName();
            if("getPageSize".equals(fieldName)){
                f.setAccessible(true);
                try {
                    pageSize = (int)f.invoke(entity);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    return BaseResult.getFailureMessageEntity("分页参数错误");
                }
            }
            if("getPageNum".equals(fieldName)){
                f.setAccessible(true);
                try {
                    pageNum = (int)f.invoke(entity);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    return BaseResult.getFailureMessageEntity("分页参数错误");
                }
            }
        }
        PageHelper.startPage(pageNum, pageSize);
        List<E> queryByLike = this.dao.queryByLike(entity);
        PageInfo pageInfo = new PageInfo(queryByLike);
        return BaseResult.getSuccessMessageEntity("查询数据成功", pageInfo);
    }
    protected <T> T getData(String key, JSONObject jsonObject, Class<T> clz) {
        if (checkStr(jsonObject.getString(key)) ) {
            return jsonObject.getJSONObject(key).toJavaObject(clz);
        }
        return null;
    }

    protected <T> T getData(String str,  Class<T> clz) {
        if (checkStr(str) ) {
            return JSONObject.parseObject(str).toJavaObject(clz);
        }
        return null;
    }
    /**
     * @param str
     * @return void
     * @Author lvleigang
     * @Description 校验字符串
     * @Date 11:41 上午 2022/12/7
     **/
    protected Boolean checkStr(String str) {
        Boolean flag = true;
        if (str == null || "".equals(str)) {
            flag = false;
        }
        return flag;
    }

    /**
     * @param str
     * @return void
     * @Author lvleigang
     * @Description 校验字符串
     * @Date 11:41 上午 2022/12/7
     **/
    protected Boolean checkInt(Integer str) {
        Boolean flag = true;
        if (str == null) {
            flag = false;
        }
        return flag;
    }
    @Override
    public boolean checkRepeated(E o) {
//		Class TargetClass;
//		try {
//			TargetClass = o.getClass();
//			List fieldList = UtilHelper.getPrimaryNameList(TargetClass);
//			String id = BeanUtils.getProperty(o, "id");
//			if (fieldList == null)
//				return false;
//
//			Object param = org.springframework.beans.BeanUtils.instantiate(TargetClass);
//			for (int i = 0; i < fieldList.size(); ++i) {
//				Field field = (Field) fieldList.get(i);
//				String name = field.getName();
//				BeanUtils.setProperty(param, name, BeanUtils.getProperty(o, name));
//			}
//			List resultList = query((E) param);
//			if ((resultList != null) && (resultList.size() > 0)) {
//				if ((id == null) || ("".equals(id)))
//					return true;
//
//				Object tempResult = resultList.get(0);
//				String tempId = BeanUtils.getProperty(tempResult, "id");
//
//				return (!(tempId.equals(id)));
//			}
//
//			return false;
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
        return false;
    }


    @Override
    public JsonResultEntity queryListJson(JSONObject object) {
        E entity = (E)getData("jsonStr", object,this.entityClass);
        List<E> queryByLike = this.dao.queryByLike(entity);
        return BaseResult.getSuccessMessageEntity("查询数据成功", queryByLike);
    }

    @Override
    public JsonResultEntity saveJson(JSONObject object) {
        E entity = (E)getData("jsonStr", object,this.entityClass);
        E returnEntity = this.dao.save(entity);
        return BaseResult.getSuccessMessageEntity("保存数据成功", returnEntity);
    }

    @Override
    public JsonResultEntity updateJson(JSONObject object) {
        E entity = (E)getData("jsonStr", object,this.entityClass);
        E returnEntity = this.dao.update(entity);
        return BaseResult.getSuccessMessageEntity("修改数据成功", returnEntity);
    }
    @Override
    public JsonResultEntity deleteJson(JSONObject object) {
        E entity = (E)getData("jsonStr", object,this.entityClass);
        Class entityClass = entity.getClass();
        try {
            Method methods = entityClass.getMethod("setModify_user_id",String.class);
            methods.invoke(entity, StpUtil.getLoginIdAsString());
        } catch (NoSuchMethodException |IllegalAccessException | InvocationTargetException e) {
            return BaseResult.getFailureMessageEntity("设置修改人错误");
        }
        int returnEntity = this.dao.logicRemoveMultiCondition(entity);
        return BaseResult.getSuccessMessageEntity("删除数据成功", returnEntity);
    }
}
