package org.jeecg.modules.basedata.controller;

import java.util.*;
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.FdContractClass;
import org.jeecg.modules.projectManagement.entity.FdContractClassTree;
import org.jeecg.modules.basedata.service.IFdContractClassService;

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-07
 * @version： V1.0
 */
@RestController
@RequestMapping("/basedata/fdContractClass")
@Slf4j
public class FdContractClassController {
	@Autowired
	private IFdContractClassService fdContractClassService;
	
	/**
	  * 分页列表查询
	 * @param fdContractClass
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<FdContractClass>> queryPageList(FdContractClass fdContractClass,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<FdContractClass>> result = new Result<IPage<FdContractClass>>();
		fdContractClass.setDelFlag(CommonConstant.DEL_FLAG_0.toString());
		QueryWrapper<FdContractClass> queryWrapper = QueryGenerator.initQueryWrapper(fdContractClass, req.getParameterMap());
		Page<FdContractClass> page = new Page<FdContractClass>(pageNo, pageSize);
		queryWrapper.orderByDesc("create_time");
		IPage<FdContractClass> pageList = fdContractClassService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

	 /**
	  * 子父级查询
	  */
	 @GetMapping(value = "contractList")
	 public Result<List<FdContractClassTree>> seList(){
		 Result<List<FdContractClassTree>> result=new Result<List<FdContractClassTree>>();
		 try {
			 LambdaQueryWrapper<FdContractClass> lambdaQueryWrapper=new LambdaQueryWrapper<>();
			 lambdaQueryWrapper.eq(FdContractClass::getDelFlag,"0");
			 lambdaQueryWrapper.orderByAsc(FdContractClass::getCode);
			 List<FdContractClass> list = fdContractClassService.list(lambdaQueryWrapper);
			 List<FdContractClassTree> treeLists=new ArrayList<FdContractClassTree>();
			 getTreeList(treeLists,list,null);
			 findLeaf(treeLists);
			 result.setResult(treeLists);
		 }catch (Exception e){
			 e.fillInStackTrace();
		 }
		 return  result;
	 }

	 /**
	  * 子父级查询（有权限）
	  */
	 @GetMapping(value = "contractList1")
	 @RequiresPermissions("url:contract-class:view")
	 public Result<List<FdContractClassTree>> seList1(){
		 Result<List<FdContractClassTree>> result=new Result<List<FdContractClassTree>>();
		 try {
			 LambdaQueryWrapper<FdContractClass> lambdaQueryWrapper=new LambdaQueryWrapper<>();
			 lambdaQueryWrapper.eq(FdContractClass::getDelFlag,"0");
			 lambdaQueryWrapper.orderByAsc(FdContractClass::getCode);
			 List<FdContractClass> list = fdContractClassService.list(lambdaQueryWrapper);
			 List<FdContractClassTree> treeLists=new ArrayList<FdContractClassTree>();
			 getTreeList(treeLists,list,null);
			 findLeaf(treeLists);
			 result.setResult(treeLists);
		 }catch (Exception e){
			 e.fillInStackTrace();
		 }
		 return  result;
	 }

