package com.boman.save.controller;

import com.alibaba.fastjson.JSONObject;
import com.boman.common.core.utils.SpringUtils;
import com.boman.common.core.utils.StringUtils;
import com.boman.common.core.web.controller.BaseController;
import com.boman.common.core.web.domain.AjaxResult;
import com.boman.common.redis.service.RedisService;
import com.boman.save.proxy.MyInvocationHandler;
import com.boman.save.utils.ClassUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;

/**
 * @author shiqian
 * @description objSave保存
 * @date 2021年03月18日 10:57
 **/
@RequestMapping("/objSave")
@RestController
public class ObjSaveController extends BaseController {

    @Autowired
    private RedisService redisService;
    @Autowired
    private SqlSession sqlSession;

    @PostMapping
    @SuppressWarnings("unchecked")
    public AjaxResult objSave(@RequestBody Map<String, Object> param) throws IllegalAccessException
            , InstantiationException, InvocationTargetException, ClassNotFoundException, NoSuchMethodException {
        String tableName = (String) param.get("table");
        if (StringUtils.isEmpty(tableName)) {
            return AjaxResult.error();
        }

        JSONObject json = redisService.getCacheObject(packTableKey(tableName.toLowerCase()));
        String entityClassName = "com.boman.save.domain." + json.getString("className");
        Class<?> entityClass = ClassUtils.getClass(entityClassName);
        Object entity = entityClass.newInstance();
        Map<String, Object> fixedData = (Map<String, Object>) param.get("fixedData");
        BeanUtils.populate(entity, fixedData);

        String mapperClassName = "com.boman.save.mapper." + json.getString("className") + "Mapper";
        Class<?> mapperClass = ClassUtils.getClass(mapperClassName);

        Object instance = Proxy.newProxyInstance(
                mapperClass.getClassLoader(),
                new Class[]{mapperClass},
                new MyInvocationHandler(sqlSession.getMapper(mapperClass))
        );

        Method method = instance.getClass().getMethod("insert", entityClass);
        method.invoke(instance,entity);

        return AjaxResult.success();
    }

    public String packTableKey(String tableName){
        return "table:"+ tableName;
    }

}
