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.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.NotDuplicate;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basedata.entity.FdQuotationTemplateItem;
import org.jeecg.modules.basedata.entity.FdQuotationTemplateItemTree;
import org.jeecg.modules.basedata.service.IFdQuotationTemplateItemService;

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-16
 * @version： V1.0
 */
@RestController
@RequestMapping("/basedata/fdQuotationTemplateItem")
@Slf4j
public class FdQuotationTemplateItemController {
	@Autowired
	private IFdQuotationTemplateItemService fdQuotationTemplateItemService;
	
	/**
	  * 分页列表查询
	 * @param fdQuotationTemplateItem
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<FdQuotationTemplateItem>> queryPageList(FdQuotationTemplateItem fdQuotationTemplateItem,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<FdQuotationTemplateItem>> result = new Result<IPage<FdQuotationTemplateItem>>();
		//对报价单模板进行模糊查询

		if (StringUtils.isNotBlank(fdQuotationTemplateItem.getName())){
			fdQuotationTemplateItem.setName("*"+fdQuotationTemplateItem.getName()+"*");
		}

		String pkQuotationTemplate=fdQuotationTemplateItem.getPkQuotationTemplate();
		if (StringUtils.isNotBlank(fdQuotationTemplateItem.getPkQuotationTemplate())){
			fdQuotationTemplateItem.setPkQuotationTemplate(null);
		}

		QueryWrapper<FdQuotationTemplateItem> queryWrapper = QueryGenerator.initQueryWrapper(fdQuotationTemplateItem, req.getParameterMap());

		if (StringUtils.isNotBlank(pkQuotationTemplate)){
			queryWrapper.eq("fqti.pk_quotation_template",pkQuotationTemplate);
		}
		Page<FdQuotationTemplateItem> page = new Page<FdQuotationTemplateItem>(pageNo, pageSize);
		IPage<FdQuotationTemplateItem> pageList = fdQuotationTemplateItemService.findByPage(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	  *   添加
	 * @param fdQuotationTemplateItem
	 * @return
	 */
	@PostMapping(value = "/add")
	@NotDuplicate
	public Result<FdQuotationTemplateItem> add(@RequestBody @Valid FdQuotationTemplateItem fdQuotationTemplateItem, BindingResult bindingResult) {
		Result<FdQuotationTemplateItem> result = new Result<FdQuotationTemplateItem>();
		try {
			StringBuilder sb = new StringBuilder();
			if (bindingResult.hasErrors()){
				//记录错误信息
				bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
				result.error500(sb.toString());
				return result;
			}
			fdQuotationTemplateItemService.save(fdQuotationTemplateItem);
			// fdQuotationTemplateItem.setTreeKey(fdQuotationTemplateItem.getId());
			// fdQuotationTemplateItemService.updateById(fdQuotationTemplateItem);
			result.success("添加成功！");
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			result.error500("操作失败:"+e.getMessage());

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

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

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<FdQuotationTemplateItem> pageList = fdQuotationTemplateItemService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "报价单模板项目列表");
      mv.addObject(NormalExcelConstants.CLASS, FdQuotationTemplateItem.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<FdQuotationTemplateItem> listFdQuotationTemplateItems = ExcelImportUtil.importExcel(file.getInputStream(), FdQuotationTemplateItem.class, params);
              for (FdQuotationTemplateItem fdQuotationTemplateItemExcel : listFdQuotationTemplateItems) {
                  fdQuotationTemplateItemService.save(fdQuotationTemplateItemExcel);
              }
              return Result.ok("文件导入成功！数据行数：" + listFdQuotationTemplateItems.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-20
	  * @param  模板id
	  * @return tree集合
	  */
	 @GetMapping(value = "/queryTreeList")
	 public Result<List<FdQuotationTemplateItemTree>> queryTreeList(@RequestParam(name="pkTemplateId") String pkTemplateId){
		 Result<List<FdQuotationTemplateItemTree>> result = new Result<>();
		 try {
			 LambdaQueryWrapper<FdQuotationTemplateItem> lambdaQueryWrapper =new LambdaQueryWrapper<>();
			 lambdaQueryWrapper.eq(FdQuotationTemplateItem::getPkQuotationTemplate,pkTemplateId);
			 lambdaQueryWrapper.orderBy(true,true,FdQuotationTemplateItem::getCode);
			 List<FdQuotationTemplateItem> list = fdQuotationTemplateItemService.list(lambdaQueryWrapper);
			 List<FdQuotationTemplateItem> list1 = fdQuotationTemplateItemService.findOrderByCode(pkTemplateId);
			 List<FdQuotationTemplateItemTree> treeLists = new ArrayList<>();
			 getTreeList(treeLists,list1,null);
			 findLeaf(treeLists);
			 result.setResult(treeLists);
		 }catch (Exception e){
			 e.fillInStackTrace();
		 }
		 return result;
	 }

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

		 }
	 }

	 private void findLeaf(List<FdQuotationTemplateItemTree> treeList) {
		 for (FdQuotationTemplateItemTree fdQuotationTemplateItemTree : treeList) {
			 if (fdQuotationTemplateItemTree.getChildren().isEmpty()) {
				 fdQuotationTemplateItemTree.setIsLeaf(true);
				 fdQuotationTemplateItemTree.setChildren(null);
			 } else {
				 findLeaf(fdQuotationTemplateItemTree.getChildren());
			 }
		 }
	 }

	 /*
	 *
	  *	查询除本身及以下的上级项目
	  * @author 陈创
	  * @date 2019-5-20
	  * @param  实体对象
	  * @return 实体集合
	  */
	 @GetMapping(value = "/queryByNotParentId")
	 public Result<List<FdQuotationTemplateItem>> queryByNotParentId(FdQuotationTemplateItem fdQuotationTemplateItem) {
		 Result<List<FdQuotationTemplateItem>> result = new Result<List<FdQuotationTemplateItem>>();
		 LambdaQueryWrapper<FdQuotationTemplateItem> lambdaQueryWrapper =new LambdaQueryWrapper<>();
		 lambdaQueryWrapper.eq(FdQuotationTemplateItem::getDelFlag,"0");
		 // lambdaQueryWrapper.eq(FdQuotationTemplateItem::getPkQuotationTemplate,fdQuotationTemplateItem.getPkQuotationTemplate());//修改对象模板外键
		 whereParent(lambdaQueryWrapper,fdQuotationTemplateItem);//排除子级
		 lambdaQueryWrapper.or();//或者
		 lambdaQueryWrapper.isNull(FdQuotationTemplateItem::getParentId);//为null
		 lambdaQueryWrapper.or();//或者
		 lambdaQueryWrapper.eq(FdQuotationTemplateItem::getParentId,"");//为空
		 lambdaQueryWrapper.orderByAsc(FdQuotationTemplateItem::getCode);//排序
		 List<FdQuotationTemplateItem> fdQuotationTemplateItemList = fdQuotationTemplateItemService.list(lambdaQueryWrapper);
		 if(fdQuotationTemplateItemList==null) {
			 result.error500("未找到对应实体");
		 }else {
			 //排除需修改对象
			 // for(){
				//  if(||!){
				// 	 //与修改对象id相等则移除
				// 	 fdQuotationTemplateItemList.remove(templateItem);
				//  }
			 // }
			 List<FdQuotationTemplateItem> list=new ArrayList<>();
			 for(FdQuotationTemplateItem templateItem: fdQuotationTemplateItemList){
			 	if(templateItem.getPkQuotationTemplate().equals(fdQuotationTemplateItem.getPkQuotationTemplate())){
			 		if(!templateItem.getId().equals(fdQuotationTemplateItem.getId())){
			 			list.add(templateItem);
					}
				}
			 }
			 result.setResult(list);
			 result.setSuccess(true);
		 }
		 return result;
	 }

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

}