	 private void getTreeList(List<FdContractClassTree> treeList, List<FdContractClass> fdlist, FdContractClassTree temp) {
	 	 int i = 0;
		 for (FdContractClass bmSupplierClass : fdlist) {
			 String tempPid = bmSupplierClass.getParentId();
			 FdContractClassTree tree = new FdContractClassTree(bmSupplierClass);
			 if(temp == null) {
				 if(oConvertUtils.isEmpty(tempPid)){
					 treeList.add(tree);
				 }
				 if(!tree.getIsLeaf()) {
					 getTreeList(treeList, fdlist, tree);
				 }
			 }else if(tempPid != null && tempPid.equals(temp.getKey())){
				 temp.getChildren().add(tree);
				 if(!tree.getIsLeaf()) {
					 getTreeList(treeList, fdlist, tree);
				 }
			 }

		 }
	 }

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

	 }

	/**
	  *   添加
	 * @param fdContractClass
	 * @return
	 */
	@PostMapping(value = "/add")
	@NotDuplicate
	@RequiresPermissions(value = {"contract-class:add","contract-class-parent:add"},logical = Logical.OR)
	public Result<FdContractClass> add(@RequestBody @Valid FdContractClass fdContractClass, BindingResult bindingResult) {
		Result<FdContractClass> result = new Result<FdContractClass>();
		try {
			StringBuilder sb = new StringBuilder();
			if (bindingResult.hasErrors()){
				//记录错误信息
				bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
				result.error500(sb.toString());
				return result;
			}
			//查询是否有同样编码
			LambdaQueryWrapper<FdContractClass> contractClassLambdaQueryWrapper=new LambdaQueryWrapper<>();
			contractClassLambdaQueryWrapper.eq(FdContractClass::getCode,fdContractClass.getCode());
			contractClassLambdaQueryWrapper.eq(FdContractClass::getDelFlag,"0");
			List<FdContractClass> contractClassList=fdContractClassService.list(contractClassLambdaQueryWrapper);
			if(contractClassList.size()>0){
				throw new RuntimeException("编码不能重复");
			}
			fdContractClass.setDelFlag(CommonConstant.DEL_FLAG_0.toString());
			fdContractClassService.save(fdContractClass);
			father();
			result.success("添加成功！");
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			result.error500("操作失败:"+e.getMessage());

		}
		return result;
	}

	 /**
	  * @Author 谭吉
	  * @Description //TODO 判断是否存在父级
	  * @Date 9:54 2019/5/8
	  * @Param []
	  * @return void
	  **/
	 public  void father(){
		 List<FdContractClass> list=fdContractClassService.list();
		 for (FdContractClass fdContractClass: list) {
			 if (oConvertUtils.isNotEmpty(fdContractClass.getParentId()) == true) {
				 fdContractClass.setParentIds(fdContractClass.getId()+","+fdContractClass.getParentId());
				 fdContractClassService.updateById(fdContractClass);
			 }
		 }
	 }
	
	/**
	  *  编辑
	 * @param fdContractClass
	 * @return
	 */
	@PutMapping(value = "/edit")
	@NotDuplicate
	@RequiresPermissions("contract-class:update")
	public Result<FdContractClass> edit(@RequestBody @Valid FdContractClass fdContractClass, BindingResult bindingResult) {
		Result<FdContractClass> result = new Result<FdContractClass>();
		FdContractClass fdContractClassEntity = fdContractClassService.getById(fdContractClass.getId());
		if(fdContractClassEntity==null) {
			result.error500("未找到对应实体");
		}else {
			StringBuilder sb = new StringBuilder();
			if (bindingResult.hasErrors()){
				//记录错误信息
				bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
				result.error500(sb.toString());
				return result;
			}
			boolean ok = fdContractClassService.updateById(fdContractClass);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}
		
		return result;
	}

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

		 return result;
	 }
	
	/**
	 * @Author 谭吉
	 * @Description //TODO 删除单个或多个
	 * @Date 14:09 2019/5/13
	 * @Param [ids]
	 * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.basedata.entity.FdContractClass>
	 **/
	@DeleteMapping(value = "/deleteBatch")
	public Result<FdContractClass> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<FdContractClass> result = new Result<FdContractClass>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			List list = Arrays.asList(ids.split(","));
			FdContractClass fdContractClass = null;
			Collection<FdContractClass> collectionList = new ArrayList<>();
			for (int i = 0; i < list.size(); i++){
				fdContractClass=new FdContractClass();
				fdContractClass.setId(list.get(i).toString());
				collectionList.add(fdContractClass);
			}
			for ( FdContractClass fdContractClasse : collectionList) {
				fdContractClasse.setDelFlag(CommonConstant.DEL_FLAG_1.toString());
				fdContractClassService.updateById(fdContractClasse);
			}
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<FdContractClass> queryById(@RequestParam(name="id",required=true) String id) {
		Result<FdContractClass> result = new Result<FdContractClass>();
		FdContractClass fdContractClass = fdContractClassService.getById(id);
		if(fdContractClass==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(fdContractClass);
			result.setSuccess(true);
		}
		return result;
	}

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

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

}
