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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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

import com.jeeplus.modules.constructionunit.entity.ConstructionExportUnit;
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.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
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.constructionunit.entity.ConstructionUnit;
import com.jeeplus.modules.constructionunit.service.ConstructionUnitService;

/**
 * ConstructionUnitController
 * @author 邱悦
 * @version 2021-12-29
 */
@RestController
@RequestMapping(value = "/constructionUnit/constructionUnit")
public class ConstructionUnitController extends BaseController {

	@Autowired
	private ConstructionUnitService constructionUnitService;

	@ModelAttribute
	public ConstructionUnit get(@RequestParam(required=false) String id) {
		ConstructionUnit entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = constructionUnitService.get(id);
		}
		if (entity == null){
			entity = new ConstructionUnit();
		}
		return entity;
	}

	/**
	 * 施工单位列表数据
	 */
	@RequiresPermissions("constructionUnit:constructionUnit:list")
	@GetMapping("list")
	public AjaxJson list(ConstructionUnit constructionUnit, HttpServletRequest request, HttpServletResponse response) {
		Page<ConstructionUnit> page = constructionUnitService.findPage(new Page<ConstructionUnit>(request, response), constructionUnit);
		return AjaxJson.success().put("page",page);
	}

	/**
	 * 根据Id获取施工单位数据
	 */
	@RequiresPermissions(value={"constructionUnit:constructionUnit:view","constructionUnit:constructionUnit:add","constructionUnit:constructionUnit:edit"},logical=Logical.OR)
	@GetMapping("queryById")
	public AjaxJson queryById(ConstructionUnit constructionUnit) {
		return AjaxJson.success().put("constructionUnit", constructionUnit);
	}

	/**
	 * 保存施工单位
	 */
	@RequiresPermissions(value={"constructionUnit:constructionUnit:add","constructionUnit:constructionUnit:edit"},logical=Logical.OR)
	@PostMapping("save")
	public AjaxJson save(ConstructionUnit constructionUnit, Model model) throws Exception{
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(constructionUnit);
		if (StringUtils.isNotBlank(errMsg)){
			return AjaxJson.error(errMsg);
		}
		//新增验证，年份加名称是否纯在，存在提是不予修改，不存在修改
		Boolean aBoolean = constructionUnitService.saveName(constructionUnit);//保存
		if (aBoolean) {
			return AjaxJson.success("保存施工单位成功");
		}else {
			return AjaxJson.error("当前年度施工单位已存在");
		}
	}



	/**
	 * 保存施工单位
	 */
	@RequiresPermissions(value={"constructionUnit:constructionUnit:add","constructionUnit:constructionUnit:edit"},logical=Logical.OR)
	@PostMapping("update")
	public AjaxJson update(ConstructionUnit constructionUnit, Model model) throws Exception{
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(constructionUnit);
		if (StringUtils.isNotBlank(errMsg)){
			return AjaxJson.error(errMsg);
		}
		//新增或编辑表单保存
		Boolean update = constructionUnitService.update(constructionUnit);//保存
		if (update) {
			return AjaxJson.success("保存施工单位成功");
		}else{
			return AjaxJson.error("施工单位已存在");
		}
	}


	/**
	 * 批量删除施工单位
	 */
	@RequiresPermissions("constructionUnit:constructionUnit:del")
	@DeleteMapping("delete")
	public AjaxJson delete(String ids) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			constructionUnitService.delete(constructionUnitService.get(id));
		}
		return AjaxJson.success("删除施工单位成功");
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("constructionUnit:constructionUnit:export")
    @GetMapping("export")
    public AjaxJson exportFile(ConstructionUnit constructionUnit, HttpServletRequest request, HttpServletResponse response) {
		try {
            String fileName = "施工单位"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<ConstructionUnit> page = constructionUnitService.findPage(new Page<ConstructionUnit>(request, response, -1), constructionUnit);
    		new ExportExcel("施工单位", ConstructionExportUnit.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error("导出施工单位记录失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("constructionUnit:constructionUnit:import")
    @PostMapping("import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file,String yearOfEvaluation, HttpServletResponse response, HttpServletRequest request) {
		try {
			ImportExcel ei = new ImportExcel(file, 1, 0);
			int lastDataRowNum = ei.getLastDataRowNum();
			List<ConstructionUnit> list = new ArrayList<>();
			for (int i = 1; i < lastDataRowNum; i++) {
				ConstructionUnit constructionUnit = new ConstructionUnit();
				Row row = ei.getRow(i);
				String cellValue = (String) ei.getCellValue(row, 0);
				constructionUnit.setUnitName(cellValue);
				list.add(constructionUnit);
			}
//			list = ei.getDataList(ConstructionUnit.class);
			if (null != list && list.size() > 0) {
				HashMap<String,String> StringMsg = constructionUnitService.insertList(list,yearOfEvaluation);
				String insertFlag = StringMsg.get("insertFlag");
				String builder = StringMsg.get("builder");
				if ("true".equals(insertFlag)) {
					return AjaxJson.success(builder);
				}else{
					return AjaxJson.error(builder);
				}
			}else{
				return AjaxJson.error("导入数据为空");
			}
		} catch (Exception e) {
			return AjaxJson.error("导入施工单位失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 下载导入施工单位数据模板
	 */
	@RequiresPermissions("constructionUnit:constructionUnit:import")
    @GetMapping("import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		try {
            String fileName = "施工单位数据导入模板.xlsx";
    		List<String> list = Lists.newArrayList();
    		new ExportExcel("", ConstructionUnit.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error( "导入模板下载失败！失败信息："+e.getMessage());
		}
    }


}