package com.ag.web.agCommon;

import com.ag.secp.platform.common.CommonUtil;
import com.ag.secp.platform.common.WbUtil;
import com.ag.secp.platform.spring.SpringApplicationContext;
import com.ag.until.ReflexObjectUtil;
import com.alibaba.fastjson.JSON;
import com.wb.util.WebUtil;
import org.apache.commons.beanutils.PropertyUtils;
import org.json.JSONObject;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ReflectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by WangN on 2017/9/9.
 * 用于可编辑Grid增删改最终保存
 */
@Service
public class ComBean {
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    public String forItem(List list, String type, HttpServletRequest request, String dataJson) {
        for (int i = 0; list != null && i < list.size(); i++) {
            Object appt = (Object) list.get(i);

            if (type.equals("insertSql")) {
                sqlSessionTemplate.insert(request.getParameter("insertSql"), appt);
                dataJson += JSON.toJSONString(appt) + ",";
            }
            if (type.equals("updateSql")) {
                try {
                    PropertyUtils.setProperty(appt, "updatedBy", (String) request.getSession().getAttribute("sys.username"));
                    PropertyUtils.setProperty(appt, "updatedOn", WbUtil.getNowDate());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                sqlSessionTemplate.update(request.getParameter("updateSql"), appt);
                dataJson += JSON.toJSONString(appt) + ",";
            }
            if (type.equals("deleteSql")) {

                sqlSessionTemplate.delete(request.getParameter("deleteSql"), appt);
                dataJson += JSON.toJSONString(appt) + ",";
            }
        }
        if (dataJson != null) {
            dataJson = dataJson.substring(0, dataJson.length() - 1);
            dataJson = dataJson.substring(4, dataJson.length());

        }
        return dataJson;
    }
    @Transactional
    public  void saveGrid(JSONObject object, HttpServletResponse response, HttpServletRequest request) throws ClassNotFoundException, NoSuchMethodException {
       // SpringApplicationContext.getBean(bean)
        Class objectClass = Class.forName(request.getParameter("className"));
        List createList = CommonUtil.getBeanlist(object, "datatable", "create", objectClass);
        List updateList = CommonUtil.getBeanlist(object, "datatable", "update", objectClass);
        List destroyList = CommonUtil.getBeanlist(object, "datatable", "destroy", objectClass);
        String dataJson=null;
        String  createReturn=forItem(createList, "insertSql", request, dataJson);
        String  updateReturn=forItem(updateList, "updateSql", request, dataJson);
        //删除的就不返回了
        forItem(destroyList, "deleteSql", request, dataJson);
        //拼JSON
        if(createReturn!=null){
            dataJson+="["+createReturn;
            dataJson=dataJson.substring(4,dataJson.length());
        }else{
            dataJson+="[";
            dataJson=dataJson.substring(4,dataJson.length());
        }
        if(updateReturn!=null&&createReturn!=null){
            dataJson+=","+updateReturn+"]";
        }else if (updateReturn!=null&&createReturn==null){
            dataJson+=updateReturn+"]";
        }else{
            dataJson+="]";
        }

        try {
            WebUtil.send(response, dataJson);
        } catch(IOException e) {
            e.printStackTrace();
        }
    }


    public void saveGridplus(JSONObject object, HttpServletResponse response, HttpServletRequest request) throws Exception {
        Class objectClass = Class.forName(request.getParameter("className"));
        List createList = CommonUtil.getBeanlist(object, "datatable", "create", objectClass);
        List updateList = CommonUtil.getBeanlist(object, "datatable", "update", objectClass);
        List destroyList = CommonUtil.getBeanlist(object, "datatable", "destroy", objectClass);

        String method = request.getParameter("method");//方法名
        String beanname = request.getParameter("beanName");//bean名称
        JSONObject fields = WebUtil.fetch(request);//字段


        if(updateList.size()>0) {
            //执行update
            Method methodname = ReflectionUtils.findMethod(SpringApplicationContext.getBean(beanname).getClass(),
                    "updateBatchById", java.util.Collection.class);
            ReflectionUtils.invokeMethod(methodname, SpringApplicationContext.getBean(beanname), updateList);
        }

        if(createList.size()>0) {
            //执行保存
            Method methodnamesave = ReflectionUtils.findMethod(SpringApplicationContext.getBean(beanname).getClass(),
                    "saveBatch", java.util.Collection.class);
            ReflectionUtils.invokeMethod(methodnamesave, SpringApplicationContext.getBean(beanname), createList);
        }


        //执行删除

        if(destroyList.size()>0) {
            List datalist = new ArrayList();
            for (int i = 0; i < destroyList.size(); i++) {
                Object dataobj = destroyList.get(i);
                String data = ReflexObjectUtil.getValueByKey(dataobj, "id").toString();
                datalist.add(data);
            }

            Method methodnamedel = ReflectionUtils.findMethod(SpringApplicationContext.getBean(beanname).getClass(),
                    "removeByIds", java.util.Collection.class);
            ReflectionUtils.invokeMethod(methodnamedel, SpringApplicationContext.getBean(beanname), datalist);

        }
        String dataJson = null;
    }

}
