package org.jeecg.modules.financeManage.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 org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.financeManage.entity.FdIncome;
import org.jeecg.modules.financeManage.entity.FdIncomeItem;
import org.jeecg.modules.financeManage.service.IFdIncomeService;

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.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.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： jeecg-boot
 * @date：   2019-12-02
 * @version： V1.0
 */
@RestController
@RequestMapping("/financeManage/fdIncome")
@Slf4j
public class FdIncomeController {
	@Autowired
	private IFdIncomeService fdIncomeService;
	
	/**
	  * 分页列表查询
	 * @param fdIncome
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	@RequiresPermissions("url:projectRevenueRecognition:view")
	public Result<IPage<FdIncome>> queryPageList(FdIncome fdIncome,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<FdIncome>> result = new Result<IPage<FdIncome>>();
		String contractName=fdIncome.getContractName();//合同号
		if(StringUtils.isNotBlank(contractName)){
			fdIncome.setContractName(null);
		}

		//判断客户id是否为字符”null“
		if(StringUtils.isNotBlank(fdIncome.getCurstomerId())){
			if(fdIncome.getCurstomerId().equals("null")){
				fdIncome.setCurstomerId(null);
			}
		}
		//生物分析总监
		List<String> bioanalyticalPmList=fdIncome.getBioanalyticalPmList();
		if(bioanalyticalPmList!=null&&bioanalyticalPmList.size()>0){
			fdIncome.setBioanalyticalPmList(null);
		}
		//合同方
		String contractPartyId=fdIncome.getContractPartyId();
		if(StringUtils.isNotBlank(contractPartyId)){
			fdIncome.setContractPartyId(null);
		}
		//生物实验地点
		String labAddressId=fdIncome.getLabAddressId();
		if(StringUtils.isNotBlank(labAddressId)){
			fdIncome.setLabAddressId(null);
		}
		//结算状态
		String settlementStatusId=fdIncome.getSettlementStatusId();
		if(StringUtils.isNotBlank(settlementStatusId)){
			fdIncome.setSettlementStatusId(null);
		}
		//委托方名称
		String curstomerName=fdIncome.getCurstomerName();
		if(StringUtils.isNotBlank(curstomerName)){
			fdIncome.setCurstomerName(null);
		}

		QueryWrapper<FdIncome> queryWrapper = QueryGenerator.initQueryWrapper(fdIncome, req.getParameterMap());
		Page<FdIncome> page = new Page<FdIncome>(pageNo, pageSize);
		if(StringUtils.isNotBlank(contractName)){//合同号模糊查询
			queryWrapper.like("fi.contract_name",contractName);
		}
		if(bioanalyticalPmList!=null&&bioanalyticalPmList.size()>0){
			queryWrapper.in("fpf.bioanalytical_pm",bioanalyticalPmList);
		}
		if(StringUtils.isNotBlank(contractPartyId)&&!contractPartyId.equals("null")){
			queryWrapper.eq("fi.contract_party_id",contractPartyId);
		}
		if(StringUtils.isNotBlank(labAddressId)&&!labAddressId.equals("null")){
			queryWrapper.eq("fi.lab_address_id",labAddressId);
		}
		if(StringUtils.isNotBlank(settlementStatusId)&&!settlementStatusId.equals("null")){
			queryWrapper.eq("fi.settlement_status_id",settlementStatusId);
		}
		if(StringUtils.isNotBlank(curstomerName)){
			queryWrapper.like("fi.curstomer_name",curstomerName);
		}

		queryWrapper.eq("fi.del_flag",CommonConstant.DEL_FLAG_0.toString());
		queryWrapper.orderByDesc("fi.create_time");
		//IPage<FdIncome> pageList = fdIncomeService.page(page, queryWrapper);
		IPage<FdIncome> pageList = fdIncomeService.findByPage(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	  *   添加
	 * @param fdIncome
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<FdIncome> add(@RequestBody FdIncome fdIncome) {
		Result<FdIncome> result = new Result<FdIncome>();
		try {
			fdIncomeService.save(fdIncome);
			result.success("添加成功！");
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param fdIncome
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<FdIncome> edit(@RequestBody FdIncome fdIncome) {
		Result<FdIncome> result = new Result<FdIncome>();
		FdIncome fdIncomeEntity = fdIncomeService.getById(fdIncome.getId());
		if(fdIncomeEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = fdIncomeService.updateById(fdIncome);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}
		
		return result;
	}
	
	// /**
	//   *   通过id删除
	//  * @param id
	//  * @return
	//  */
	// @DeleteMapping(value = "/delete")
	// public Result<FdIncome> delete(@RequestParam(name="id",required=true) String id) {
	// 	Result<FdIncome> result = new Result<FdIncome>();
	// 	FdIncome fdIncome = fdIncomeService.getById(id);
	// 	if(fdIncome==null) {
	// 		result.error500("未找到对应实体");
	// 	}else {
	// 		boolean ok = fdIncomeService.removeById(id);
	// 		if(ok) {
	// 			result.success("删除成功!");
	// 		}
	// 	}
	//
	// 	return result;
	// }

