package com.ag.web.agCommon;

import com.ag.base.BaseService;
import com.ag.dynamicmodule.main.HotApplicationContext;
import com.ag.util.CommonUtil;
import com.ag.log.entity.LogParam;
import com.ag.log.OperLogServcie;
import com.ag.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.IService;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

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

    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", super.getNow());
                } 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+="]";
        }
        if (object.has("keyword") && object.has("bizType")){
            try {
                LogParam logParam = new LogParam(object, object.getString("keyword"), StrUtil.toUpperCol(objectClass.getSimpleName()), null, "datatable");
                logParam.setMenuName(object.getString("bizType"));
                logServcie.saveLogGrid(logParam, response);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

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


    /**
    * @Description:  mybatisPlus 可编辑表格
    * @return: void
    * @Author: fengjun
    * @Date: 2022/8/11
    */
    public void saveGridPlus(JSONObject object, HttpServletResponse response, HttpServletRequest request) throws Exception {
        Class objectClass = Class.forName(request.getParameter("className"));

        IService service;
        if (StrUtil.isNotEmpty(request.getParameter("service"))) {
            Class serviceClass = Class.forName(request.getParameter("service"));
            service = (IService) HotApplicationContext.getBean(serviceClass);
        } else {
            String serviceImpl = objectClass.getSimpleName()+"ServiceImpl";
            serviceImpl = serviceImpl.substring(0, 1).toLowerCase() + serviceImpl.substring(1);
            service = (IService) HotApplicationContext.getBean(serviceImpl);
        }

        List createList = CommonUtil.getBeanlist(object, "datatable", "create", objectClass);
        List updateList = CommonUtil.getBeanlist(object, "datatable", "update", objectClass);
        List destroyList = CommonUtil.getBeanlist(object, "datatable", "destroy", objectClass);


        service.saveOrUpdateBatch(createList);
        service.saveOrUpdateBatch(updateList);
        service.removeBatchByIds(destroyList);
    }

}
