/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sg.financial.settlement.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.BasicInformationChild;
import com.jeeplus.modules.sg.financial.settlement.entity.Corresponding;
import com.jeeplus.modules.sg.financial.settlement.service.CorrespondingService;
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.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 物料对应配置Controller
 * @author user3
 * @version 2021-04-22
 */
@Controller
@RequestMapping(value = "${adminPath}/finance/corresponding")
public class CorrespondingController extends BaseController {

	@Autowired
	private CorrespondingService correspondingService;
	
	@ModelAttribute
	public Corresponding get(@RequestParam(required=false) String id) {
		Corresponding entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = correspondingService.get(id);
		}
		if (entity == null){
			entity = new Corresponding();
		}
		return entity;
	}
	
	/**
	 * 物料对应配置列表页面
	 */
	@RequiresPermissions("test:settlement:corresponding:list")
	@RequestMapping(value = {"list", ""})
	public String list(Corresponding corresponding, Model model) {
		model.addAttribute("corresponding", corresponding);
		return "modules/sg/financial/settlement/correspondingList";
	}
	
		/**
	 * 物料对应配置列表数据
	 */
	@ResponseBody
	@RequiresPermissions("test:settlement:corresponding:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Corresponding corresponding, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Corresponding> page = correspondingService.findPage(new Page<Corresponding>(request, response), corresponding); 
		return getBootstrapData(page);
	}

	@ResponseBody
	@RequestMapping(value = "detail")
	public Map<String, Object> detail(Corresponding corresponding, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Corresponding> page = correspondingService.findChildPage(new Page<Corresponding>(request, response), corresponding);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑物料对应配置表单页面
	 */
	@RequiresPermissions(value={"test:settlement:corresponding:view","test:settlement:corresponding:add","test:settlement:corresponding:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Corresponding corresponding, Model model) {
		model.addAttribute("corresponding", corresponding);
		return "modules/sg/financial/settlement/correspondingForm";
	}

	/**
	 * 保存物料对应配置
	 */
	@ResponseBody
	@RequiresPermissions(value={"test:settlement:corresponding:add","test:settlement:corresponding:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Corresponding corresponding, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		List<Corresponding> childList = corresponding.getChildList();
		if (null == childList || childList.size() <= 0) {
			j.setSuccess(false);
			j.setMsg("物料信息不能为空");
			return j;
		}
		String errMsg = beanValidator(corresponding);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		correspondingService.save(corresponding);//保存
		j.setSuccess(true);
		j.setMsg("保存物料对应配置成功");
		return j;
	}
	
	/**
	 * 删除物料对应配置
	 */
	@ResponseBody
	@RequiresPermissions("test:settlement:corresponding:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Corresponding corresponding) {
		AjaxJson j = new AjaxJson();
		correspondingService.delete(corresponding);
		j.setMsg("删除物料对应配置成功");
		return j;
	}
	
	/**
	 * 批量删除物料对应配置
	 */
	@ResponseBody
	@RequiresPermissions("test:settlement:corresponding:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			correspondingService.delete(correspondingService.get(id));
		}
		j.setMsg("删除物料对应配置成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("test:settlement:corresponding:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(Corresponding corresponding, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "物料对应配置"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Corresponding> page = correspondingService.findChildPage(new Page<Corresponding>(request, response, -1), corresponding);
    		new ExportExcel("物料对应配置", Corresponding.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出物料对应配置记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据
	 */
	@ResponseBody
	@RequiresPermissions("test:settlement:corresponding:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Corresponding> list = ei.getDataList(Corresponding.class);
			Map<String, List<Corresponding>> collect = list.stream().collect(Collectors.groupingBy(Corresponding::getSerialNumber));
			List<Corresponding> insertList = new ArrayList<>();
			for (String key : collect.keySet()) {
				Corresponding corresponding = new Corresponding();
				corresponding.setSerialNumber(key);
				insertList.add(corresponding);
			}
			for (Corresponding c :
					insertList) {
				Corresponding aNull = correspondingService.isNull(c);
				if (null == aNull) {
					correspondingService.insert(c);
				}
				correspondingService.deleteAllChild(c);
			}
			for (Corresponding corresponding : list){
				correspondingService.insertChild(corresponding);
			}
			j.setMsg( "已成功导入物料对应配置记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入物料对应配置失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入物料对应配置数据模板
	 */
	@ResponseBody
	@RequiresPermissions("test:settlement:corresponding:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "物料对应配置导入模板.xlsx";
    		List<Corresponding> list = Lists.newArrayList(); 
    		new ExportExcel("物料对应配置", Corresponding.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }

}