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

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.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sg.audit.information.entity.Information;
import com.jeeplus.modules.sg.audit.information.service.InformationService;
import com.jeeplus.modules.sg.financial.erpcredit.entity.*;
import com.jeeplus.modules.sg.financial.erpcredit.service.ErpCreditService;
import com.jeeplus.modules.sg.financial.erpcredit.util.*;
import com.jeeplus.modules.sg.financial.settlement.entity.MaintainData;
import com.jeeplus.modules.sg.financial.settlement.service.DataMaintenanceService;
import com.jeeplus.modules.sg.managementcenter.project.entity.Project;
import com.jeeplus.modules.test.one.dialog.entity.Leave1;
import groovy.util.IFileNameFinder;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.omg.PortableServer.LIFESPAN_POLICY_ID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
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.servlet.http.HttpSession;
import javax.validation.ConstraintViolationException;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据维护
 */
@Controller
@RequestMapping(value = "${adminPath}/sg/financial/erpCredit")
public class ErpCreditController extends BaseController {

	@Autowired
	private ErpCreditService erpCreditService;
	@Autowired
	private DataMaintenanceService dataMaintenanceService;

	@ModelAttribute
	public ErpCredit get(@RequestParam(required=false) String id) {
		ErpCredit entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = erpCreditService.get(id);
		}
		if (entity == null){
			entity = new ErpCredit();
		}
		return entity;
	}
	/**
	 * 表单列表页面
	 */
	@RequiresPermissions("sg:financial:erpCredit:list")
	@RequestMapping(value = {"list", ""})
	public String list(ErpCredit erpCredit, Model model) {
		model.addAttribute("erpCredit", erpCredit);
		return "modules/sg/financial/erp/erpCreditList";
	}

	/**
	 * 表单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("sg:financial:erpCredit:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(ErpCredit erpCredit, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception{
		HttpSession session = request.getSession();
		String attribute = (String) session.getAttribute("erpStatus");
		Page<ErpCredit> page = null;
		if (attribute!=null){
			erpCredit.setStatus(attribute);
			page = erpCreditService.findPage(new Page<ErpCredit>(request, response), erpCredit);
		}else {
//			erpCredit.setId("123456");
//			erpCredit.setStatus("0");
			page = erpCreditService.findPage(new Page<ErpCredit>(request, response), erpCredit);
		}
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑表单表单页面
	 */
	@RequiresPermissions(value={"sg:financial:erpCredit:view","sg:financial:erpCredit:add","sg:financial:erpCredit:edit"},logical= Logical.OR)
	@RequestMapping(value = "form")
	public String form(ErpCredit erpCredit, Model model) {
		model.addAttribute("erpCredit", erpCredit);
		return "modules/sg/financial/erp/erpCreditForm";
	}
	/*
		提示
	 */
	@RequestMapping(value = "tips")
	public String Tips(String str,Model model, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		str = URLDecoder.decode(str,"UTF-8");
		String[] strings2;
		List<ErpJudge> erpJudges = new ArrayList<ErpJudge>();
		ErpJudge erpJudge = null;
		if (str.contains("-")){
			String[] strings =  str.split("-");
			for (String str1 :strings){
				strings2 = str1.split(",");
				erpJudge = new ErpJudge();
				erpJudge.setItemId(strings2[0]);
				erpJudge.setMainFlag(strings2[1]);
				erpJudge.setMainStartDate(strings2[2]);
				erpJudge.setMainEndDate(strings2[3]);
				erpJudge.setMainApprovalNumber(strings2[4]);
				erpJudge.setMainDesign(strings2[5]);
				erpJudge.setMainSupervision(strings2[6]);
				erpJudge.setMainConstructionUnits(strings2[7]);
				erpJudge.setMainDesignUnits(strings2[8]);
				erpJudge.setMainInvestmen(strings2[9]);
				erpJudge.setInfoFlag(strings2[10]);
				erpJudges.add(erpJudge);
			}
		}else {
			String[] strings3 = str.split(",");
			erpJudge = new ErpJudge();
			erpJudge.setItemId(strings3[0]);
			erpJudge.setMainFlag(strings3[1]);
			erpJudge.setMainStartDate(strings3[2]);
			erpJudge.setMainEndDate(strings3[3]);
			erpJudge.setMainApprovalNumber(strings3[4]);
			erpJudge.setMainDesign(strings3[5]);
			erpJudge.setMainSupervision(strings3[6]);
			erpJudge.setMainConstructionUnits(strings3[7]);
			erpJudge.setMainDesignUnits(strings3[8]);
			erpJudge.setMainInvestmen(strings3[9]);
			erpJudge.setInfoFlag(strings3[10]);
			erpJudges.add(erpJudge);
		}
		model.addAttribute("erpList",erpJudges);
		return "modules/sg/financial/erp/erpCreditTips";
	}
	/**
	 * 保存表单
	 */
	@ResponseBody
	@RequiresPermissions(value={"sg:financial:erpCredit:add","sg:financial:erpcredit:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(ErpCredit erpCredit, Model model,HttpServletRequest request, HttpServletResponse response) throws Exception{
		HttpSession session = request.getSession();
		String random = "";
		random = (String) session.getAttribute("erpStatus");
		if (random==null){
			random = ErpInfo.getStatus();
			request.getSession().setAttribute("erpStatus",random);
		}
		erpCredit.setStatus(random);
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(erpCredit);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		erpCreditService.save(erpCredit);//保存
		j.setSuccess(true);
		j.setMsg("保存表单成功");
		return j;
	}

	/**
	 * 删除表单
	 */
	@ResponseBody
	@RequiresPermissions("sg:financial:erpCredit:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(ErpCredit erpCredit) {
		AjaxJson j = new AjaxJson();
		erpCreditService.delete(erpCredit);
		j.setMsg("删除表单成功");
		return j;
	}

	/**
	 * 批量表单
	 */
	@ResponseBody
	@RequiresPermissions("sg:financial:erpCredit:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			erpCreditService.delete(erpCreditService.get(id));
		}
		j.setMsg("删除表单成功");
		return j;
	}

    /**
     * 导出excel列表文件
     */
    @ResponseBody
	@RequiresPermissions("sg:financial:erpCredit:export")
    @RequestMapping(value = "exportList")
    public Result exportFileList(ErpCredit erpCredit,HttpServletRequest request, HttpServletResponse response){
		HttpSession session = request.getSession();
		String attribute = (String) session.getAttribute("erpStatus");
		erpCredit.setStatus(attribute);
        Result j = new Result();
        try {
            String fileName = "送审决算信息"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<ErpCredit> page = erpCreditService.findPage(new Page<ErpCredit>(request, response, -1), erpCredit);
            new ExportExcel("送审决算信息", ErpCredit.class).setDataList(page.getList()).write(response, fileName).dispose();

            j.setSuccess(true);
            j.setMsg("导出成功！");
        }catch (Exception e){
            j.setSuccess(false);
            j.setMsg("导出失败！失败信息："+e.getMessage());
        }
        return j;
    }
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("sg:financial:erpCredit:export")
	@RequestMapping(value = "export")
	public Result exportFile(String ids,HttpServletRequest request, HttpServletResponse response){
		Result j = new Result();
		try {
			HttpSession session = request.getSession();
			String attribute = (String) session.getAttribute("erpStatus");
			erpCreditService.getExport(ids,response,attribute);
			j.setSuccess(true);
			j.setMsg("导出成功！");
		}catch (Exception e){
			j.setSuccess(false);
			j.setMsg("导出失败！失败信息："+e.getMessage());
		}
		return j;
	}
	@ResponseBody
	@RequestMapping(value = "detail")
	public ErpCredit detail(String id) {
		return erpCreditService.get(id);
	}
	/**
	 * 导入Excel数据
	 */
	@ResponseBody
	@RequiresPermissions("sg:financial:erpCredit:import")
	@RequestMapping(value = "import")
	public Result importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request,Model model) throws IOException, InvalidFormatException {
		Result j = new Result();
		String str = "";
//		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportUtil importUtil = new ImportUtil(file, 0, 0);
            Boolean erpJugde = ErpInfo.getErpJugde(importUtil);
            if (erpJugde){
                j.setSuccess(false);
                j.setMsg("导入失败！失败信息："+"表不符合规范");
                return j;
            }
			List<ErpAccount> erpAccounts = ErpInfo.getErpAccount(importUtil);//获取表格数据
			List<ErpCredit> erpCredits = ErpInfo.getAllErpCreditList(erpAccounts);//获取单条数据
			//验证方法
			List<ErpJudge> erpJudges  = erpCreditService.getAllCheck(erpCredits);
			if (null!=erpJudges&&erpJudges.size()>0){
				String judge = "";
				for (ErpJudge erpJudge:erpJudges){
					judge += erpJudge.getItemId()+","+erpJudge.getMainFlag()+","+
							erpJudge.getMainStartDate()+","+erpJudge.getMainEndDate()+","+
							erpJudge.getMainApprovalNumber()+","+erpJudge.getMainDesign()+"," +
							erpJudge.getMainSupervision()+","+erpJudge.getMainConstructionUnits()+","+
							erpJudge.getMainDesignUnits()+","+erpJudge.getMainInvestmen()+","+erpJudge.getInfoFlag()+"-";
				}
				judge = judge.substring(0,judge.length()-1);
//				j.setErpList(erpJudges);
				j.setList(judge);
				j.setFlag(true);
				j.setSuccess(false);
				return j;
			}
			for (ErpCredit erpCredit:erpCredits){
				str+=erpCredit.getItemId()+",";
			}
			str = str.substring(0,str.length()-1);
			String random = random = ErpInfo.getStatus();//保存session
			request.getSession().setAttribute("erpStatus",random);;
			for (ErpCredit erpCredit : erpCredits){
				try{
					erpCreditService.save(erpCredit,random);
					successNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条送审决算记录。");
			}
			j.setMsg( "已成功导入 "+successNum+" 条送审决算记录"+failureMsg);
			j.setList(str);
//		} catch (Exception e) {
//			j.setSuccess(false);
//			j.setMsg("导入送审决算失败！失败信息："+e.getMessage());
//		}
		return j;
	}
}