package org.jeecg.modules.basedata.controller;

import java.util.ArrayList;
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 org.apache.shiro.authz.annotation.Logical;
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.basedata.entity.FdPassFeeClass;
import org.jeecg.modules.basedata.entity.FdPassFeeClassTree;
import org.jeecg.modules.basedata.service.IFdPassFeeClassService;

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.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： jeecg-boot
 * @date：   2019-05-10
 * @version： V1.0
 */
@RestController
@RequestMapping("/basedata/fdPassFeeClass")
@Slf4j
public class FdPassFeeClassController {
	@Autowired
	private IFdPassFeeClassService fdPassFeeClassService;
	
	/**
	  * 分页列表查询
	 * @param fdPassFeeClass
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<FdPassFeeClass>> queryPageList(FdPassFeeClass fdPassFeeClass,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<FdPassFeeClass>> result = new Result<IPage<FdPassFeeClass>>();
		QueryWrapper<FdPassFeeClass> queryWrapper = QueryGenerator.initQueryWrapper(fdPassFeeClass, req.getParameterMap());
		Page<FdPassFeeClass> page = new Page<FdPassFeeClass>(pageNo, pageSize);
		IPage<FdPassFeeClass> pageList = fdPassFeeClassService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	  *   添加
	 * @param fdPassFeeClass
	 * @return
	 */
	@PostMapping(value = "/add")
	@NotDuplicate
	@RequiresPermissions(value = {"cost-class:add","cost-class-parent:add"},logical = Logical.OR)
	public Result<FdPassFeeClass> add(@RequestBody @Valid FdPassFeeClass fdPassFeeClass, BindingResult bindingResult) {
		Result<FdPassFeeClass> result = new Result<FdPassFeeClass>();
		try {
			StringBuilder stringBuilder=new StringBuilder();
			if(bindingResult.hasErrors()){
				//实体错误信息
				bindingResult.getAllErrors().stream().forEach(error -> stringBuilder.append(error.getDefaultMessage() + "<br/>"));
				result.error500(stringBuilder.toString());
				return result;
			}
			fdPassFeeClass.setDelFlag(CommonConstant.DEL_FLAG_0.toString());
			fdPassFeeClassService.save(fdPassFeeClass);
			result.success("添加成功！");
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			result.error500("操作失败:"+e.getMessage());

		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param fdPassFeeClass
	 * @return
	 */
	@PutMapping(value = "/edit")
	@NotDuplicate
	@RequiresPermissions("cost-class:update")
	public Result<FdPassFeeClass> edit(@RequestBody @Valid FdPassFeeClass fdPassFeeClass,BindingResult bindingResult) {
		Result<FdPassFeeClass> result = new Result<FdPassFeeClass>();
		FdPassFeeClass fdPassFeeClassEntity = fdPassFeeClassService.getById(fdPassFeeClass.getId());
		if(fdPassFeeClassEntity==null) {
			StringBuilder stringBuilder=new StringBuilder();
			if(bindingResult.hasErrors()){
				//实体错误信息
				bindingResult.getAllErrors().stream().forEach(error -> stringBuilder.append(error.getDefaultMessage() + "<br/>"));
				result.error500(stringBuilder.toString());
				return result;
			}
			result.error500("未找到对应实体");
		}else {
			boolean ok = fdPassFeeClassService.updateById(fdPassFeeClass);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	@NotDuplicate
	@RequiresPermissions("cost-class:update")
	public Result<FdPassFeeClass> delete(@RequestParam(name="id",required=true) String id) {
		Result<FdPassFeeClass> result = new Result<FdPassFeeClass>();
		FdPassFeeClass fdPassFeeClass = fdPassFeeClassService.getById(id);
		if(fdPassFeeClass==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = fdPassFeeClassService.removeById(id);
			if(ok) {
				result.success("删除成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<FdPassFeeClass> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<FdPassFeeClass> result = new Result<FdPassFeeClass>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.fdPassFeeClassService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<FdPassFeeClass> queryById(@RequestParam(name="id",required=true) String id) {
		Result<FdPassFeeClass> result = new Result<FdPassFeeClass>();
		FdPassFeeClass fdPassFeeClass = fdPassFeeClassService.getById(id);
		if(fdPassFeeClass==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(fdPassFeeClass);
			result.setSuccess(true);
		}
		return result;
	}

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

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

  /*
  *
   *树集合
   * @author 陈创
   * @date 2019-5-10
   * @param
   * @return
   */
	 @GetMapping(value = "passFeeClassTree")
	 public Result<List<FdPassFeeClassTree>> getPassFeeClassTree(){
		 Result<List<FdPassFeeClassTree>> result=new Result<List<FdPassFeeClassTree>>();
		 try {
			 List<FdPassFeeClass> list=fdPassFeeClassService.list();
			 List<FdPassFeeClassTree> treeLists=new ArrayList<FdPassFeeClassTree>();
			 getTreeList(treeLists,list,null);
			 findLeaf(treeLists);
			 result.setResult(treeLists);
		 }catch (Exception e){
			 e.fillInStackTrace();
		 }
		 return  result;
	 }

	 /*
	  *
	  *树集合
	  * @author 陈创
	  * @date 2019-5-10
	  * @param
	  * @return
	  */
	 @GetMapping(value = "passFeeClassTree1")
	 @RequiresPermissions("url:cost:view")
	 public Result<List<FdPassFeeClassTree>> getPassFeeClassTree1(){
		 Result<List<FdPassFeeClassTree>> result=new Result<List<FdPassFeeClassTree>>();
		 try {
			 List<FdPassFeeClass> list=fdPassFeeClassService.list();
			 List<FdPassFeeClassTree> treeLists=new ArrayList<FdPassFeeClassTree>();
			 getTreeList(treeLists,list,null);
			 findLeaf(treeLists);
			 result.setResult(treeLists);
		 }catch (Exception e){
			 e.fillInStackTrace();
		 }
		 return  result;
	 }

	 private void getTreeList(List<FdPassFeeClassTree> treeList, List<FdPassFeeClass> bmlist, FdPassFeeClassTree temp) {
		 for (FdPassFeeClass bmSupplierClass : bmlist) {
			 String tempPid = bmSupplierClass.getParentId();
			 FdPassFeeClassTree tree = new FdPassFeeClassTree(bmSupplierClass);
			 if(temp == null && oConvertUtils.isEmpty(tempPid)) {
				 treeList.add(tree);
				 if(!tree.getIsLeaf()) {
					 getTreeList(treeList, bmlist, tree);
				 }
			 }else if(temp != null && tempPid != null && tempPid.equals(temp.getId())){
				 temp.getChildren().add(tree);
				 if(!tree.getIsLeaf()) {
					 getTreeList(treeList, bmlist, tree);
				 }
			 }

		 }
	 }

	 private void findLeaf(List<FdPassFeeClassTree> treeList){
		 for(FdPassFeeClassTree bmSupplierClassTree : treeList){
			 if(bmSupplierClassTree.getChildren().isEmpty()){
				 bmSupplierClassTree.setIsLeaf(true);
			 }else{
				 findLeaf(bmSupplierClassTree.getChildren());
			 }
		 }

	 }

	 /*
	 *
	  * 查询除本身及以下的上级项目
	  * @author 陈创
	  * @date 2019/5/21
	  * @param	过手费分类修改时对象id
	  * @return 过手费分类集合
	  */
	 @GetMapping(value = "/queryByNotParentId")
	 public Result<List<FdPassFeeClass>> queryByNotParentId(FdPassFeeClass fdPassFeeClass) {
		 Result<List<FdPassFeeClass>> result = new Result<List<FdPassFeeClass>>();
		 LambdaQueryWrapper<FdPassFeeClass> lambdaQueryWrapper =new LambdaQueryWrapper<>();//查询条件
		 lambdaQueryWrapper.eq(FdPassFeeClass::getDelFlag,"0");
		 whereParent(lambdaQueryWrapper,fdPassFeeClass);//排除子级
		 lambdaQueryWrapper.or();//或者
		 lambdaQueryWrapper.isNull(FdPassFeeClass::getParentId);//为null
		 lambdaQueryWrapper.or();//或者
		 lambdaQueryWrapper.eq(FdPassFeeClass::getParentId,"");//为空
		 lambdaQueryWrapper.orderByAsc(FdPassFeeClass::getCode);//排序
		 List<FdPassFeeClass> fdPassFeeClassList = fdPassFeeClassService.list(lambdaQueryWrapper);
		 if(fdPassFeeClassList==null) {
			 result.error500("未找到对应实体");
		 }else {
			 //排除需修改对象
			 for(FdPassFeeClass feeclass: fdPassFeeClassList){
				 if(feeclass.getId().equals(fdPassFeeClass.getId())){
					 //与修改对象id相等则移除
					 fdPassFeeClassList.remove(feeclass);
					 break;
				 }
			 }
			 result.setResult(fdPassFeeClassList);
			 result.setSuccess(true);
		 }
		 return result;
	 }

	 //递归排除修改对象的子级以及以下节点数据
	 public void whereParent(LambdaQueryWrapper<FdPassFeeClass> lambdaQueryWrapper,FdPassFeeClass fdPassFeeClass){
		 lambdaQueryWrapper.ne(FdPassFeeClass::getParentId,fdPassFeeClass.getId());//排除子级
		 LambdaQueryWrapper<FdPassFeeClass> lambdaQueryWrapper2=new LambdaQueryWrapper<>();
		 lambdaQueryWrapper2.eq(FdPassFeeClass::getDelFlag,"0");
		 lambdaQueryWrapper2.eq(FdPassFeeClass::getParentId,fdPassFeeClass.getId());//父级id
		 List<FdPassFeeClass> list=fdPassFeeClassService.list(lambdaQueryWrapper2);//根据父级id查询子级
		 for(FdPassFeeClass passClass:list){
			 whereParent(lambdaQueryWrapper,passClass);
		 }
	 }

}