	 /**
	  *   通过id删除
	  * @param id
	  * @return
	  */
	 @DeleteMapping(value = "/delete")
	 public Result<FdIncome> delete(@RequestParam(name="id",required=true) String id) {
		 Result<FdIncome> result = new Result<FdIncome>();
		 FdIncome fdIncome = fdIncomeService.getById(id);
		 if(fdIncome==null) {
			 result.error500("未找到对应实体");
		 }else {
		 	 fdIncome.setDelFlag(CommonConstant.DEL_FLAG_1.toString());
			 boolean ok = fdIncomeService.updateById(fdIncome);
			 if(ok) {
				 result.success("删除成功!");
			 }
		 }

		 return result;
	 }
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<FdIncome> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<FdIncome> result = new Result<FdIncome>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.fdIncomeService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<FdIncome> queryById(@RequestParam(name="id",required=true) String id) {
		Result<FdIncome> result = new Result<FdIncome>();
		FdIncome fdIncome = fdIncomeService.getById(id);
		if(fdIncome==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(fdIncome);
			result.setSuccess(true);
		}
		return result;
	}

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

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<FdIncome> pageList = fdIncomeService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "收入确认列表");
      mv.addObject(NormalExcelConstants.CLASS, FdIncome.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<FdIncome> listFdIncomes = ExcelImportUtil.importExcel(file.getInputStream(), FdIncome.class, params);
              for (FdIncome fdIncomeExcel : listFdIncomes) {
                  fdIncomeService.save(fdIncomeExcel);
              }
              return Result.ok("文件导入成功！数据行数：" + listFdIncomes.size());
          } catch (Exception e) {
              log.error(e.getMessage());
              return Result.error("文件导入失败！");
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

  /***
   * @Title:根据报价id查询模板明细项
          * @Description:TODO
          * @param quotationId
          * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.financeManage.entity.FdIncome>
          * @exception 
          * @author 陈创
          * @date 2019/12/2 17:52
          * @updatehistory:
   *   2019/12/2 17:52 新增
          */
  @GetMapping("/getTempItemsByQuotation")
  public Result<List<FdIncomeItem>> getTempItemsByQuotation(String quotationId){
  	Result<List<FdIncomeItem>> result=new Result<>();
	  try {
		  List<FdIncomeItem> fdIncomeItemList= fdIncomeService.getTempItemsByQuotation(quotationId);
		  result.setResult(fdIncomeItemList);
		  result.setSuccess(true);
	  } catch (Exception e) {
		  e.printStackTrace();
		  result.error500("操作失败："+e.getMessage());
	  }
	  return result;
  }

  /***
   * @Title:新增收入确认与明细
          * @Description:TODO
          * @param fdIncome
          * @return org.jeecg.common.api.vo.Result
          * @exception 
          * @author 陈创
          * @date 2019/12/2 18:15
          * @updatehistory:
   *   2019/12/2 18:15 新增
          */
  @PostMapping("/addIncome")
  public Result addIncome(@RequestBody FdIncome fdIncome){
  	Result result=new Result();
	  try {
		  fdIncomeService.addIncome(fdIncome);
		  result.setSuccess(true);
	  } catch (Exception e) {
		  e.printStackTrace();
		  result.error500("操作失败："+e.getMessage());
	  }
	  return result;
  }

  /***
   * @Title:修改
          * @Description:TODO
          * @param fdIncome
          * @return org.jeecg.common.api.vo.Result
          * @exception
          * @author 陈创
          * @date 2019/12/4 10:13
          * @updatehistory:
   *   2019/12/4 10:13 新增
          */
  @PostMapping("/updateIncome")
  public Result updateIncome(@RequestBody FdIncome fdIncome){
      Result result=new Result();
	  FdIncome fdIncomeEntity = fdIncomeService.getById(fdIncome.getId());
	  if(fdIncomeEntity==null) {
		  result.error500("未找到对应实体");
	  }else {
		  try {
			  fdIncomeService.updateIncome(fdIncome);
			  result.setSuccess(true);
		  } catch (Exception e) {
			  e.printStackTrace();
			  result.error500("操作失败："+e.getMessage());
		  }
	  }
  	return result;
  }

  /***
   * @Title:复制
          * @Description:TODO 复制拉去项目信息 获取上期完成
          * @param id
          * @return org.jeecg.common.api.vo.Result
          * @exception
          * @author 陈创
          * @date 2019/12/27 13:35
          * @updatehistory:
   *   2019/12/27 13:35 新增
          */
  @GetMapping("/copyIncome")
  public Result copyIncome(String id){
      Result result=new Result();
      FdIncome fdIncomeEntity = fdIncomeService.getById(id);
      if(fdIncomeEntity==null){
          result.error500("未找到对应实体");
      }else{
          try {
              fdIncomeService.copyIncome(fdIncomeEntity);
              result.setSuccess(true);
          } catch (Exception e) {
              e.printStackTrace();
              result.error500("操作失败："+e.getMessage());
          }
      }
      return result;
  }

  /**
  * @Author chenchuang
  * @Description //TODO 获取相关主表确认信息
  * @Date 2020/5/28 14:14
  * @Param [contractId]
  * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.financeManage.entity.FdIncome>
  */
  @GetMapping("/getFdIncomeData")
  public Result<FdIncome> getFdIncomeData(String contractId){
	  Result<FdIncome> result=new Result<>();
	  try {
		  FdIncome fdIncome=fdIncomeService.getFdIncomeData(contractId);
		  result.setResult(fdIncome);
		  result.success("操作成功");
	  } catch (Exception e) {
		  e.printStackTrace();
		  result.error500("操作失败："+e.getMessage());
	  }
	  return result;
  }

  /**
  * @Author chenchuang
  * @Description //TODO 更新收入确认
  * @Date 2020/5/29 16:49
  * @Param []
  * @return org.jeecg.common.api.vo.Result
  */
  @GetMapping("/refreshProgress")
  public Result refreshProgress(){
  	Result result=new Result();
	  try {
		  fdIncomeService.refreshProgress();
		  result.success("操作成功");
	  } catch (Exception e) {
		  e.printStackTrace();
		  result.error500("操作失败");
	  }
	  return result;
  }


}
