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

import java.util.List;

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

import com.google.common.base.Strings;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
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.*;
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.worksupplier.entity.WorkSupplier;
import com.jeeplus.modules.worksupplier.service.WorkSupplierService;

/**
 * 供应商管理Controller
 * @author 供应商管理
 * @version 2018-07-10
 */
@Controller
@RequestMapping(value = "${adminPath}/worksupplier/workSupplier")
public class WorkSupplierController extends BaseController {

	@Autowired
	private WorkSupplierService workSupplierService;
	@Autowired
	private HttpServletRequest request;
	@ModelAttribute
	public WorkSupplier get(@RequestParam(required=false) String id) {
		WorkSupplier entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workSupplierService.get(id);
		}
		if (entity == null){
			entity = new WorkSupplier();
		}
		return entity;
	}
	
	/**
	 * 列表页面
	 */
	@RequiresPermissions("worksupplier:workSupplier:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkSupplier workSupplier, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkSupplier> page = workSupplierService.findPage(new Page<WorkSupplier>(request, response), workSupplier);
		model.addAttribute("page", page);
		return "modules/worksupplier/workSupplierList";
	}

	/**
	 * 查看，增加，编辑表单页面
	 */
	//@RequiresPermissions(value={"worksupplier:workSupplier:view","worksupplier:workSupplier:add","worksupplier:workSupplier:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkSupplier workSupplier, Model model) {
		String view = "workSupplierForm";
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workSupplierView";
		}
		if(StringUtils.isBlank(workSupplier.getRemoveSign())){
			workSupplier.setRemoveSign("1");
		}
		if(StringUtils.isBlank(workSupplier.getId())){
			model.addAttribute("workSupplier", workSupplier);
			return "modules/worksupplier/workSupplierForms";
		}
		model.addAttribute("workSupplier", workSupplier);
		return "modules/worksupplier/"+view;
	}

	/**
	 * 保存
	 */
	@RequiresPermissions(value={"worksupplier:workSupplier:add","worksupplier:workSupplier:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkSupplier workSupplier, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workSupplier)){
			return form(workSupplier, model);
		}
		User user = workSupplier.getCreateBy();
		String submitter = "";
		if(user != null){
			submitter = user.getId();
		}
		if(!UserUtils.getUser().getId().equals(submitter) && !Strings.isNullOrEmpty(submitter)){
			addMessage(redirectAttributes, "您不是创建人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/worksupplier/workSupplier/?repage";
		}
		if(!workSupplier.getIsNewRecord()){//编辑表单保存
			WorkSupplier t = workSupplierService.get(workSupplier.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workSupplier, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workSupplierService.save(t);//保存
		}else{//新增表单保存
			workSupplier.setCompanyId(UserUtils.getSelectOffice().getParentId());
			workSupplier.setOfficeId(UserUtils.getSelectOffice().getId());
			workSupplierService.save(workSupplier);//保存
		}
		addMessage(redirectAttributes, "保存成功");
		return "redirect:"+Global.getAdminPath()+"/worksupplier/workSupplier/?repage";
	}
	
	/**
	 * 删除
	 */
	@RequiresPermissions("worksupplier:workSupplier:del")
	@RequestMapping(value = "delete")
	public String delete(WorkSupplier workSupplier, RedirectAttributes redirectAttributes) {
		workSupplierService.delete(workSupplier);
		addMessage(redirectAttributes, "删除成功");
		return "redirect:"+Global.getAdminPath()+"/worksupplier/workSupplier/?repage";
	}
	@RequiresPermissions("worksupplier:workSupplier:edit")
	@RequestMapping(value = "remove")
	public String remove(WorkSupplier workSupplier, RedirectAttributes redirectAttributes) {
		workSupplier.setRemoveSign("2");
		workSupplierService.updateSign(workSupplier);
		addMessage(redirectAttributes, "移除成功");
		return "redirect:"+Global.getAdminPath()+"/worksupplier/workSupplier/?repage";
	}
	@RequiresPermissions("worksupplier:workSupplier:edit")
	@RequestMapping(value = "live")
	public String live(WorkSupplier workSupplier, RedirectAttributes redirectAttributes) {
		workSupplier.setRemoveSign("1");
		workSupplierService.updateSign(workSupplier);
		addMessage(redirectAttributes, "恢复成功");
		return "redirect:"+Global.getAdminPath()+"/worksupplier/workSupplier/?repage";
	}
	
	/**
	 * 批量删除
	 */
	@RequiresPermissions("worksupplier:workSupplier:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workSupplierService.delete(workSupplierService.get(id));
		}
		addMessage(redirectAttributes, "删除成功");
		return "redirect:"+Global.getAdminPath()+"/worksupplier/workSupplier/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("worksupplier:workSupplier:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkSupplier workSupplier, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = ""+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkSupplier> page = workSupplierService.findPage(new Page<WorkSupplier>(request, response, -1), workSupplier);
    		new ExportExcel("", WorkSupplier.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/worksupplier/workSupplier/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("worksupplier:workSupplier: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<WorkSupplier> list = ei.getDataList(WorkSupplier.class);
			for (WorkSupplier workSupplier : list){
				try{
					workSupplierService.save(workSupplier);
					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()+"/worksupplier/workSupplier/?repage";
    }
	
	/**
	 * 下载导入数据模板
	 */
	@RequiresPermissions("worksupplier:workSupplier:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "数据导入模板.xlsx";
    		List<WorkSupplier> list = Lists.newArrayList(); 
    		new ExportExcel("供应商管理数据", WorkSupplier.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/worksupplier/workSupplier/?repage";
    }
	@ResponseBody
	@RequestMapping(value = "validateUscCode")
	public boolean validateMobileExist(String uscCode, HttpServletResponse response, Model model) {
		WorkSupplier workSupplier =  workSupplierService.findUniqueByProperty("usc_code", uscCode);
		String id = request.getParameter("ids");
		if(workSupplier != null){
			if(StringUtils.isNotBlank(id)){
				if(!id.equals(workSupplier.getId())){
					return false;
				}else{
					return true;
				}
			}
			return false;
		}else{
			return true;
		}
	}
	
	

}