/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sg.annualmaterialreport.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.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sg.annualmaterialreport.entity.NewMaterialReport;
import com.jeeplus.modules.sg.annualmaterialreport.entity.ReportDetails;
import com.jeeplus.modules.sg.annualmaterialreport.service.NewMaterialReportService;
import com.jeeplus.modules.sg.annualmaterialreport.service.ReportDetailsService;
import com.jeeplus.modules.sg.managementcenter.materialinfo.entity.MaterialInfo;
import com.jeeplus.modules.sg.managementcenter.materialinfo.entity.MaterialInfoBean;
import com.jeeplus.modules.sg.managementcenter.materialinfo.service.MaterialInfoService;
import com.jeeplus.modules.sg.managementcenter.materialproject.entity.MaterialProject;
import com.jeeplus.modules.sg.managementcenter.materialproject.service.MaterialProjectService;
import org.apache.poi.ss.usermodel.Row;
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.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 新年度物资上报明细controller
 *
 * @author QY
 */
@Controller
@RequestMapping(value = "${adminPath}/annualMaterial/reportDetails")
public class ReportDetailsController extends BaseController {

	@Autowired
	private ReportDetailsService reportDetailsService;

	@Autowired
	private NewMaterialReportService newMaterialReportService;

	
	@ModelAttribute
	public ReportDetails get(@RequestParam(required=false) String id) {
		ReportDetails entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = reportDetailsService.get(id);
		}
		if (entity == null){
			entity = new ReportDetails();
		}
		return entity;
	}
	
	/**
	 * 年度物资上报明细 列表页面
	 */
	@RequiresPermissions("annualMaterial:reportDetails:list")
	@RequestMapping(value = "list")
	public String list(ReportDetails reportDetails, Model model) {
		model.addAttribute("reportDetails", reportDetails);
		return "modules/sg/annualMaterialReport/annualMaterialReportList";
	}
	
	/**
	 * 年度物资上报明细 列表数据
	 */
	@ResponseBody
	@RequiresPermissions("annualMaterial:reportDetails:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(ReportDetails reportDetails, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ReportDetails> page = reportDetailsService.findPage(new Page<ReportDetails>(request, response), reportDetails);
		return getBootstrapData(page);
	}

    /**
     * 年度物资上报明细 多文件导入
     */
    @ResponseBody
    @RequiresPermissions("annualMaterial:reportDetails:import")
    @RequestMapping(value = "imports")
    public AjaxJson importFile(@RequestParam("file")MultipartFile[] file, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            for(int i=0;i<file.length;i++) {
				String originalFilename = file[i].getOriginalFilename();
				originalFilename = originalFilename.substring(0, originalFilename.indexOf("_"));
				reportDetailsService.saveData(file[i],originalFilename);
            }
			j.setSuccess(true);
            j.setMsg("导入成功");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setErrorCode("999");
            j.setMsg("导入失败！失败信息："+e.getMessage());
        }
        return j;
    }

	/**
	 * 年度物资上报明细 多文件导入页面
	 */
	@RequestMapping(value = "/importMore/Form")
	public String importMoreForm(Model model){
		return "modules/sg/annualMaterialReport/importMore";
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("annualMaterial:reportDetails:export")
	@RequestMapping(value = "export")
	public AjaxJson exportFile(ReportDetails reportDetails, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		HttpSession session = request.getSession();
		try {
			String fileName = "年度物资上报表"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			Page<ReportDetails> page = reportDetailsService.findPage(new Page<ReportDetails>(request, response, -1), reportDetails);
			new ExportExcel("", ReportDetails.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 = "importValidations")
    public AjaxJson importValidations(@RequestParam("file")MultipartFile[] file) {
        AjaxJson j = new AjaxJson();
        List<ReportDetails> list = new ArrayList<>();
		List<String> searchList = new ArrayList<>();
        try {
        	//获取项目名称列表
            for(int i = 0;i<file.length;i++) {
				String name = file[i].getOriginalFilename();
				name = name.substring(0, name.indexOf("_"));
				System.out.println(name);
				searchList.add(name);
            }
            List<NewMaterialReport> projects = newMaterialReportService.findByList(searchList);
            //判断是否有已存在项目
            if(projects != null && projects.size()>0){
            	StringBuilder stringBuilder = new StringBuilder();
            	for(ReportDetails reportDetails : list){
            		stringBuilder.append(reportDetails.getReserveProjectName()+",");
				}
            	j.setMsg(stringBuilder.toString());
                j.setSuccess(true);
            }else {
                for(int k=0;k<file.length;k++) {
					String originalFilename = file[k].getOriginalFilename();
					originalFilename = originalFilename.substring(0, originalFilename.indexOf("_"));
                    reportDetailsService.saveData(file[k],originalFilename);
                }
                j.setSuccess(true);
				j.setErrorCode("0");
                j.setMsg("导入成功");
            }
        } catch (Exception e) {
            j.setSuccess(false);
            j.setErrorCode("999");
            j.setMsg("导入失败！失败信息："+e.getMessage());
        }
        return j;
    }
}