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

import com.google.common.collect.Lists;
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.financial.erpcredit.util.ImportUtil;
import com.jeeplus.modules.sg.financial.settlement.entity.MaintainData;
import com.jeeplus.modules.sg.financial.settlement.service.DataMaintenanceService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 概预算基本信息维护
 */
@Controller
@RequestMapping(value = "${adminPath}/sg/settlement")
public class DataMaintenanceController extends BaseController {

	@Autowired
	private DataMaintenanceService dataMaintenanceService;
	
	@ModelAttribute
	public MaintainData get(@RequestParam(required=false) String id) {
		MaintainData entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = dataMaintenanceService.get(id);
		}
		if (entity == null){
			entity = new MaintainData();
		}
		return entity;
	}
	
	/**
	 * 列表页面
	 */
	@RequiresPermissions("sg:settlement:list")
	@RequestMapping(value = {"list", ""})
	public String list(MaintainData maintainData, Model model) {
		model.addAttribute("maintainData", maintainData);
		return "modules/sg/financial/settlement/dataMaintenanceList";
	}


	/**
	 * 列表数据
	 */
	@ResponseBody
	@RequiresPermissions("sg:settlement:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(MaintainData maintainData, HttpServletRequest request, HttpServletResponse response, Model model,HttpSession session) {
		String id = UserUtils.getUser().getId();
		String state = maintainData.getState();
		String st = "";
//		这里state不知道代表什么含义
		if(state.equals("0")) {
			st = (String) session.getAttribute(id);
		}else {
			session.removeAttribute(id);
		}
		String projectId = maintainData.getProjectId();
		if(StringUtils.isNotBlank(projectId)){
			st = projectId;
		}
//		对查询的id进行处理，若只有一个id设置projectId模糊匹配，若有多个设置projectIds精准匹配
		if(StringUtils.isNotBlank(st)){
			String[] sts = st.split("\\s+");
			if(sts.length == 1){
			    maintainData.setProjectId(sts[0]);
            }else {
                maintainData.setProjectIds(sts);
                maintainData.setProjectId(null);
            }
		}
		Page<MaintainData> page = dataMaintenanceService.findPage(new Page<MaintainData>(request, response), maintainData);
		return getBootstrapData(page);
	}
	/**
	 * 导入查询
	 */
	@ResponseBody
	@RequiresPermissions("sg:settlement:import")
	@RequestMapping(value = "importsel")
	public Map<String, Object> importSelect(@RequestParam("file")MultipartFile file, MaintainData maintainData, HttpServletResponse response, HttpServletRequest request, HttpSession session){
		try {
			ImportExcel importExcel = new ImportExcel(file, 1, 0);
			int lastRow = importExcel.getLastDataRowNum();
			StringBuilder stringBuilder = new StringBuilder();
			for(int i=1;i<lastRow;i++){
				Row row = importExcel.getRow(i);
				String str = (String) importExcel.getCellValue(row, 0);
				if(StringUtils.isNotBlank(str)) {
					stringBuilder.append(str + " ");
				}
			}
			String st = stringBuilder.toString();
			String sts = st.substring(0,st.length()-1);
			//把id作为key，把查询条件存入session
			String id = UserUtils.getUser().getId();
			session.setAttribute(id,st);
			String[] strs = st.split(" ");
			maintainData.setProjectIds(strs);
			Page<MaintainData> page = dataMaintenanceService.findPage(new Page<MaintainData>(request, response), maintainData);
			return getBootstrapData(page);
		}catch (Exception e){
			return  null;
		}
	}
	/**
	 * 查看，增加，编辑表单页面
	 */
	@RequiresPermissions(value={"sg:settlement:view","sg:settlement:add","sg:settlement:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(MaintainData maintainData, Model model) {
		model.addAttribute("maintainData", maintainData);
		return "modules/sg/financial/settlement/dataMaintenanceForm";
	}

	/**
	 * 保存
	 */
	@ResponseBody
	@RequiresPermissions(value={"sg:settlement:add","sg:settlement:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(MaintainData maintainData, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(maintainData);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		dataMaintenanceService.save(maintainData);//保存
		j.setSuccess(true);
		j.setMsg("保存成功");
		return j;
	}
	
	/**
	 * 删除
	 */
	@ResponseBody
	@RequiresPermissions("sg:settlement:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(MaintainData maintainData) {
		AjaxJson j = new AjaxJson();
		dataMaintenanceService.delete(maintainData);
		j.setMsg("删除成功");
		return j;
	}
	/**
	 * 批量删除
	 */
	@ResponseBody
	@RequiresPermissions("sg:settlement:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			dataMaintenanceService.deleteData(id);
		}
		j.setMsg("删除成功");
		return j;
	}
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("sg:settlement:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(MaintainData maintainData, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
//            String fileName = DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
//            Page<MaintainData> page = dataMaintenanceService.findPage(new Page<MaintainData>(request, response, -1), maintainData);
//    		new ExportExcel(null, MaintainData.class).setDataList(page.getList()).write(response, fileName).dispose();
			dataMaintenanceService.export(maintainData,response);
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@ResponseBody
	@RequiresPermissions("sg:settlement:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			ImportExcel ei = new ImportExcel(file, 2, 0);
			Boolean mainJudge = getMainJudge(ei);
			if (mainJudge){
				j.setSuccess(false);
				j.setMsg("导入失败！失败信息："+"表不符合规范");
				return j;
			}
			List<MaintainData> list = getData(ei);
			dataMaintenanceService.saveList(list);
			j.setMsg("导入成功");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入失败！失败信息："+e.getMessage());
		}
		return j;
    }



	/**
	 * 下载导入数据模板
	 */
	@ResponseBody
	@RequiresPermissions("sg:settlement:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
			dataMaintenanceService.exportHeard(response);
			j.setSuccess(true);
			j.setMsg("导出成功！");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }

	/**
	 *excel文件数据读取
	 */
	private List<MaintainData> getData(ImportExcel importExcel) throws ParseException {
		int lastRow = importExcel.getLastDataRowNum();
		List<MaintainData> list = new ArrayList<>();
		MaintainData maintainData = null;
		for(int i=3; i<lastRow;i++){
			maintainData = new MaintainData();
			Row row = importExcel.getRow(i);
			String projectId = (String) importExcel.getCellValue(row,0);
			if(StringUtils.isNotBlank(projectId)) {
				maintainData.setProjectId(projectId);
				maintainData.setDesignUnits((String) importExcel.getCellValue(row, 1));
				maintainData.setConstructionUnits((String) importExcel.getCellValue(row, 2));
				maintainData.setAddress((String) importExcel.getCellValue(row, 3));
				maintainData.setProperty((String) importExcel.getCellValue(row, 4));
				maintainData.setInvestment((String) importExcel.getCellValue(row, 5));
			    maintainData.setStartDate(getDate(importExcel,row,6));
			    maintainData.setEndDate(getDate(importExcel,row,7));
				maintainData.setApprovalNumber((String) importExcel.getCellValue(row, 8));
				maintainData.setBuildingFee(getDouble(importExcel,row,9));
				maintainData.setInstallFee(getDouble(importExcel,row,10));
				maintainData.setEquipmentFee(getDouble(importExcel,row,11));
				maintainData.setMaterialFee(getDouble(importExcel,row,12));
				maintainData.setDesignFee(getDouble(importExcel,row,13));
				maintainData.setSupervisionFee(getDouble(importExcel,row,14));
				maintainData.setPreliminaryWorkFee(getDouble(importExcel,row,15));
				maintainData.setDamages(getDouble(importExcel,row,16));
				maintainData.setManagementFee(getDouble(importExcel,row,17));
				list.add(maintainData);
			}
		}
		return list;
	}

	/**
	 *获取excel double类型的值
	 */
	private double getDouble(ImportExcel importExcel,Row row,int col){
		double d = 0.00;
        Object o = importExcel.getCellValue(row,col);
        if(!o.equals("")){
        	d = Double.parseDouble(o.toString());
		}
      return d;
	}

	/**
	 *获取excel date类型的值
	 */
	private Date getDate(ImportExcel importExcel,Row row,int col) throws ParseException {
		Date d = null;
		Object o = importExcel.getCellValue(row,col);
		if(!o.equals("")){
			SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
			d = simpleDateFormat.parse(o.toString());
		}
		return d;
	}


	//校验数据表格是否正确
	public static Boolean getMainJudge(ImportExcel importExcel){
		Boolean flag = false;
		Row row = importExcel.getRow(0);
		String mainCode = (String) importExcel.getCellValue(row,0);
		if (!mainCode.contains("项目定义")){
			flag = true;
		}
		String lineItem = (String)importExcel.getCellValue(row,1);
		if (!lineItem.contains("单位")){
			flag = true;
		}
		return  flag;
	}


}