/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sg.financial.expense.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.audit.information.entity.Information;
import com.jeeplus.modules.sg.audit.information.entity.append;
import com.jeeplus.modules.sg.financial.expense.entity.Expense;
import com.jeeplus.modules.sg.financial.expense.service.ExpenseService;
import com.jeeplus.modules.test.onetomany.dialog.entity.TestDataMain1;
import com.jeeplus.modules.test.onetomany.form.entity.TestDataMain2;
import com.jeeplus.modules.test.onetomany.form.service.TestDataMain2Service;
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.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 费用入账管理
 */
@Controller
@RequestMapping(value = "${adminPath}/sg/financial/expense")
public class ExpenseController extends BaseController {

	@Autowired
	private ExpenseService expenseService;
	
	@ModelAttribute
	public Expense get(@RequestParam(required=false) String id) {
		Expense entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = expenseService.get(id);
		}
		if (entity == null){
			entity = new Expense();
		}
		return entity;
	}
	
	/**
	 * 费用入账 列表页面
	 */
//	@RequiresPermissions("sg:financial:expense:list")
	@RequestMapping(value = {"list", ""})
	public String list(Expense expense, Model model) {
		model.addAttribute("expense", expense);
		return "modules/sg/financial/expense/expenseList";
	}


	/**
	 * 获取费用入账列表数据
	 * @param expense
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@ResponseBody
//	@RequiresPermissions("test:onetomany:form:testDataMain2:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Expense expense, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Expense> page = expenseService.findPage(new Page<Expense>(request, response), expense);
		return getBootstrapData(page);
	}

	/**
	 * 新增费用入账页面
	 * @param expense
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "addForm")
	public String addForm(Expense expense, Model model) {
		model.addAttribute("expense", expense);
		return "modules/sg/financial/expense/expenseForm";
	}

	/**
	 * 编辑费用入账页面
	 * @param expense
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "editForm")
	public String editForm(Expense expense, Model model) {
		model.addAttribute("expense", expense);
		return "modules/sg/financial/expense/expenseEditForm";
	}

	/**
	 * 批量删除
	 */
	@ResponseBody
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		if(StringUtils.isBlank(ids)){
			j.setSuccess(false);
			j.setMsg("请选择要删除的项目定义号！");
		}else{
			String idArray[] =ids.split(",");
			List<String> idList = Arrays.asList(idArray);
			expenseService.deleteDatas(idList);
			j.setMsg("删除成功");
		}
		return j;
	}



	/**
	 * 保存费用入账页面 对项目定义号做验证
	 */
	@ResponseBody
	@RequestMapping(value = "save")
	public AjaxJson save(Expense expense, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		Expense expense1 = expenseService.selectByProjectId(expense.getProjectId());
		if (expense1 == null) {
			expenseService.insertData(expense);//保存
			j.setSuccess(true);
			j.setMsg("保存票务代理成功");
		} else {
			j.setSuccess(false);
			j.setMsg("项目定义号已存在不可重复");
		}
		return j;
	}

	/**
	 * 更新
	 */
	@ResponseBody
	@RequestMapping(value = "update")
	public AjaxJson update(Expense expense, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		expenseService.updateData(expense);//保存
		j.setSuccess(true);
		j.setMsg("保存票务代理成功");
		return j;
	}

	/**
	 * 导出模板文件
	 */
	@ResponseBody
	@RequestMapping(value = "templates")
	public AjaxJson templates(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
			String fileName = "费用入账模板文件.xlsx";
			List<append> list = Lists.newArrayList();
			new ExportExcel("", Expense.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 = "importExpense")
    public AjaxJson importExpense(@RequestParam("file") MultipartFile file, Expense expense, HttpServletRequest request, HttpServletResponse response, Model model) {
        AjaxJson j = new AjaxJson();
		List<Expense> expenseList = new ArrayList<>();
		try {
			int successNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			int lastDataRowNum = ei.getLastDataRowNum();
			String reg = "\\d+(\\.\\d+)?";
			for (int i = 1; i < lastDataRowNum; i++) {
				Expense insertExpense = new Expense();
				Row row = ei.getRow(i);
				String projectId = ei.getCellValue(row, 0).toString();
				String projectName = ei.getCellValue(row, 1).toString();
				String projectBatch = ei.getCellValue(row, 2).toString();
				String constructionCost = ei.getCellValue(row, 3).toString();
				String designCost = ei.getCellValue(row, 4).toString();
				String designTypeicalCost = ei.getCellValue(row, 5).toString();
				String supervisionCost = ei.getCellValue(row, 6).toString();
				String supervisionTypeicalCost = ei.getCellValue(row, 7).toString();
				String documentDesignCost = ei.getCellValue(row, 8).toString();
				String documentSupervisionCost = ei.getCellValue(row, 9).toString();
				if ("".equals(projectId)) {
					failureMsg.append("第 "+i+" 行未填写项目定义号</br>");
					continue;
				} else if ("".equals(projectName)) {
					failureMsg.append("项目："+projectId+";未填写项目名称</br>");
					continue;
				}else if ("".equals(projectBatch)) {
					failureMsg.append("项目："+projectId+";未填写项目批次</br>");
					continue;
				}else if ("".equals(constructionCost)||!constructionCost.matches(reg)) {
					failureMsg.append("项目："+projectId+";未正确填写施工费合同折扣</br>");
					continue;
				}else if ("".equals(designCost)||!designCost.matches(reg)) {
					failureMsg.append("项目："+projectId+";未正确填写设计费合同折扣</br>");
					continue;
				}else if ("".equals(designTypeicalCost)||!designTypeicalCost.matches(reg)) {
					failureMsg.append("项目："+projectId+";未正确填写设计费典型折扣</br>");
					continue;
				}else if ("".equals(supervisionCost)||!supervisionCost.matches(reg)) {
					failureMsg.append("项目："+projectId+";未正确填写监理费合同折扣</br>");
					continue;
				}else if ("".equals(supervisionTypeicalCost)||!supervisionTypeicalCost.matches(reg)) {
					failureMsg.append("项目："+projectId+";未正确填写监理费典型折扣</br>");
					continue;
				}else if ("".equals(documentDesignCost)||!documentDesignCost.matches(reg)) {
					failureMsg.append("项目："+projectId+";未发文中设计费金额</br>");
					continue;
				} else if ("".equals(documentSupervisionCost)||!documentSupervisionCost.matches(reg)) {
					failureMsg.append("项目："+projectId+";发文中监理费金额</br>");
					continue;
				} else {
					insertExpense.setProjectId(projectId);
					insertExpense.setProjectName(projectName);
					insertExpense.setProjectBatch(projectBatch);
					insertExpense.setConstructionCost(Double.valueOf(constructionCost));
					insertExpense.setDesignCost(Double.valueOf(designCost));
					insertExpense.setDesignTypeicalCost(Double.valueOf(designTypeicalCost));
					insertExpense.setSupervisionCost(Double.valueOf(supervisionCost));
					insertExpense.setSupervisionTypeicalCost(Double.valueOf(supervisionTypeicalCost));
					insertExpense.setDocumentDesignCost(Double.valueOf(documentDesignCost));
					insertExpense.setDocumentSupervisionCost(Double.valueOf(documentSupervisionCost));
				}
				expenseList.add(insertExpense);
			}
			if (expenseList.size() > 0) {
				expenseService.insertList(expenseList);
				j.setSuccess(true);
				j.setMsg("已成功导入 " + expenseList.size() + " 条费用入账记录</br>" + failureMsg);
			} else {
				j.setSuccess(true);
				j.setMsg( "没有符合规定的数据");
			}
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入费用入账失败！失败信息："+e.getMessage());
		}
        return j;
    }
}