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

import com.google.common.base.Strings;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysmtree.service.SysMtreeService;
import com.jeeplus.modules.workcontent.entity.WorkContentInvestmentCost;
import com.jeeplus.modules.workinvoicedetail.entity.WorkInvoiceDetail;
import com.jeeplus.modules.workreceiptsregister.entity.ResponseEntity;
import com.jeeplus.modules.workreimbursement.entity.WorkAccount;
import com.jeeplus.modules.workreimbursement.entity.WorkReimbursement;
import com.jeeplus.modules.workreimbursement.service.WorkAccountService;
import com.jeeplus.modules.workreimbursement.service.WorkReimbursementService;
import com.jeeplus.modules.workreimbursement.utils.VarStr;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
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 org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 财务报销Controller
 * @author mapengbo
 * @version 2017-10-19
 */
@Controller
@RequestMapping(value = "${adminPath}/workAccount/workAccount")
public class WorkAccountController extends BaseController {

	@Autowired
	private WorkAccountService workAccountService;

	@Autowired
	private WorkReimbursementService workReimbursementService;

	@Autowired
	private HttpServletRequest request;

	@Autowired
    private OfficeService officeService;

	@Autowired
    private SysMtreeService sysMtreeService;

	@ModelAttribute
	public WorkAccount get(@RequestParam(required=false) String id) {

		WorkAccount entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workAccountService.get(id);
		}
		if (entity == null){
			entity = new WorkAccount();
		}
		return entity;
	}

	/**
	 * 报销单列表页面
	 */
	/*@RequestMapping("/addBill")
	public String addBill(WorkAccount workAccount, RedirectAttributes redirectAttributes,Model model) {
//		String wid = request.getParameter("wid");
//		if(!StringUtils.isNotBlank(wid)){
//			addMessage(redirectAttributes, "请先保存报销信息，否则无法添加报销单信息");
//			return "modules/workreimbursement/workReimbursementFormBill";
//		}
//		WorkReimbursement workReimbursement = workReimbursementService.get(wid);
        String typeId = request.getParameter("typeId");
        String flag = request.getParameter("flag");
        String submitterId = request.getParameter("submitterId");
        String officeId = request.getParameter("officeId");
        String billNumber = request.getParameter("billNumber");
        String money = request.getParameter("money");
        String payMode = request.getParameter("payMode");
        String detail = request.getParameter("detail");
        String travelDays = request.getParameter("travelDays");
        if(StringUtils.isNotBlank(typeId)){
            workAccount.setType(sysMtreeService.get(typeId));
        }
        if(StringUtils.isNotBlank(officeId)){
            workAccount.setOffice(officeService.get(officeId));
        }
        if(StringUtils.isNotBlank(submitterId)){
            workAccount.setSubmitter(UserUtils.get(submitterId));
        }
        if(StringUtils.isNotBlank(flag)){
			workAccount.setId(flag);
		}else{
        	workAccount.setId("flag");
		}
		workAccount.setIndex(request.getParameter("index"));
        workAccount.setPayMode(payMode);
        workAccount.setDetail(detail);
        workAccount.setTravelDays(travelDays);
        workAccount.setMoney(money);
        workAccount.setBillNumber(billNumber);
        model.addAttribute("workAccount",workAccount);
//		model.addAttribute("workReimbursement",workReimbursement);
		return "modules/workreimbursement/workReimbursementFormBill";
	}*/
	/**
	 * 报销单列表页面
	 */
	@RequiresPermissions("workAccount:workAccount:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkAccount workAccount, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkAccount> page = workAccountService.findPage(new Page<WorkAccount>(request, response), workAccount);
		model.addAttribute("page", page);
		return "modules/workreimbursement/workReimbursementList";
	}

	/**
	 * 查看，增加，编辑报销单表单页面
	 */
//	@RequiresPermissions(value={"workreimbursement:workReimbursement:view","workreimbursement:workReimbursement:add","workreimbursement:workReimbursement:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkAccount workAccount,Model model) {
        String view = "workReimbursementFormBill";
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workReimbursementFormBillDetail";
		}
//		WorkReimbursement workReimbursement = workReimbursementService.get(workAccount.getWorkReimbursement().getId());
		model.addAttribute("workAccount", workAccount);
