package org.jeecg.modules.financeManage.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.aspect.annotation.NotDuplicate;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.basedata.entity.FdPassFeeClassProject;
import org.jeecg.modules.projectManagement.entity.FdContract;
import org.jeecg.modules.projectManagement.entity.FdProjectFile;
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.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.financeManage.entity.FdHandoverfeeB;
import org.jeecg.modules.financeManage.entity.FdHandoverfee;
import org.jeecg.modules.financeManage.vo.FdHandoverfeePage;
import org.jeecg.modules.financeManage.service.IFdHandoverfeeService;
import org.jeecg.modules.financeManage.service.IFdHandoverfeeBService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
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 com.alibaba.fastjson.JSON;

 /**
 * @Title: Controller
 * @Description: 财务过手费主表
 * @author： jeecg-boot
 * @date：   2019-07-13
 * @version： V1.0
 */
@RestController
@RequestMapping("/financeManage/fdHandoverfee")
@Slf4j
public class FdHandoverfeeController {
	@Autowired
	private IFdHandoverfeeService fdHandoverfeeService;
	@Autowired
	private IFdHandoverfeeBService fdHandoverfeeBService;

	@Autowired
	private ISysSerialPatternService sysSerialPatternService;

	/**
	  * 分页列表查询
	 * @param fdHandoverfee
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	@RequiresPermissions("url:theirFees:view")
	public Result<IPage<FdHandoverfee>> queryPageList(FdHandoverfee fdHandoverfee,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		fdHandoverfee.setDelFlag("0");
		Result<IPage<FdHandoverfee>> result = new Result<IPage<FdHandoverfee>>();
		String contractno = fdHandoverfee.getContractno();
		if (StringUtils.isNotBlank(fdHandoverfee.getContractno())) {
			fdHandoverfee.setContractno(null);
		}
		String code = fdHandoverfee.getCode();
		if (StringUtils.isNotBlank(fdHandoverfee.getCode())) {
			fdHandoverfee.setCode(null);
		}
		QueryWrapper<FdHandoverfee> queryWrapper = QueryGenerator.initQueryWrapper(fdHandoverfee, req.getParameterMap());
		if (StringUtils.isNotBlank(contractno)) {
			queryWrapper.like("contractno", contractno);
		}
		if (StringUtils.isNotBlank(code)) {
			queryWrapper.like("code", code);
		}
		queryWrapper.lambda().eq(FdHandoverfee::getDelFlag,"0");
		queryWrapper.lambda().orderByDesc(FdHandoverfee::getCreateTime);
		Page<FdHandoverfee> page = new Page<FdHandoverfee>(pageNo, pageSize);
		IPage<FdHandoverfee> pageList = fdHandoverfeeService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	  *   添加
	 * @param fdHandoverfeePage
	 * @return
	 */
	@PostMapping(value = "/add")
	@NotDuplicate
	@RequiresPermissions("theirFees:add")
	public Result<FdHandoverfee> add(@RequestBody  @Valid FdHandoverfeePage fdHandoverfeePage, BindingResult bindingResult) {
		Result<FdHandoverfee> result = new Result<FdHandoverfee>();
		try {
			FdHandoverfee fdHandoverfee = new FdHandoverfee();
			BeanUtils.copyProperties(fdHandoverfeePage, fdHandoverfee);
			StringBuilder stringBuilder = new StringBuilder();
			if (bindingResult.hasErrors()) {
				//实体错误信息
				bindingResult.getAllErrors().stream().forEach(error -> stringBuilder.append(error.getDefaultMessage() + "<br/>"));
				result.error500(stringBuilder.toString());
				return result;
			}

			//获取GSF 6 编码
			CallResult<String> resultSerial = sysSerialPatternService.getNextSerial(fdHandoverfee, "fd_handoverfee", "code", true);
			if(!resultSerial.isSucceed()){
				result.error500("获取编码失败");
				return result;
			}
			fdHandoverfee.setCode(resultSerial.getContent());

			if(fdHandoverfeePage.getFdHandoverfeeBList().size() < 1){
				result.error500("明细不能为空");
				return result;
			}

			fdHandoverfeeService.saveMain(fdHandoverfee, fdHandoverfeePage.getFdHandoverfeeBList());
			result.success("添加成功！");
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param fdHandoverfeePage
	 * @return
	 */
	@PutMapping(value = "/edit")
	@NotDuplicate
	@RequiresPermissions("theirFees:update")
	public Result<FdHandoverfee> edit(@RequestBody @Valid FdHandoverfeePage fdHandoverfeePage, BindingResult bindingResult) {
		Result<FdHandoverfee> result = new Result<FdHandoverfee>();
		FdHandoverfee fdHandoverfee = new FdHandoverfee();
		BeanUtils.copyProperties(fdHandoverfeePage, fdHandoverfee);
		FdHandoverfee fdHandoverfeeEntity = fdHandoverfeeService.getById(fdHandoverfee.getId());
		if(fdHandoverfeeEntity==null) {
			result.error500("未找到对应实体");
		}else {

			StringBuilder stringBuilder = new StringBuilder();
			if (bindingResult.hasErrors()) {
				//实体错误信息
				bindingResult.getAllErrors().stream().forEach(error -> stringBuilder.append(error.getDefaultMessage() + "<br/>"));
				result.error500(stringBuilder.toString());
				return result;
			}
			if(fdHandoverfeePage.getFdHandoverfeeBList().size() < 1){
				result.error500("明细不能为空");
				return result;
			}
			boolean ok = fdHandoverfeeService.updateById(fdHandoverfee);
			fdHandoverfeeService.updateAll(fdHandoverfee, fdHandoverfeePage.getFdHandoverfeeBList());
			result.success("修改成功!");
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	@NotDuplicate
	@RequiresPermissions("theirFees:delete")
	public Result<FdHandoverfee> delete(@RequestParam(name="id",required=true) String id) {
		Result<FdHandoverfee> result = new Result<FdHandoverfee>();
		FdHandoverfee fdHandoverfee = fdHandoverfeeService.getById(id);
		if(fdHandoverfee==null) {
			result.error500("未找到对应实体");
		}else {
			fdHandoverfee.setDelFlag(CommonConstant.DEL_FLAG_1.toString());
			boolean ok = fdHandoverfeeService.updateById(fdHandoverfee);
// 			fdHandoverfeeService.delMain(id);
			result.success("删除成功!");
		}
		
		return result;
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<FdHandoverfee> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<FdHandoverfee> result = new Result<FdHandoverfee>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.fdHandoverfeeService.delBatchMain(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<FdHandoverfee> queryById(@RequestParam(name="id",required=true) String id) {
		Result<FdHandoverfee> result = new Result<FdHandoverfee>();
		FdHandoverfee fdHandoverfee = fdHandoverfeeService.getById(id);
		if(fdHandoverfee==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(fdHandoverfee);
			result.setSuccess(true);
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryFdHandoverfeeBByMainId")
	public Result<List<FdHandoverfeeB>> queryFdHandoverfeeBListByMainId(@RequestParam(name="id",required=true) String id) {
		Result<List<FdHandoverfeeB>> result = new Result<List<FdHandoverfeeB>>();
		List<FdHandoverfeeB> fdHandoverfeeBList = fdHandoverfeeBService.selectByMainId(id);
		result.setResult(fdHandoverfeeBList);
		result.setSuccess(true);
		return result;
	}

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

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<FdHandoverfeePage> pageList = new ArrayList<FdHandoverfeePage>();
      List<FdHandoverfee> fdHandoverfeeList = fdHandoverfeeService.list(queryWrapper);
      for (FdHandoverfee fdHandoverfee : fdHandoverfeeList) {
          FdHandoverfeePage vo = new FdHandoverfeePage();
          BeanUtils.copyProperties(fdHandoverfee, vo);
          List<FdHandoverfeeB> fdHandoverfeeBList = fdHandoverfeeBService.selectByMainId(fdHandoverfee.getId());
          vo.setFdHandoverfeeBList(fdHandoverfeeBList);
          pageList.add(vo);
      }
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "财务过手费主表列表");
      mv.addObject(NormalExcelConstants.CLASS, FdHandoverfeePage.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<FdHandoverfeePage> list = ExcelImportUtil.importExcel(file.getInputStream(), FdHandoverfeePage.class, params);
              for (FdHandoverfeePage page : list) {
                  FdHandoverfee po = new FdHandoverfee();
                  BeanUtils.copyProperties(page, po);
                  fdHandoverfeeService.saveMain(po, page.getFdHandoverfeeBList());
              }
              return Result.ok("文件导入成功！数据行数：" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage());
              return Result.error("文件导入失败！");
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

	 /**
	  * 通过合同号，查询合同所有关联数据
	  * @param code
	  * @return
	  */
	 @GetMapping(value = "/findContractByCode")
	 public Result<FdProjectFile> findContractByCode(@RequestParam(name="pkProjectFile") String pkProjectFile) {
	 	System.out.println(pkProjectFile + "-----------");
	 	Result<FdProjectFile> result = new Result<FdProjectFile>();
		result.setResult(fdHandoverfeeService.findContractByCode(pkProjectFile));
		result.setCode(0);
		if(result.getResult() == null){
			result.setCode(1);
		}
		return result;
	 }

	 /**
	  * 通过过手费编码，查询所有关联数据
	  * @param code
	  * @return
	  */
	 @GetMapping(value = "/findHandoverfeeByCode")
	 public Result<FdPassFeeClassProject> findHandoverfeeByCode(@RequestParam(name="code") String code) {

	 	 Result<FdPassFeeClassProject> result = new Result<FdPassFeeClassProject>();
		 List<FdPassFeeClassProject> list = fdHandoverfeeService.findHandoverfeeByCode(code);
		 if(list.size() > 0){
			 result.setResult(list.get(0));
			 result.setCode(0);
		 }else{
			 result.setCode(1);
		 }

		 return result;
	 }

	 /**
	  * 通过合同编码，查询收款条件
	  * @param code
	  * @return
	  */
	 @GetMapping(value = "/selectClause")
	 public FdHandoverfeePage selectClause(@RequestParam(name="code") String code) {
		 FdHandoverfeePage result = new FdHandoverfeePage();
		 List<FdHandoverfeeB> list = fdHandoverfeeService.selectClause(code);
		 int num = 1;
		 for(FdHandoverfeeB a:list){

		 	Double estimator = a.getEstimator();
		 	System.out.println("------------");
		 	Double contractAmountAll = a.getContractAmountAll();
		 	a.setContractAmount(contractAmountAll*(estimator/100));
		 	a.setNumber(num);
		 	num ++;
		 }
		 result.setFdHandoverfeeBList(list);
	 	 return result;
	 }

	 /**
	  * 查询合同下拉
	  * @return
	  */
//	 public List<FdHandoverfee> selectContract(){
//		 return fdHandoverfeeMapper.selectContract();
//	 }

	 public static void main(){
		 Double num1 = 7.0;
		 Double num2 = 9.0;

		 // 创建一个数值格式化对象
		 NumberFormat numberFormat = NumberFormat.getInstance();
		 // 设置精确到小数点后2位
		 numberFormat.setMaximumFractionDigits(2);

		 String result = numberFormat.format(  num1 /  num2 * 100);

		 System.out.println("num1和num2的百分比为:" + result + "%");
	 }



	 /**
	  * 查询重复编码
	  * @param code
	  * @return
	  */
	 @GetMapping(value = "/fingMoreCodeInfo")
	 public Result fingMoreCodeInfo(@RequestParam(name="code") String code,@RequestParam(name="id") String id) {
		 Result result = new Result();
		  int list = fdHandoverfeeService.fingMoreCode(code,id);
		  if(list > 0){
			  result.setCode(1);
		  }else{
			  result.setCode(0);
		  }
		 return result;

	 }

	 /**
	  * 审核
	  * @param ids
	  * @return
	  */
	 @GetMapping(value = "/toExamine")
	 public Result toExamine(@RequestParam(name="ids") String ids,@RequestParam(name="state") String state) {
		 Result result = new Result();
		 fdHandoverfeeService.toExamine(ids,state);
		 return result;

	 }
 }
