package com.jeeplus.modules.filing.basicInformation.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.filing.basicInformation.entity.BasicInformation;
import com.jeeplus.modules.filing.basicInformation.entity.BasicInformationChild;
import com.jeeplus.modules.filing.basicInformation.service.BasicInformationService;
import com.jeeplus.modules.test.onetomany.dialog.entity.TestDataMain1;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 基础信息管理Controller
 * @author qy
 * @version 2021-03-23
 */
@Controller
@RequestMapping(value = "${adminPath}/filing/basicInformation")
public class BasicInformationController extends BaseController {

	@Autowired
	private BasicInformationService basicInformationService;
	
	@ModelAttribute
	public BasicInformation get(@RequestParam(required=false) String id) {
		BasicInformation entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = basicInformationService.get(id);
		}
		if (entity == null){
			entity = new BasicInformation();
		}
		return entity;
	}
	
	/**
	 * 基础信息列表页面
	 */
	@RequiresPermissions("test:filing:basicInformation:list")
	@RequestMapping(value = {"list", ""})
	public String list(BasicInformation basicInformation, Model model) {
		model.addAttribute("basicInformation", basicInformation);
		return "modules/filing/basicInformation/basicInformationList";
	}
	
		/**
	 * 基础信息列表数据
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:basicInformation:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(BasicInformation basicInformation, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<BasicInformation> page = basicInformationService.findPage(new Page<BasicInformation>(request, response,-1), basicInformation);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加,基础信息表单页面
	 */
	@RequiresPermissions(value={"test:filing:basicInformation:view","test:filing:basicInformation:add","test:filing:basicInformation:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(BasicInformation basicInformation, Model model) {
		model.addAttribute("basicInformation", basicInformation);
		return "modules/filing/basicInformation/basicInformationForm";
	}

	/**
	 * 修改,基础信息表单页面
	 */
	@RequiresPermissions(value={"test:filing:basicInformation:view","test:filing:basicInformation:add","test:filing:basicInformation:edit"},logical=Logical.OR)
	@RequestMapping(value = "updateForm")
	public String updateForm(BasicInformation basicInformation, Model model) {
		model.addAttribute("basicInformation", basicInformation);
		return "modules/filing/basicInformation/updateForm";
	}

	/**
	 * 字类查看，增加，编辑基础信息表单页面
	 */
	@RequiresPermissions(value={"test:filing:basicInformation:view","test:filing:basicInformation:add","test:filing:basicInformation:edit"},logical=Logical.OR)
	@RequestMapping(value = "childForm")
	public String childForm(BasicInformation basicInformation, Model model) {
		model.addAttribute("basicInformation", basicInformation);
		return "modules/filing/basicInformation/childForm";
	}

	/**
	 * 保存基础信息
	 */
	@ResponseBody
	@RequiresPermissions(value={"test:filing:basicInformation:add","test:filing:basicInformation:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(BasicInformation basicInformation, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(basicInformation);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		Boolean aBoolean = basicInformationService.saveAll(basicInformation);//保存
		if (false == aBoolean) {
			j.setSuccess(false);
			j.setMsg("项目编码已存在");
		} else {
			j.setSuccess(true);
			j.setMsg("保存基础信息成功");
		}
		return j;
	}

	/**
	 * 保存基础信息
	 */
	@ResponseBody
	@RequiresPermissions(value={"test:filing:basicInformation:add","test:filing:basicInformation:edit"},logical=Logical.OR)
	@RequestMapping(value = "updateSave")
	public AjaxJson updateSave(BasicInformation basicInformation, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(basicInformation);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		Boolean aBoolean = basicInformationService.updateAll(basicInformation);//保存
		if (true == aBoolean) {
			j.setSuccess(false);
			j.setMsg("项目编码重复");
		} else {
			j.setSuccess(true);
			j.setMsg("保存基础信息成功");
		}
		return j;
	}

	/**
	 * 保存基础信息
	 */
	@ResponseBody
	@RequiresPermissions(value={"test:filing:basicInformation:add","test:filing:basicInformation:edit"},logical=Logical.OR)
	@RequestMapping(value = "childSave")
	public AjaxJson childSave(BasicInformationChild basicInformationChild, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(basicInformationChild);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		Boolean aBoolean = basicInformationService.updateChild(basicInformationChild);//保存
		if (true == aBoolean) {
			j.setSuccess(false);
			j.setMsg("项目编码重复");
		} else {
			j.setSuccess(true);
			j.setMsg("保存基础信息成功");
		}
		return j;
	}
	
	/**
	 * 删除基础信息
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:basicInformation:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(BasicInformation basicInformation) {
		AjaxJson j = new AjaxJson();
		basicInformationService.delete(basicInformation);
		j.setMsg("删除基础信息成功");
		return j;
	}
	
	/**
	 * 批量删除基础信息
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:basicInformation:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			basicInformationService.delete(basicInformationService.get(id));
		}
		j.setMsg("删除基础信息成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:basicInformation:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(BasicInformation basicInformation, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "基础信息"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			//查询所有父级的信息
			List<BasicInformation> list = basicInformationService.findList(basicInformation);
			List<BasicInformation> returnList = new ArrayList<>();
			//根据父级，查询所有子级的信息
			for (BasicInformation a :
					list) {
				List<BasicInformation> childList = basicInformationService.findAllChildList(a);
				returnList.add(a);
				for (BasicInformation b :
						childList) {
					returnList.add(b);
				}
			}
			new ExportExcel("基础信息", BasicInformation.class).setDataList(returnList).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出基础信息记录失败！失败信息："+e.getMessage());
		}
			return j;
    }
    
    @ResponseBody
    @RequestMapping(value = "detail")
	public Map<String, Object> detail(BasicInformationChild basicInformation, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<BasicInformationChild> page = basicInformationService.findOnePage(new Page<BasicInformationChild>(request, response), basicInformation);
		return getBootstrapData(page);
	}
	

	/**
	 * 导入Excel数据
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:basicInformation:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<BasicInformation> list = ei.getDataList(BasicInformation.class);
			List<BasicInformation> parentList = new ArrayList<>();
			List<BasicInformationChild> childRenList = new ArrayList<>();
			for (BasicInformation basicInformation : list){
				int length = basicInformation.getProjectCode().length();
				if (length == 12) {
					parentList.add(basicInformation);
				} else {
					BasicInformationChild basicInformationChild = new BasicInformationChild();
					basicInformationChild.setProjectCode(basicInformation.getProjectCode());
					basicInformationChild.setMonomerCode(basicInformation.getMonomerCode());
					basicInformationChild.setEntryName(basicInformation.getEntryName());
					childRenList.add(basicInformationChild);
				}
			}
			for (BasicInformation a :
					parentList) {
				for (BasicInformationChild b :
						childRenList) {
					if (b.getProjectCode().startsWith(a.getProjectCode())) {
						b.setParentId(a.getProjectCode());
					}
				}
			}
			if (parentList.size() > 0) {
				for (BasicInformation a :
						parentList) {
					basicInformationService.save(a);
				}
			}
			if (childRenList.size() > 0) {
				for (BasicInformationChild a :
						childRenList) {
					basicInformationService.insertChild(a);
				}
			}
			j.setMsg( "已成功导入条基础信息记录");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入基础信息失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入基础信息数据模板
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:basicInformation:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "基础信息数据导入模板.xlsx";
    		List<BasicInformation> list = Lists.newArrayList(); 
    		new ExportExcel("基础信息数据", BasicInformation.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }
	

}