//		model.addAttribute("workReimbursement", workReimbursement);
		return "modules/workreimbursement/"+view;
	}

	/**
	 * 报销单信息保存
	 */
	@RequestMapping(value = "save")
	public String save(WorkAccount workAccount, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workAccount)){
			return form(workAccount, model);
		}
		WorkReimbursement workReimbursement = workReimbursementService.get(workAccount.getWorkReimbursement().getId());
		String submitter = workReimbursement.getCreateBy().getId();
		if(!UserUtils.getUser().getId().equals(submitter) && !Strings.isNullOrEmpty(submitter)){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workreimbursement/workReimbursement/?repage";
		}
		String sta = workReimbursement.getStatus();
		//不是再暂存状态或者 审核不通过的情况下 无法修改
		if(!VarStr.status[0].equals(sta) && !VarStr.status[2].equals(sta) && sta != null){
			addMessage(redirectAttributes, "报销单在审核中或者已报销，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workreimbursement/workReimbursement/?repage";
		}
		workAccountService.save(workAccount);
		addMessage(redirectAttributes, "保存报销单成功");
		return "redirect:" + adminPath +"/workreimbursement/workReimbursement/?repage";
	}

	/**
	 * 删除报销单信息
	 */
	@RequiresPermissions("workreimbursement:workReimbursement:del")
	@RequestMapping(value = "delete")
	public String delete(WorkAccount workAccount, RedirectAttributes redirectAttributes,Model model) {
		WorkReimbursement workReimbursement = workReimbursementService.get(workAccount.getWorkReimbursement().getId());
		String sta = workReimbursement.getStatus();
		if(!VarStr.status[0].equals(sta)){
			if(VarStr.status[4].equals(sta)){
				addMessage(redirectAttributes, "报销单已报销，无法删除");
				return "redirect:"+adminPath+"/workreimbursement/workReimbursement/form?id="+workAccount.getWorkReimbursement().getId();
			}else{
				addMessage(redirectAttributes, "报销单正在审核中，无法删除");
				return "redirect:"+adminPath+"/workreimbursement/workReimbursement/form?id="+workAccount.getWorkReimbursement().getId();
			}
		}
		workAccountService.delete(workAccount);
		addMessage(redirectAttributes, "删除报销单成功");
		return "redirect:"+adminPath+"/workreimbursement/workReimbursement/form?id="+workAccount.getWorkReimbursement().getId();
	}
	/**
	 * 导入Excel数据
	 */
	@ResponseBody
	@RequestMapping(value = "import", method=RequestMethod.POST)
	public Object importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		String impType=request.getParameter("impType");
		String orUnicode=request.getParameter("orUnicode");
		String invoiceType=request.getParameter("invoiceType");
		String str="zyfpkjmx";
		if("普票".equals(invoiceType)){
			str="ptfpkjmx";
		}
		List<WorkInvoiceDetail> list =new ArrayList<>();
		ResponseEntity<WorkInvoiceDetail> responseEntity = new ResponseEntity<>();
		try {
			SAXReader reader = new SAXReader();
			try {
				// 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。
				Document document = reader.read(file.getInputStream());
				// 通过document对象获取根节点
				Element bookStore = document.getRootElement();
				// 通过element对象的elementIterator方法获取迭代器
				Iterator it = bookStore.elementIterator();
				// 遍历迭代器，获取根节点中的信息
				while (it.hasNext()) {
					Element root = (Element) it.next();
					Iterator rootIt = root.elementIterator();
					while (rootIt.hasNext()) {
						Element body = (Element) rootIt.next();
						if("body".equals(body.getName())){
							Iterator bodyIt = body.elementIterator();
							while (bodyIt.hasNext()) {
								Element bodyChild = (Element) bodyIt.next();
								if(str.equals(bodyChild.getName())){
									Iterator bodyChildIt = bodyChild.elementIterator();
									while (bodyChildIt.hasNext()) {
										Element mxxx = (Element) bodyChildIt.next();
										Iterator mxxxIt = mxxx.elementIterator();
										WorkInvoiceDetail workInvoiceDetail=new WorkInvoiceDetail();
										String zfbz="";//作废标志
										String gmfnsrsbh="";//纳税人识别号
										while (mxxxIt.hasNext()) {
											Element mxxxChildIt = (Element) mxxxIt.next();
											switch (mxxxChildIt.getName()){
												case "fpdm":
													workInvoiceDetail.setCode(mxxxChildIt.getStringValue());
													break;
												case "fphm":
													workInvoiceDetail.setNumber(mxxxChildIt.getStringValue());
													break;
												case "je":
													workInvoiceDetail.setTaxMoney(mxxxChildIt.getStringValue());
													break;
												case "se":
													workInvoiceDetail.setTaxRate(mxxxChildIt.getStringValue());
													break;
												case "zfbz":
													zfbz=mxxxChildIt.getStringValue();
													break;
												case "gmfnsrsbh":
													gmfnsrsbh=mxxxChildIt.getStringValue();
													break;
											}
										}
										BigDecimal bd=new BigDecimal(workInvoiceDetail.getTaxMoney());
										BigDecimal bd1=new BigDecimal(workInvoiceDetail.getTaxRate());
										workInvoiceDetail.setTotalMoney(bd.add(bd1).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
										BigDecimal divide=(bd1.divide(bd,2, BigDecimal.ROUND_HALF_UP));
										workInvoiceDetail.setTax((divide.multiply(new BigDecimal(100))).setScale(0, BigDecimal.ROUND_HALF_UP).toString());
										if("1".equals(impType)){
											if(orUnicode.equals(gmfnsrsbh)){
												if("N".equals(zfbz)){
													list.add(workInvoiceDetail);
												}
											}
										}else{
											if("N".equals(zfbz)){
												list.add(workInvoiceDetail);
											}
										}
									}
								}
							}
						}
					}
				}
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			responseEntity.setData(list);
			responseEntity.setMessage("成功导入发票明细"+list.size()+"条！");
		} catch (Exception e) {
			logger.error("导入发票明细失败！",e);
			responseEntity.setMessage("导入发票明细失败！"+e.getMessage());
		}
		return responseEntity;
	}
	/**
	 * 导出excel文件
	 */
//	@RequiresPermissions("workreimbursement:workReimbursement:export")
//    @RequestMapping(value = "export", method=RequestMethod.POST)
//    public String exportFile(WorkReimbursement workReimbursement, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
//		try {
//            String fileName = "报销单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
//            Page<WorkReimbursement> page = workReimbursementService.findPage(new Page<WorkReimbursement>(request, response, -1), workReimbursement);
//    		new ExportExcel("报销单", WorkReimbursement.class).setDataList(page.getList()).write(response, fileName).dispose();
//    		return null;
//		} catch (Exception e) {
//			addMessage(redirectAttributes, "导出报销单记录失败！失败信息："+e.getMessage());
//		}
//		return "redirect:"+Global.getAdminPath()+"/workreimbursement/workReimbursement/?repage";
//    }

	/**
	 * 导入Excel数据

	 */
//	@RequiresPermissions("workreimbursement:workReimbursement:import")
//    @RequestMapping(value = "import", method=RequestMethod.POST)
//    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
//		try {
//			int successNum = 0;
//			int failureNum = 0;
//			StringBuilder failureMsg = new StringBuilder();
//			ImportExcel ei = new ImportExcel(file, 1, 0);
//			List<WorkReimbursement> list = ei.getDataList(WorkReimbursement.class);
//			for (WorkReimbursement workReimbursement : list){
//				try{
//					workReimbursementService.save(workReimbursement);
//					successNum++;
//				}catch(ConstraintViolationException ex){
//					failureNum++;
//				}catch (Exception ex) {
//					failureNum++;
//				}
//			}
//			if (failureNum>0){
//				failureMsg.insert(0, "，失败 "+failureNum+" 条报销单记录。");
//			}
//			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条报销单记录"+failureMsg);
//		} catch (Exception e) {
//			addMessage(redirectAttributes, "导入报销单失败！失败信息："+e.getMessage());
//		}
//		return "redirect:"+Global.getAdminPath()+"/workreimbursement/workReimbursement/?repage";
//    }
	
	/**
	 * 下载导入报销单数据模板
	 */
//	@RequiresPermissions("workreimbursement:workReimbursement:import")
//    @RequestMapping(value = "import/template")
//    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
//		try {
//            String fileName = "报销单数据导入模板.xlsx";
//    		List<WorkReimbursement> list = Lists.newArrayList();
//    		new ExportExcel("报销单数据", WorkReimbursement.class, 1).setDataList(list).write(response, fileName).dispose();
//    		return null;
//		} catch (Exception e) {
//			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
//		}
//		return "redirect:"+Global.getAdminPath()+"/workreimbursement/workReimbursement/?repage";
//    }

	@RequestMapping("/saveEntity")
	@ResponseBody
	public Map<Object,Object> saveEntity(){

		return null;
	}
}