package org.jeecg.modules.finance.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.NotDuplicate;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.finance.entity.FdBalancePaymentSettlement;
import org.jeecg.modules.finance.entity.FdBalancePaymentSettlementItem;
import org.jeecg.modules.finance.service.IFdBalancePaymentSettlementItemService;
import org.jeecg.modules.finance.service.IFdBalancePaymentSettlementService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.projectManagement.entity.FdContractClause;
import org.jeecg.modules.projectManagement.service.IFdContractClauseService;
import org.jeecg.modules.system.service.ISysSerialPatternService;
import org.jeecg.modules.system.vo.CallResult;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;

 /**
 * @Title: Controller
 * @Description: 尾款结算
 * @author： tanj
 * @date：   2019-07-20
 * @version： V1.0
 */
@RestController
@RequestMapping("/finance/fdBalancePaymentSettlement")
@Slf4j
public class FdBalancePaymentSettlementController {
	@Autowired
	private IFdBalancePaymentSettlementService fdBalancePaymentSettlementService;
	@Autowired
	private IFdBalancePaymentSettlementItemService fdBalancePaymentSettlementItemService;
	@Autowired
	private IFdContractClauseService fdContractClauseService;

	@Autowired
	private ISysSerialPatternService sysSerialPatternService;

	/**
	  * 分页列表查询
	 * @param fdBalancePaymentSettlement
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	@RequiresPermissions("url:balancePayment:view")
	public Result<IPage<FdBalancePaymentSettlement>> queryPageList(FdBalancePaymentSettlement fdBalancePaymentSettlement,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<FdBalancePaymentSettlement>> result = new Result<IPage<FdBalancePaymentSettlement>>();
		String contractCode = fdBalancePaymentSettlement.getContractCode();
		if (StringUtils.isNotBlank(fdBalancePaymentSettlement.getContractCode())){
			fdBalancePaymentSettlement.setContractCode(null);
		}
		String statementNo = fdBalancePaymentSettlement.getStatementNo();
		if (StringUtils.isNotBlank(fdBalancePaymentSettlement.getStatementNo())){
			fdBalancePaymentSettlement.setStatementNo(null);
		}
		QueryWrapper<FdBalancePaymentSettlement> queryWrapper = QueryGenerator.initQueryWrapper(fdBalancePaymentSettlement, req.getParameterMap());
		if (StringUtils.isNotBlank(contractCode)){
			queryWrapper.like("contract_code",contractCode);
		}
		if (StringUtils.isNotBlank(statementNo)){
			queryWrapper.like("statement_no",statementNo);
		}
		// queryWrapper.eq("del_flag","0");
		queryWrapper.lambda().eq(FdBalancePaymentSettlement::getDelFlag,"0");
		queryWrapper.lambda().orderByDesc(FdBalancePaymentSettlement::getCreateTime);
		Page<FdBalancePaymentSettlement> page = new Page<FdBalancePaymentSettlement>(pageNo, pageSize);
		IPage<FdBalancePaymentSettlement> pageList = fdBalancePaymentSettlementService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	  *   添加
	 * @param fdBalancePaymentSettlement
	 * @return
	 */
	@PostMapping(value = "/add")
	@NotDuplicate
	@RequiresPermissions("balancePayment:add")
	public Result<FdBalancePaymentSettlement> add(@RequestBody @Valid FdBalancePaymentSettlement fdBalancePaymentSettlement, BindingResult bindingResult) {
		Result<FdBalancePaymentSettlement> result = new Result<FdBalancePaymentSettlement>();
		try {
			StringBuilder sb = new StringBuilder();
			if (bindingResult.hasErrors()) {
				//记录错误信息
				bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
				result.error500(sb.toString());
				return result;
			}
			// if (Integer.parseInt(fdBalancePaymentSettlement.getContractMoney()) == 0){
			// 	result.error500("合同金额不能小于或为零");
			// 	return result;
			// }
			if (fdBalancePaymentSettlement.getBalancePaymentSettlementItemList().size() == 0){
				result.error500("至少添加一条尾款明细");
				return result;
			}
			//新增产生
			if(fdBalancePaymentSettlement.getId()==null||fdBalancePaymentSettlement.getId().equals("")){
				//获取GSF 6 编码
				CallResult<String> resultSerial = sysSerialPatternService.getNextSerial(fdBalancePaymentSettlement, "fd_balance_payment_settlement", "statement_no", true);
				if(!resultSerial.isSucceed()){
					result.error500("获取编码失败");
					return result;
				}
				fdBalancePaymentSettlement.setStatementNo(resultSerial.getContent());
			}
			fdBalancePaymentSettlementService.addBalancePaymentSettlement(fdBalancePaymentSettlement);
			result.success("添加成功！");
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			result.error500("操作失败" + e.getMessage());
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param fdBalancePaymentSettlement
	 * @return
	 */
	@PutMapping(value = "/edit")
	@NotDuplicate
	@RequiresPermissions("balancePayment:update")
	public Result<FdBalancePaymentSettlement> edit(@RequestBody @Valid FdBalancePaymentSettlement fdBalancePaymentSettlement, BindingResult bindingResult) {
		Result<FdBalancePaymentSettlement> result = new Result<FdBalancePaymentSettlement>();
		FdBalancePaymentSettlement fdBalancePaymentSettlementEntity = fdBalancePaymentSettlementService.getById(fdBalancePaymentSettlement.getId());
		if(fdBalancePaymentSettlementEntity==null) {
			result.error500("未找到对应实体");
		}else {
			try {
				StringBuilder sb = new StringBuilder();
				if (bindingResult.hasErrors()) {
					//记录错误信息
					bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
					result.error500(sb.toString());
					return result;
				}
				// if (Integer.parseInt(fdBalancePaymentSettlement.getContractMoney()) <= 0){
				// 	result.error500("合同金额不能小于或为零");
				// 	return result;
				// }
				if (fdBalancePaymentSettlement.getBalancePaymentSettlementItemList().size() <= 0){
					result.error500("至少保留一条尾款明细");
					return result;
				}
				fdBalancePaymentSettlementService.updateBalancePaymentSettlement(fdBalancePaymentSettlement);
				result.success("修改成功！");
			} catch (Exception e) {
				e.printStackTrace();
				log.info(e.getMessage());
				result.error500("操作失败" + e.getMessage());
			}
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	// @DeleteMapping(value = "/delete")
	// public Result<FdBalancePaymentSettlement> delete(@RequestParam(name="id",required=true) String id) {
	// 	Result<FdBalancePaymentSettlement> result = new Result<FdBalancePaymentSettlement>();
	// 	FdBalancePaymentSettlement fdBalancePaymentSettlement = fdBalancePaymentSettlementService.getById(id);
	// 	if(fdBalancePaymentSettlement==null) {
	// 		result.error500("未找到对应实体");
	// 	}else {
	// 		try {
	// 			fdBalancePaymentSettlementService.removeById(id);
	// 			//	将关联的尾款明细删除
	// 			Map<String, Object> map = Maps.newHashMap();
	// 			map.put("balance_payment_settlement_id",fdBalancePaymentSettlement.getId());
	// 			fdBalancePaymentSettlementItemService.removeByMap(map);
	// 			result.success("删除成功！");
	// 		} catch (Exception e) {
	// 			e.printStackTrace();
	// 			log.info(e.getMessage());
	// 			result.error500("操作失败" + e.getMessage());
	// 		}
	// 	}
	//
	// 	return result;
	// }

	/***
	 * @Title:删除
	        * @Description:TODO
	        * @param id
	        * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.finance.entity.FdBalancePaymentSettlement>
	        * @exception
	        * @author 陈创
	        * @date 2019/11/1 17:35
	        * @updatehistory:
	 *   2019/11/1 17:35 删除
	        */
	@DeleteMapping(value = "/delete")
	@NotDuplicate
	@RequiresPermissions("balancePayment:delete")
	public Result<FdBalancePaymentSettlement> delete(@RequestParam(name="id",required=true) String id) {
		Result<FdBalancePaymentSettlement> result = new Result<FdBalancePaymentSettlement>();
		FdBalancePaymentSettlement fdBalancePaymentSettlement = fdBalancePaymentSettlementService.getById(id);
		if(fdBalancePaymentSettlement==null) {
			result.error500("未找到对应实体");
		}else {
			try {
				fdBalancePaymentSettlement.setDelFlag(CommonConstant.DEL_FLAG_1.toString());
				fdBalancePaymentSettlementService.updateById(fdBalancePaymentSettlement);
				result.success("删除成功！");
			} catch (Exception e) {
				e.printStackTrace();
				log.info(e.getMessage());
				result.error500("操作失败" + e.getMessage());
			}
		}

		return result;
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<FdBalancePaymentSettlement> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<FdBalancePaymentSettlement> result = new Result<FdBalancePaymentSettlement>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.fdBalancePaymentSettlementService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<FdBalancePaymentSettlement> queryById(@RequestParam(name="id",required=true) String id) {
		Result<FdBalancePaymentSettlement> result = new Result<FdBalancePaymentSettlement>();
		FdBalancePaymentSettlement fdBalancePaymentSettlement = fdBalancePaymentSettlementService.getById(id);
		if(fdBalancePaymentSettlement==null) {
			result.error500("未找到对应实体");
		}else {
			//	将尾款明细带出
			Map<String, Object> map = Maps.newHashMap();
			map.put("balance_payment_settlement_id",fdBalancePaymentSettlement.getId());
			map.put("del_flag","0");
			LambdaQueryWrapper<FdBalancePaymentSettlementItem> fdBalancePaymentSettlementItemLambdaQueryWrapper=new LambdaQueryWrapper<>();
			fdBalancePaymentSettlementItemLambdaQueryWrapper.eq(FdBalancePaymentSettlementItem::getBalancePaymentSettlementId,fdBalancePaymentSettlement.getId());
			fdBalancePaymentSettlementItemLambdaQueryWrapper.eq(FdBalancePaymentSettlementItem::getDelFlag,"0");
			fdBalancePaymentSettlementItemLambdaQueryWrapper.orderByAsc(FdBalancePaymentSettlementItem::getSort);
			List<FdBalancePaymentSettlementItem>  fdBalancePaymentSettlementItemMap =fdBalancePaymentSettlementItemService.list(fdBalancePaymentSettlementItemLambdaQueryWrapper);
			fdBalancePaymentSettlement.setBalancePaymentSettlementItemList(fdBalancePaymentSettlementItemMap);
			result.setResult(fdBalancePaymentSettlement);
			result.setSuccess(true);
		}
		return result;
	}

	/**
	 * @Author tanj
	 * @Description //TODO 弃审核数据,使其状态为0
	 * @Date 14:11 2019/7/20
	 * @Param [ids]
	 * @return org.jeecg.common.api.vo.Result<FdProjectFile>
	 **/
	@GetMapping(value = "/auditBatch")
	public Result<FdBalancePaymentSettlement> auditBatch(@RequestParam(name="ids",required = true) List<String> ids){
		Result<FdBalancePaymentSettlement> result=new Result<>();
		String message="";
		if(ids.isEmpty()){
			message+="请选择数据</br>";
		}
		Map<String,Object> map= null;
		try {
			//执行service
			map = fdBalancePaymentSettlementService.auditBatch(ids);
			result.setSuccess(true);
			result.setMessage(message+map.get("msg").toString());
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
		}
		return result;
	}

	/**
	 * @Author tanj
	 * @Description //TODO 状态关闭,使其状态为1
	 * @Date 14:57 2019/7/20
	 * @Param [ids]
	 * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.finance.entity.FdBalancePaymentSettlement>
	 **/
	@GetMapping(value = "/reviewBatch")
	public Result<FdBalancePaymentSettlement> reviewBatch(@RequestParam(name="ids",required = true) List<String> ids){
		Result<FdBalancePaymentSettlement> result=new Result<>();
		String message="";
		if(ids.isEmpty()){
			message+="请选择数据</br>";
		}
		Map<String,Object> map= null;
		try {
			//执行service
			map = fdBalancePaymentSettlementService.reviewBatch(ids);
			result.setSuccess(true);
			result.setMessage(message+map.get("msg").toString());
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
		}
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<FdBalancePaymentSettlement> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              FdBalancePaymentSettlement fdBalancePaymentSettlement = JSON.parseObject(deString, FdBalancePaymentSettlement.class);
              queryWrapper = QueryGenerator.initQueryWrapper(fdBalancePaymentSettlement, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<FdBalancePaymentSettlement> pageList = fdBalancePaymentSettlementService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "尾款结算列表");
      mv.addObject(NormalExcelConstants.CLASS, FdBalancePaymentSettlement.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("尾款结算列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<FdBalancePaymentSettlement> listFdBalancePaymentSettlements = ExcelImportUtil.importExcel(file.getInputStream(), FdBalancePaymentSettlement.class, params);
              for (FdBalancePaymentSettlement fdBalancePaymentSettlementExcel : listFdBalancePaymentSettlements) {
                  fdBalancePaymentSettlementService.save(fdBalancePaymentSettlementExcel);
              }
              return Result.ok("文件导入成功！数据行数：" + listFdBalancePaymentSettlements.size());
          } catch (Exception e) {
              log.error(e.getMessage());
              return Result.error("文件导入失败！");
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

}
