/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.casematerials.web;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.caseinfo.entity.CaseInfo;
import com.jeeplus.modules.caseinfo.service.CaseInfoService;
import com.jeeplus.modules.sys.service.AreaService;
import com.jeeplus.modules.workreimbursement.utils.VarStr;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.casematerials.entity.CaseMaterials;
import com.jeeplus.modules.casematerials.service.CaseMaterialsService;

/**
 * 案例-材料Controller
 * @author fgy
 * @version 2018-01-24
 */
@Controller
@RequestMapping(value = "${adminPath}/casematerials/caseMaterials")
public class CaseMaterialsController extends BaseController {

	@Autowired
	private CaseMaterialsService caseMaterialsService;
	@Autowired
	private AreaService areaService;
	@Autowired
	private CaseInfoService caseInfoService;
	@Autowired
	private HttpServletRequest request;

	
	@ModelAttribute
	public CaseMaterials get(@RequestParam(required=false) String id) {
		CaseMaterials entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = caseMaterialsService.get(id);
		}
		if (entity == null){
			entity = new CaseMaterials();
		}
		return entity;
	}
	
	/**
	 * 案例-材料列表页面
	 */
	@RequiresPermissions("casematerials:caseMaterials:list")
	@RequestMapping(value = {"list", ""})
	public String list(CaseMaterials caseMaterials, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<CaseMaterials> page = caseMaterialsService.findPage(new Page<CaseMaterials>(request, response), caseMaterials); 
		model.addAttribute("page", page);
		return "modules/casematerials/caseMaterialsList";
	}

	/**
	 * 查看，增加，编辑案例-材料表单页面
	 */
	/*@RequiresPermissions(value={"casematerials:caseMaterials:view","casematerials:caseMaterials:add","casematerials:caseMaterials:edit"},logical=Logical.OR)*/
	@RequestMapping(value = "form")
	public String form(CaseMaterials caseMaterials, Model model) {
		String tabId = request.getParameter("tabId");
		model.addAttribute("caseMaterials", caseMaterials);
		if("1".equals(tabId)){
			return "modules/caseinfo/caseMaterialsFormBillDetail";
		}
		return "modules/casematerials/caseMaterialsForm";
	}

	/**
	 * 保存案例-材料
	 */
	@RequiresPermissions(value={"casematerials:caseMaterials:add","casematerials:caseMaterials:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(CaseMaterials caseMaterials, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, caseMaterials)){
			return form(caseMaterials, model);
		}
		if(!caseMaterials.getIsNewRecord()){//编辑表单保存
			CaseMaterials t = caseMaterialsService.get(caseMaterials.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(caseMaterials, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			caseMaterialsService.save(t);//保存
		}else{//新增表单保存
			caseMaterialsService.save(caseMaterials);//保存
		}
		addMessage(redirectAttributes, "保存案例-材料成功");
		return "redirect:"+Global.getAdminPath()+"/casematerials/caseMaterials/?repage";
	}
	
	/**
	 * 删除案例-材料
	 */
	/*@RequiresPermissions("casematerials:caseMaterials:del")*/
	@RequestMapping(value = "delete")
	public String delete(CaseMaterials caseMaterials, RedirectAttributes redirectAttributes) {
		CaseInfo caseInfo = caseInfoService.get(caseMaterials.getCaseId());

		String sta = caseInfo.getStatus();
		/*if(!VarStr.status[0].equals(sta)){
			if(VarStr.status[4].equals(sta)){
				addMessage(redirectAttributes, "报销单已报销，无法删除");
				return "redirect:"+adminPath+"/workreimbursement/workReimbursement/form?id="+workAccount.getWorkReimbursement().getId();
			}else{
				addMessage(redirectAttributes, "报销单正在审核中，无法删除");
				return "redirect:"+adminPath+"/workreimbursement/workReimbursement/form?id="+workAccount.getWorkReimbursement().getId();
			}
		}*/
		caseMaterialsService.delete(caseMaterials);
		addMessage(redirectAttributes, "删除案例-材料成功");
		return "redirect:"+adminPath+"/caseinfo/caseInfo/form?id="+caseMaterials.getCaseId();
	}
	/**
	 * 批量删除案例-材料
	 */
	@RequiresPermissions("casematerials:caseMaterials:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			caseMaterialsService.delete(caseMaterialsService.get(id));
		}
		addMessage(redirectAttributes, "删除案例-材料成功");
		return "redirect:"+Global.getAdminPath()+"/casematerials/caseMaterials/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("casematerials:caseMaterials:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(CaseMaterials caseMaterials, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "案例-材料"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<CaseMaterials> page = caseMaterialsService.findPage(new Page<CaseMaterials>(request, response, -1), caseMaterials);
    		new ExportExcel("案例-材料", CaseMaterials.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出案例-材料记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/casematerials/caseMaterials/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("casematerials:caseMaterials:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<CaseMaterials> list = ei.getDataList(CaseMaterials.class);
			for (CaseMaterials caseMaterials : list){
				try{
					caseMaterialsService.save(caseMaterials);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条案例-材料记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条案例-材料记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入案例-材料失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/casematerials/caseMaterials/?repage";
    }
	
	/**
	 * 下载导入案例-材料数据模板
	 */
	@RequiresPermissions("casematerials:caseMaterials:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "案例-材料数据导入模板.xlsx";
    		List<CaseMaterials> list = Lists.newArrayList(); 
    		new ExportExcel("案例-材料数据", CaseMaterials.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/casematerials/caseMaterials/?repage";
    }

	/**
	 * 材料价格列表页面
	 */
	@RequestMapping("/addBill")
	public String addBill(CaseMaterials caseMaterials, RedirectAttributes redirectAttributes,Model model, HttpServletRequest request) {
		SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
		SimpleDateFormat sdf2= new SimpleDateFormat("yyyy-MM-dd");
//		String wid = request.getParameter("wid");
//		if(!StringUtils.isNotBlank(wid)){
//			addMessage(redirectAttributes, "请先保存报销信息，否则无法添加报销单信息");
//			return "modules/workreimbursement/workReimbursementFormBill";
//		}
//		WorkReimbursement workReimbursement = workReimbursementService.get(wid);
		String name = request.getParameter("name");
		String flag = request.getParameter("flag");
		String specification = request.getParameter("specification");
		String calculateUnit = request.getParameter("calculateUnit");
		String taxPrice = request.getParameter("taxPrice");
		String price = request.getParameter("price");
		String ud = request.getParameter("useDate");
		String source = request.getParameter("source");
		String tax = request.getParameter("tax");
		String material = request.getParameter("material");
		String brand = request.getParameter("brand");
		String pp = request.getParameter("pp");
		String areaId = request.getParameter("areaId");
		if(StringUtils.isNotBlank(name)&&StringUtils.isNotBlank(flag)&&StringUtils.isNotBlank(flag)&&StringUtils.isNotBlank(specification)
				&&StringUtils.isNotBlank(calculateUnit)&&StringUtils.isNotBlank(taxPrice)&&StringUtils.isNotBlank(price)&&StringUtils.isNotBlank(ud)
				&&StringUtils.isNotBlank(source)&&StringUtils.isNotBlank(tax)&&StringUtils.isNotBlank(material)&&StringUtils.isNotBlank(brand)
				&&StringUtils.isNotBlank(source)&&StringUtils.isNotBlank(tax)
				){
			try {
				name = URLDecoder.decode(name, "UTF-8");
				flag = URLDecoder.decode(flag, "UTF-8");
				specification = URLDecoder.decode(specification, "UTF-8");
				calculateUnit = URLDecoder.decode(calculateUnit, "UTF-8");
				taxPrice = URLDecoder.decode(taxPrice, "UTF-8");
				price = URLDecoder.decode(price, "UTF-8");
				ud = URLDecoder.decode(ud, "UTF-8");
				source = URLDecoder.decode(source, "UTF-8");
				tax = URLDecoder.decode(tax, "UTF-8");
				material = URLDecoder.decode(material, "UTF-8");
				brand = URLDecoder.decode(brand, "UTF-8");
				pp = URLDecoder.decode(pp, "UTF-8");
				areaId = URLDecoder.decode(areaId, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		if(StringUtils.isNotBlank(areaId)){
			caseMaterials.setArea(areaService.get(areaId));
		}
		if(StringUtils.isNotBlank(flag)){
			caseMaterials.setId(flag);
		}else{
			caseMaterials.setId("flag");
		}
		caseMaterials.setIndex(request.getParameter("index"));
		caseMaterials.setName(name);
		caseMaterials.setSpecification(specification);
		caseMaterials.setCalculateUnit(calculateUnit);
		caseMaterials.setTaxPrice(taxPrice);
		caseMaterials.setPrice(price);
		Date useDate = null;
		if(StringUtils.isNotBlank(ud)){
			try {
				useDate = sdf.parse(ud);
			} catch (ParseException e) {
				e.printStackTrace();
				if(useDate == null){
					try{
					useDate = sdf2.parse(ud);}
					catch (ParseException e1){
						e1.printStackTrace();
					}
				}
			}
		}
		caseMaterials.setUseDate(useDate);
		caseMaterials.setSource(source);
		caseMaterials.setTax(tax);
		caseMaterials.setMaterial(material);
		caseMaterials.setBrand(brand);
		caseMaterials.setPp(pp);
		model.addAttribute("caseMaterials",caseMaterials);
		return "modules/caseinfo/caseMaterialsFormBill";
	}
	

}