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

import java.util.List;
import java.util.Map;
import java.util.Objects;

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

import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.warehouse.goods.entity.GoodsInfo;
import com.jeeplus.modules.warehouse.profitwarehousing.entity.ProfitWarehousingInfo;
import com.jeeplus.modules.warehouse.profitwarehousing.mapper.ProfitWarehousingInfoMapper;
import com.jeeplus.modules.warehouse.qrcode.entity.QrCode;
import com.jeeplus.modules.warehouse.qrcode.service.QrCodeService;
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.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.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.warehouse.profitwarehousing.entity.ProfitWarehousing;
import com.jeeplus.modules.warehouse.profitwarehousing.service.ProfitWarehousingService;

/**
 * 盘盈入库单Controller
 * @author zhanglt
 * @version 2023-02-14
 */
@Controller
@RequestMapping(value = "${adminPath}/warehouse/profitwarehousing/profitWarehousing")
public class ProfitWarehousingController extends BaseController {

	@Autowired
	private ProfitWarehousingService profitWarehousingService;
	@Autowired
	private ProfitWarehousingInfoMapper profitWarehousingInfoMapper;
	@Autowired
	private QrCodeService qrCodeService;

	
	@ModelAttribute
	public ProfitWarehousing get(@RequestParam(required=false) String id) {
		ProfitWarehousing entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = profitWarehousingService.get(id);
		}
		if (entity == null){
			entity = new ProfitWarehousing();
		}
		return entity;
	}
	
	/**
	 * 盘盈入库单列表页面
	 */
	@RequiresPermissions("warehouse:profitwarehousing:profitWarehousing:list")
	@RequestMapping(value = {"list", ""})
	public String list(ProfitWarehousing profitWarehousing, Model model) {
		model.addAttribute("profitWarehousing", profitWarehousing);
		return "modules/warehouse/profitwarehousing/profitWarehousingList";
	}
	
		/**
	 * 盘盈入库单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("warehouse:profitwarehousing:profitWarehousing:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(ProfitWarehousing profitWarehousing, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ProfitWarehousing> page = profitWarehousingService.findPage(new Page<ProfitWarehousing>(request, response), profitWarehousing); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑盘盈入库单表单页面
	 */
	@RequiresPermissions(value={"warehouse:profitwarehousing:profitWarehousing:view","warehouse:profitwarehousing:profitWarehousing:add","warehouse:profitwarehousing:profitWarehousing:edit"},logical=Logical.OR)
	@RequestMapping(value = "form/{mode}")
	public String form(@PathVariable String mode, ProfitWarehousing profitWarehousing, Model model) {
		if(mode !=null && Objects.equals(mode, "add")){
			if(profitWarehousing.getNumber()==null|| Objects.equals(profitWarehousing.getNumber(), "")){
				profitWarehousing.setNumber(profitWarehousingService.createPYDH());
			}
			if(profitWarehousing.getOperator() == null){
				profitWarehousing.setOperator(UserUtils.getUser());
			}
		}

		model.addAttribute("profitWarehousing", profitWarehousing);
		model.addAttribute("mode", mode);
		return "modules/warehouse/profitwarehousing/profitWarehousingForm";
	}

	/**
	 * 保存盘盈入库单
	 */
	@ResponseBody
	@RequiresPermissions(value={"warehouse:profitwarehousing:profitWarehousing:add","warehouse:profitwarehousing:profitWarehousing:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(ProfitWarehousing profitWarehousing, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(profitWarehousing);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		profitWarehousingService.save(profitWarehousing);//保存
		j.setSuccess(true);
		j.setMsg("保存盘盈入库单成功");
		return j;
	}
	
	/**
	 * 删除盘盈入库单
	 */
	@ResponseBody
	@RequiresPermissions("warehouse:profitwarehousing:profitWarehousing:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(ProfitWarehousing profitWarehousing) {
		AjaxJson j = new AjaxJson();
		profitWarehousingService.delete(profitWarehousing);
		j.setMsg("删除盘盈入库单成功");
		return j;
	}
	
	/**
	 * 批量删除盘盈入库单
	 */
	@ResponseBody
	@RequiresPermissions("warehouse:profitwarehousing:profitWarehousing:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			profitWarehousingService.delete(profitWarehousingService.get(id));
		}
		j.setMsg("删除盘盈入库单成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("warehouse:profitwarehousing:profitWarehousing:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(ProfitWarehousing profitWarehousing, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "盘盈入库单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<ProfitWarehousing> page = profitWarehousingService.findPage(new Page<ProfitWarehousing>(request, response, -1), profitWarehousing);
    		new ExportExcel("盘盈入库单", ProfitWarehousing.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;
    }
    
    @ResponseBody
    @RequestMapping(value = "detail")
	public ProfitWarehousing detail(String id) {
		return profitWarehousingService.get(id);
	}
	

	/**
	 * 导入Excel数据

	 */
	@ResponseBody
	@RequiresPermissions("warehouse:profitwarehousing:profitWarehousing:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<ProfitWarehousing> list = ei.getDataList(ProfitWarehousing.class);
			for (ProfitWarehousing profitWarehousing : list){
				try{
					profitWarehousingService.save(profitWarehousing);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条盘盈入库单记录。");
			}
			j.setMsg( "已成功导入 "+successNum+" 条盘盈入库单记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入盘盈入库单失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入盘盈入库单数据模板
	 */
	@ResponseBody
	@RequiresPermissions("warehouse:profitwarehousing:profitWarehousing:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "盘盈入库单数据导入模板.xlsx";
    		List<ProfitWarehousing> list = Lists.newArrayList(); 
    		new ExportExcel("盘盈入库单数据", ProfitWarehousing.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }
	/**
	 * 打印二维码
	 */
	@ResponseBody
	@RequestMapping(value = "printQr")
	public AjaxJson printQr(String profitWarehousingInfoId) throws Exception{
		AjaxJson j = new AjaxJson();
		//查询该明细，是否已经生成二维码记录
		ProfitWarehousingInfo profitWarehousingInfo1 = profitWarehousingInfoMapper.get(profitWarehousingInfoId);
		if(profitWarehousingInfo1.getQrCode() != null){
			j.setSuccess(false);
			j.setMsg("二维码已存在");
			return j;
		}
		ProfitWarehousingInfo profitWarehousingInfo = profitWarehousingService.printQr(profitWarehousingInfoId);//保存
		j.put("profitWarehousingInfo", profitWarehousingInfo);
		j.setSuccess(true);
		j.setMsg("生成二维码成功");
		return j;
	}

	/**
	 * 清除二维码
	 * @param goodsInfoId
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "cleanQr")
	public AjaxJson cleanQr(String profitWarehousingInfoId) throws Exception{
		AjaxJson j = new AjaxJson();
		//新增或编辑表单保存
		ProfitWarehousingInfo profitWarehousingInfo1 = profitWarehousingInfoMapper.get(profitWarehousingInfoId);
		if(profitWarehousingInfo1.getQrCode() == null){
			j.setSuccess(false);
			j.setMsg("二维码不存在");
			return j;
		}
		if(Objects.equals(profitWarehousingInfo1.getQrCode().getState(), "0")){
			profitWarehousingService.cleanQr(profitWarehousingInfoId);//保存
		}else {
			j.setSuccess(false);
			j.setMsg("该物资已入账不能清除二维码");
			return j;
		}

		j.setSuccess(true);
		j.setMsg("清除二维码成功");
		return j;
	}
	/**
	 * 盘盈入库明细，入台账
	 */
	@ResponseBody
	@RequiresPermissions(value={"warehouse:profitwarehousing:profitWarehousing:add","warehouse:profitwarehousing:profitWarehousing:edit"},logical=Logical.OR)
	@RequestMapping(value = "inLedgerInfo")
	public AjaxJson inLedgerInfo(String profitWarehousingInfoId, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(profitWarehousingInfoId);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		ProfitWarehousingInfo profitWarehousingInfo = profitWarehousingInfoMapper.get(profitWarehousingInfoId);
		if(profitWarehousingInfo.getQrCode() == null){
			j.setSuccess(false);
			j.setMsg("请先生成二维码");
		}
		if(profitWarehousingInfo.getQrCode() != null){
			QrCode qrCode = qrCodeService.get(profitWarehousingInfo.getQrCode().getId());
			//刚生成未入库
			if(Objects.equals(qrCode.getState(), "0")){
				profitWarehousingService.inLedgerInfo(profitWarehousingInfo);//保存
			}
		}
		j.setSuccess(true);
		j.setMsg("物资入帐成功");
		return j;
	}

}