package com.cftech.core.mybatis.mybatis;

import com.cftech.core.util.DateUtils;
import com.cftech.core.util.StringUtils;

public class ControllerGenerator extends AbstractMybatisGenerator {
	@Override
    public void outputJavaCode(TableBean tableBean) {
        if (tableBean != null) {
            String rootPath = "";
            if (StringUtils.isBlank(rootPath)) {
                rootPath = System.getProperty("user.dir");
            }
            if (!rootPath.endsWith("/src/main/java") || !rootPath.endsWith("src/main/java/")) {
                if (rootPath.endsWith("/")) {
                    rootPath += "src/main/java/";
                } else {
                    rootPath += "/src/main/java/";
                }
            }
            String basePackage = tableBean.getBasePackage();

            String filePath = rootPath + basePackage.replace(pointStr, "/") + "/";
            String entityName = tableBean.getEntityName();
            String serviceFilePath = filePath + "web/" + entityName + "Controller.java";
            String modelPackage = tableBean.getPackageName();
            // outputJavaFile(daoFilePath, generateMapper(basePackage, modelPackage, entityName).toString());
            outputJavaFile(serviceFilePath, generateServiceImpl(basePackage, modelPackage, entityName).toString());
        }
    }
	
	 /**
     * generateServiceImpl
     *
     * @param basePackage
     * @param modelPackage
     * @param entityName
     * @return StringBuffer
     */
    public StringBuffer generateServiceImpl(String basePackage, String modelPackage, String entityName) {
        StringBuffer sb = new StringBuffer();

        String clazzSimpleName = entityName;
        String clazzNameLower = clazzSimpleName.substring(0, 1).toLowerCase() + clazzSimpleName.substring(1);

        String packageSuffix = "web";
        String suffix = "web";
        String suffixUpper = suffix.substring(0, 1).toUpperCase() + suffix.substring(1);
        sb.append("package ").append(basePackage).append(pointStr).append(packageSuffix).append(semicolon).append(enter);
        sb.append(enter);
        sb.append("import java.io.File;"
        		+enter+
        		"import java.io.IOException;");
        sb.append("import java.util.Date;").append(enter);
        sb.append("import java.util.List;").append(enter);
        sb.append("import javax.servlet.http.HttpServletRequest;").append(enter);
        sb.append("import javax.servlet.http.HttpServletResponse;").append(enter);
        sb.append("import org.apache.shiro.authz.annotation.RequiresPermissions;").append(enter);
        sb.append("import org.springframework.beans.factory.annotation.Autowired;").append(enter);
        sb.append("import org.springframework.stereotype.Controller;").append(enter);
        sb.append("import org.springframework.ui.Model;").append(enter);
        sb.append("import org.springframework.web.bind.annotation.RequestMapping;").append(enter);
        sb.append("import org.springframework.web.bind.annotation.RequestMethod;").append(enter);
        sb.append("import org.springframework.web.bind.annotation.RequestParam;").append(enter);
        sb.append("import org.springframework.web.bind.annotation.ResponseBody;").append(enter);
        sb.append("import com.alibaba.fastjson.JSONObject;").append(enter);
        sb.append("import OrderType;").append(enter);
        sb.append("import ExcelKit;").append(enter);
        sb.append("import Conds;").append(enter);
    	sb.append("import Sort;").append(enter);
    	sb.append("import Constants;").append(enter);
    	sb.append("import DateUtils;").append(enter);
    	sb.append("import ExcelUtils;").append(enter);
    	sb.append("import StringUtils;").append(enter);
    	sb.append("import PermissionSign;").append(enter);
    	sb.append("import UserUtils;").append(enter);
    	sb.append("import org.springframework.web.multipart.MultipartFile;");
        sb.append(enter);
        String serviceSuffix = "service";
        String serviceSuffixUpper = "Service";
        String importString = "import ";
        sb.append(importString).append(basePackage).append(pointStr).append(serviceSuffix).append(pointStr);
        sb.append(clazzSimpleName).append(serviceSuffixUpper).append(semicolon).append(enter);
        sb.append(importString).append(modelPackage).append(pointStr).append(clazzSimpleName).append(semicolon).append(enter);
        //sb.append(importString).append(basePackage).append(pointStr).append(suffix).append(pointStr).append(clazzSimpleName);
        //sb.append(suffixUpper).append(semicolon).append(enter);
        sb.append(enter);
        sb.append("/**").append(enter);
        sb.append("*权限字符串说明:").append(enter);
        sb.append("*查看:public static final String "+clazzSimpleName.toUpperCase()+ "_VIEW = \"qy:"+clazzSimpleName.toLowerCase()+":view\"").append(enter);
        sb.append("*查看:public static final String "+clazzSimpleName.toUpperCase()+ "_EDIT = \"qy:"+clazzSimpleName.toLowerCase()+":edit\"").append(enter);
        sb.append(" * ").append(clazzNameLower).append(suffixUpper).append(enter);
        // sb.append(" * @author ice").append(enter);
        sb.append(" * Created by " + this.authorName + " " + DateUtils.getDate("dd/MM/yyyy") + ".").append(enter);
        sb.append(" */").append(enter);
        sb.append("@Controller").append(enter);
        sb.append("@RequestMapping(\"/a/"+clazzNameLower+"\")").append(enter);
        sb.append("public class ").append(clazzSimpleName).append("Controller").append(" {").append(enter);
        sb.append(enter);
        sb.append(tab).append("/**").append(enter);
        sb.append(tab).append(" * ").append(clazzNameLower).append(serviceSuffixUpper).append(enter);
        sb.append(tab).append(" */").append(enter);
        sb.append(tab).append("@Autowired").append(enter);
        sb.append(tab).append("private ").append(clazzSimpleName).append(serviceSuffixUpper);
        sb.append(" ").append(clazzNameLower).append(serviceSuffixUpper).append(semicolon).append(enter);
        sb.append(enter);
        
        //生成列表页面
        sb.append("//返回列表页面");
        sb.append(enter);
        sb.append(tab).append("@RequiresPermissions(value = PermissionSign");
        sb.append(pointStr+clazzSimpleName.toUpperCase()+"_VIEW").append(")");
        sb.append(tab).append("@RequestMapping(\"/list\")"); 
        sb.append(tab).append(" public String ").append("list").append("(Model model,HttpServletRequest request){");
        sb.append("return \""+clazzSimpleName.toLowerCase()+"/"+clazzSimpleName.toLowerCase()+"list\";"+"}");
        sb.append(enter);
        
      //返回编辑页面（新增、修改）
        sb.append(enter);
        sb.append("//返回编辑页面（新增、修改）");
        sb.append(enter);
        sb.append(tab).append("@RequiresPermissions(value = PermissionSign");
        sb.append(pointStr+clazzSimpleName.toUpperCase()+"_VIEW").append(")");
        sb.append(tab).append("@RequestMapping(\"/form\")"); 
        sb.append(" public String form(String id, Model model) {"
        		+ "if (StringUtils.isNotBlank(id)) {"
        		+ " "
        		+ " "+clazzSimpleName + " "
        		+ " "+clazzNameLower+ " = "
        		+ " "+clazzNameLower+serviceSuffixUpper+".fetchById(id);"
        		+"model.addAttribute(\"data\", "+clazzNameLower+");}return \""+clazzSimpleName.toLowerCase()+"/"+clazzSimpleName.toLowerCase()+"form\";}");
       //编辑提交数据
        sb.append(enter);
        sb.append("//提交编辑页面（新增、修改）");
        sb.append(enter);
        sb.append(tab).append("@RequiresPermissions(value = PermissionSign");
        sb.append(pointStr+clazzSimpleName.toUpperCase()+"_EDIT").append(")");
        sb.append(tab).append("@RequestMapping(\"/formData\")"); 
        sb.append(tab).append("@ResponseBody");
        sb.append(tab).append(" public JSONObject "+clazzNameLower+"ListformData("+clazzSimpleName+" "+clazzNameLower+",Model model, HttpServletRequest request) {");
        sb.append(tab).append("JSONObject rtnJson = new JSONObject();");
        sb.append(tab).append("try {if ("+clazzNameLower+" != null && "+clazzNameLower+".getId() != null) {");
        sb.append(tab).append(clazzNameLower+".setUpdateby(UserUtils.getUser().getId());");
		sb.append(tab).append(clazzNameLower+serviceSuffixUpper+".update("+clazzNameLower+");");
		sb.append(tab).append("rtnJson.put(\"errorNo\", 0);} else {");
		sb.append(tab).append(clazzNameLower+".setDelflag(false);"
				+ clazzNameLower+".setAccountsId(UserUtils.getmpaccounts(request));"
				+ clazzNameLower+".setCreateby(UserUtils.getUser().getId());"
				+ clazzNameLower+".setUpdateby(UserUtils.getUser().getId());"
				+ clazzNameLower+serviceSuffixUpper+".save("+clazzNameLower+");rtnJson.put(\"errorNo\", 2);}");
		sb.append("} catch (Exception e) {rtnJson.put(\"errorNo\", 1);}");
		sb.append("return rtnJson;");
		sb.append("}");
		
		//获取列表数据
		sb.append(enter);
		sb.append("//获取列表数据");
		sb.append(enter);
        sb.append(tab).append("@RequiresPermissions(value = PermissionSign");
        sb.append(pointStr+clazzSimpleName.toUpperCase()+"_VIEW").append(")");
        sb.append(tab).append("@RequestMapping(value = \"/listData\", method = RequestMethod.GET)"); 
        sb.append("@ResponseBody");
        sb.append(enter);
		sb.append("public JSONObject listData(int iDisplayStart, int iDisplayLength,"+clazzSimpleName+" "+clazzNameLower+", HttpServletRequest request) {");
		sb.append("Long accountsId = UserUtils.getmpaccounts(request);");
		sb.append("Conds conds = new Conds();"
				+ "conds.equal(\"delflag\", false);"
				+ "conds.equal(\"accounts_id\", accountsId);"
				+ "if (StringUtils.isNotBlank("+clazzNameLower+".getName())) {"
				+ "conds.like(\"name\", "+clazzNameLower+".getName());"
				+ "}");
		sb.append("Sort sort = new Sort(\"createtime\", OrderType.DESC);"
				+ "List<"+clazzSimpleName+"> list ="+clazzNameLower+serviceSuffixUpper
				+ ".fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);"
				+ "Integer userCounts = "+clazzNameLower+serviceSuffixUpper+".count(conds);"
				+ "JSONObject rtnJson = new JSONObject();"
				+ "rtnJson.put(\"iTotalRecords\", userCounts);"
				+ "rtnJson.put(\"iTotalDisplayRecords\", userCounts);"
				+ "rtnJson.put(\"aaData\", list);"
				+ "return rtnJson;}");
		//删除数据
		sb.append(enter);
		sb.append("//删除数据");
		sb.append(enter);
        sb.append(tab).append("@RequiresPermissions(value = PermissionSign");
        sb.append(pointStr+clazzSimpleName.toUpperCase()+"_EDIT").append(")");
        sb.append(tab).append("@RequestMapping(\"/remove\")"); 
        sb.append("@ResponseBody");
        sb.append(enter);
        sb.append(" public JSONObject commoditypeList(String id) {");
        sb.append("JSONObject rtnJosn = new JSONObject();"
        		+ "try {"+clazzNameLower+serviceSuffixUpper+".delete(id);"
        				+ "rtnJosn.put(\"errorNo\",0);"
        		+ "} catch (Exception e) {rtnJosn.put(\"errorNo\",1);}return rtnJosn;}"
        		+ "");
        
      //导出数据
        sb.append(enter);
        sb.append("//导出数据");
        sb.append(enter);
        sb.append(tab).append("@RequiresPermissions(value = PermissionSign");
        sb.append(pointStr+clazzSimpleName.toUpperCase()+"_EDIT").append(")");
        sb.append(tab).append("@RequestMapping(value = \"/exportListData\", method = RequestMethod.GET)"); 
        sb.append("@ResponseBody");
        sb.append(" public void cardFetechData("+clazzSimpleName+" "+clazzNameLower+", HttpServletRequest request,HttpServletResponse response) {"
        		+ "Long accountsId = UserUtils.getmpaccounts(request);Conds conds = new Conds();conds.equal(\"delflag\", false);"
        		+ "conds.equal(\"accounts_id\", accountsId);"
        		+ "if (StringUtils.isNotBlank("+clazzNameLower+".getName())) {"
        		+ "conds.like(\"name\", "+clazzNameLower+".getName());"
        		+ "}"
        		+ "Sort sort = new Sort(\"createtime\", OrderType.DESC);"
        		+ "List<"+clazzSimpleName+"> list = "+clazzNameLower+serviceSuffixUpper+".fetchSearchByPage(conds, sort, 0, 0);"
        		+ "try {"
        		+"ExcelKit.$Export("+clazzSimpleName+".class, response).toExcel(list, \"信息\");"
        		+ "} catch (Exception e) {e.printStackTrace();}}"
        		+ "");
        
        //查看详情
//        sb.append(enter);
//        sb.append("//查看详情");
//        sb.append(enter);
//        sb.append(tab).append("@RequiresPermissions(value = PermissionSign");
//        sb.append(pointStr+clazzSimpleName.toUpperCase()+"_EDIT").append(")");
//        sb.append(tab).append("@RequestMapping(value=\"/dataDetail\",method = RequestMethod.POST)"); 
//        sb.append("@ResponseBody");
//        sb.append(enter);
//        sb.append("public JSONObject dataDetail(@RequestParam(\"id\") String id){"
//        		+ "JSONObject rtnJson = new JSONObject();"
//        		+ "try {"
//        		+ " "
//        		+ " "+clazzSimpleName + " "
//        		+ " "+clazzNameLower+ " = "
//        		+ " "+clazzNameLower+serviceSuffixUpper+".fetchById(id);"
//        		+ "rtnJson.put(\"errorNo\",0);"
//        		+ "rtnJson.put(\"data\","+clazzNameLower+");"
//        		+ "} catch (Exception e) {"
//        		+ "rtnJson.put(\"errorNo\",1);"
//        		+ "}"
//        		+ "return rtnJson;"
//        		+ "}");
        
        //导入数据（生成后需自己手写相关填数据）
        sb.append("@RequestMapping(\"/importExcel\")");
        sb.append(tab).append("@RequiresPermissions(value = PermissionSign");
        sb.append(pointStr+clazzSimpleName.toUpperCase()+"_EDIT").append(")");
        sb.append(enter);
        sb.append("public String importExcel(HttpServletRequest request, MultipartFile file, Model model) {");
        sb.append(enter).append("Long accountId = UserUtils.getmpaccounts(request);");
        sb.append(enter).append("if (file == null) {");
        sb.append(enter).append("return list(model,request);");
        sb.append(enter).append("}");
        sb.append(enter).append("// 构造临时路径来存储上传的文件");
        sb.append(enter).append("String uploadPath = System.getProperty(\"java.io.tmpdir\");");
        sb.append(enter).append("File uploadDir = new File(uploadPath);");
        sb.append(enter).append("if (!uploadDir.exists()) {");
        sb.append(enter).append("uploadDir.mkdir();");
        sb.append("}");
        sb.append("String fileName = file.getOriginalFilename();");
        sb.append("String filePath = uploadPath + File.separator + fileName;");
        sb.append("File storeFile = new File(filePath);");
        sb.append(enter).append("try {");
        sb.append(enter).append("file.transferTo(storeFile);");
        sb.append(enter).append("ExcelKit.$Import().readExcel(storeFile, rowData -> {");
        sb.append(enter).append(clazzSimpleName + " " + clazzNameLower + " " + "= new " +clazzSimpleName+"();");
        sb.append(enter).append(clazzNameLower+serviceSuffixUpper+".save("+clazzNameLower+");");
        sb.append("});");
        sb.append("} catch (IOException e) {e.printStackTrace();}return list(model,request);}");
        //导入时下载模板
        sb.append(tab).append("@RequestMapping(\"/templateExcel\")");
        sb.append(tab).append("@RequiresPermissions(value = PermissionSign");
        sb.append(pointStr+clazzSimpleName.toUpperCase()+"_VIEW").append(")");
        sb.append(enter);
        sb.append("public void templateExcel(HttpServletRequest request, HttpServletResponse response) {");
        sb.append(enter);
        sb.append("// 生成Excel并使用浏览器下载");
        sb.append(enter);
		sb.append("ExcelKit.$Export("+clazzSimpleName+".class, response).toExcel(null, \"信息\");}}");
        return sb;
    }
}
