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 com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
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.FdCustomer;
import org.jeecg.modules.basedata.entity.FdCustomerContacts;
import org.jeecg.modules.basedata.service.IFdCustomerContactsService;
import org.jeecg.modules.basedata.service.IFdCustomerService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.projectManagement.entity.FdProjectQuotation;
import org.jeecg.modules.projectManagement.service.IFdProjectQuotationService;
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.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-05
 * @version： V1.0
 */
@RestController
@RequestMapping("/basedata/fdCustomer")
@Slf4j
public class FdCustomerController {
	@Autowired
	private IFdCustomerService fdCustomerService;

	@Autowired
	private IFdCustomerContactsService fdCustomerContactsService;

	@Autowired
	private ISysSerialPatternService iSysSerialPatternService;

	@Autowired
	private IFdProjectQuotationService iFdProjectQuotationService;

	/**
	 * @Author 谭吉
	 * @Description //TODO 分页连接查询
	 * @Date 12:01 2019/5/8
	 * @Param [fdCustomer, pageNo, pageSize]
	 * @return org.jeecg.common.api.vo.Result<com.baomidou.mybatisplus.core.metadata.IPage<org.jeecg.modules.basedata.entity.FdCustomer>>
	 **/
	@GetMapping(value = "/list")

	public Result<IPage<FdCustomer>> custonerPageList(FdCustomer fdCustomer,
													   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													   HttpServletRequest req) {
		Result<IPage<FdCustomer>> result = new Result<IPage<FdCustomer>>();
		//客户名称
		String name=fdCustomer.getName();
		if(fdCustomer.getName()!=null&&fdCustomer.getName()!=""){
			fdCustomer.setName(null);
		}
		//客户编码
		String code=fdCustomer.getCode();
		if(fdCustomer.getCode()!=null&&fdCustomer.getCode()!=""){
			fdCustomer.setCode(null);
		}
		//客户缩写
		String abbreviation=fdCustomer.getAbbreviation();
		if(StringUtils.isNotBlank(abbreviation)){
			fdCustomer.setAbbreviation(null);
		}
		// if(StringUtils.isNotBlank(fdCustomer.getAbbreviation())) {
		// 	fdCustomer.setAbbreviation("*"+fdCustomer.getAbbreviation()+"*");
		// }
		// if(StringUtils.isNotBlank(fdCustomer.getName())) {
		// 	fdCustomer.setName("*"+fdCustomer.getName()+"*");
		// }
		// String address = fdCustomer.getAddress();
		// if(StringUtils.isNotBlank(fdCustomer.getAddress())) {
		// 	fdCustomer.setAddress("*"+fdCustomer.getAddress()+"*");
		// }
		QueryWrapper<FdCustomer> queryWrapper = QueryGenerator.initQueryWrapper(fdCustomer, req.getParameterMap());
		Page<FdCustomer> page = new Page<FdCustomer>(pageNo, pageSize);
		queryWrapper.eq("f.del_flag","0");
		queryWrapper.eq("fs.is_default","1");
		if(name!=null&&name!="") {
			queryWrapper.like("f.name",name);
		}
		if(StringUtils.isNotBlank(code)) {
			queryWrapper.like("f.code",code);
		}
		if(StringUtils.isNotBlank(abbreviation)){
			queryWrapper.like("f.abbreviation",abbreviation);
		}
		// if(StringUtils.isNotBlank(fdCustomer.getContactPsn())) {
		// 	queryWrapper.eq("fs.contact_psn","*"+fdCustomer.getContactPsn()+"*");
		// }
		// if(StringUtils.isNotBlank(address)) {
		// 	queryWrapper.eq("f.address","*"+address+"*");
		// }
		queryWrapper.orderByDesc("f.create_time");
		IPage<FdCustomer> pageList = fdCustomerService.findByPage(page,queryWrapper);
		result.setResult(pageList);
		result.setSuccess(true);
		return result;
	}



     /**
      * @Author 谭吉
      * @Description //TODO 分页连接查询(带权限)
      * @Date 12:01 2019/5/8
      * @Param [fdCustomer, pageNo, pageSize]
      * @return org.jeecg.common.api.vo.Result<com.baomidou.mybatisplus.core.metadata.IPage<org.jeecg.modules.basedata.entity.FdCustomer>>
      **/
     @GetMapping(value = "/list1")
	 @RequiresPermissions("url:customer:view")
     public Result<IPage<FdCustomer>> custonerPageList1(FdCustomer fdCustomer,
                                                       @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                       @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                       HttpServletRequest req) {
         Result<IPage<FdCustomer>> result = new Result<IPage<FdCustomer>>();
         //客户名称
         String name=fdCustomer.getName();
         if(fdCustomer.getName()!=null&&fdCustomer.getName()!=""){
             fdCustomer.setName(null);
         }
         //客户编码
         String code=fdCustomer.getCode();
         if(fdCustomer.getCode()!=null&&fdCustomer.getCode()!=""){
             fdCustomer.setCode(null);
         }
		 //客户缩写
		 String abbreviation=fdCustomer.getAbbreviation();
		 if(StringUtils.isNotBlank(abbreviation)){
			 fdCustomer.setAbbreviation(null);
		 }
         QueryWrapper<FdCustomer> queryWrapper = QueryGenerator.initQueryWrapper(fdCustomer, req.getParameterMap());
         Page<FdCustomer> page = new Page<FdCustomer>(pageNo, pageSize);
         queryWrapper.eq("f.del_flag","0");
         queryWrapper.eq("fs.is_default","1");
         if(name!=null&&name!="") {
             queryWrapper.like("f.name",name);
         }
         if(StringUtils.isNotBlank(code)) {
             queryWrapper.like("f.code",code);
         }
		 if(StringUtils.isNotBlank(abbreviation)){
			 queryWrapper.like("f.abbreviation",abbreviation);
		 }
         queryWrapper.orderByDesc("f.create_time");
         IPage<FdCustomer> pageList = fdCustomerService.findByPage(page,queryWrapper);
         result.setResult(pageList);
         result.setSuccess(true);
         return result;
     }

	 /**
	  * 查询全部客户信息
	  * @param fdCustomer
	  * @return
	  */
	 @GetMapping(value = "/getCustomerListAll")
     public Result<List<FdCustomer>> getCustomerListAll(FdCustomer fdCustomer){
     	Result<List<FdCustomer>> result=new Result<>();
		 try {
		 	 LambdaQueryWrapper<FdCustomer> lambdaQueryWrapper=new LambdaQueryWrapper<>();
		 	 lambdaQueryWrapper.eq(FdCustomer::getDelFlag,"0");
		 	 lambdaQueryWrapper.orderByDesc(FdCustomer::getCreateTime);
			 List<FdCustomer> fdCustomerList=fdCustomerService.list(lambdaQueryWrapper);
			 result.success("操作成功");
			 result.setResult(fdCustomerList);
		 } catch (Exception e) {
			 e.printStackTrace();
			 result.error500("操作失败："+e.getMessage());
		 }
		return result;
	 }

	/**
	  *   添加
	 * @param fdCustomer
	 * @return
	 */
	@PostMapping(value = "/add")
	@NotDuplicate
	@RequiresPermissions(value = {"customer:add","url:pm-quotation:view","url:pm-macromolecule:view"},logical = Logical.OR)
	public Result<FdCustomer> add(@RequestBody @Valid FdCustomer fdCustomer, BindingResult bindingResult) {
		Result<FdCustomer> result = new Result<FdCustomer>();
		try {
			StringBuilder sb = new StringBuilder();
			if (bindingResult.hasErrors()){
				//记录错误信息
				bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
				result.error500(sb.toString());
				return result;
			}
			// fdCustomer.setCode(resultSerial.getContent());

			//新增才执行
			if(StringUtils.isEmpty(fdCustomer.getId())){
				fdCustomer.setDelFlag(CommonConstant.DEL_FLAG_0.toString());
				//根据名称查询是否存在
				LambdaQueryWrapper<FdCustomer> queryWrapper=new LambdaQueryWrapper<>();
				queryWrapper.eq(FdCustomer::getName,fdCustomer.getName());
				queryWrapper.eq(FdCustomer::getDelFlag,"0");
				List<FdCustomer> fdCustomerList=fdCustomerService.list(queryWrapper);
				if(!fdCustomerList.isEmpty()&&fdCustomerList.size()>0){
					result.error500("客户名称已存在");
					return result;
				}
//				LambdaQueryWrapper<FdCustomer> queryWrapper2=new LambdaQueryWrapper<>();
//				queryWrapper2.eq(FdCustomer::getDelFlag,"0");
//				queryWrapper2.eq(FdCustomer::getAbbreviation,fdCustomer.getAbbreviation());
//				List<FdCustomer> fdCustomerList2=fdCustomerService.list(queryWrapper2);
//				if(!fdCustomerList2.isEmpty()&&fdCustomerList2.size()>0){
//					result.error500("客户缩写已存在");
//					return result;
//				}
			}

			fdCustomerService.saveCustomer(fdCustomer);
			result.success("添加成功！");
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			result.error500("操作失败:"+e.getMessage());
		}
		return result;
	}

	/**
	* @Author chenchuang
	* @Description //TODO 查询是否存在同样的客户缩写
	* @Date 2020/7/17 15:25
	* @Param [fdCustomer]
	* @return org.jeecg.common.api.vo.Result<org.jeecg.modules.basedata.entity.FdCustomer>
	*/
	@GetMapping(value = "/isAbbreviation")
	public Result<FdCustomer> isAbbreviation(FdCustomer fdCustomer){
		Result result=new Result();
		FdCustomer fdCustomerResult=new FdCustomer();
		//通过缩写查询客户
		LambdaQueryWrapper<FdCustomer> queryWrapper2=new LambdaQueryWrapper<>();
		queryWrapper2.eq(FdCustomer::getDelFlag,"0");
		queryWrapper2.eq(FdCustomer::getAbbreviation,fdCustomer.getAbbreviation());
		queryWrapper2.orderByDesc(FdCustomer::getCreateTime);
		List<FdCustomer> fdCustomerList2=fdCustomerService.list(queryWrapper2);
		//是否有数据
		if(fdCustomerList2!=null&&fdCustomerList2.size()>0){
			//则存在当前的客户缩写
			fdCustomerResult.setIsAbbreviation("2");
			fdCustomerResult.setFdCustomerList(fdCustomerList2);
		}
		result.setResult(fdCustomerResult);
		return result;
	}

	/**
	  *  编辑
	 * @param fdCustomer
	 * @return
	 */
	@PutMapping(value = "/edit")
	@NotDuplicate
	@RequiresPermissions(value = {"customer:update","url:pm-quotation:view","url:pm-macromolecule:view"},logical = Logical.OR)
	public Result<List<FdCustomerContacts>> edit(@RequestBody @Valid FdCustomer fdCustomer, BindingResult bindingResult) {
		Result<List<FdCustomerContacts>> result = new Result<List<FdCustomerContacts>>();
		FdCustomer fdCustomerEntity = fdCustomerService.getById(fdCustomer.getId());
		if(fdCustomerEntity==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 = fdCustomerService.updateById(fdCustomer);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}

		return result;
	}

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

         return result;
     }

	/**
	 * @Author 谭吉
	 * @Description //TODO	单个或多个删除
	 * @Date 14:06 2019/5/13
	 * @Param [ids]
	 * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.basedata.entity.FdCustomer>
	 **/
	@DeleteMapping(value = "/deleteBatch")
	@NotDuplicate
	@RequiresPermissions("customer:delete")
	public Result<FdCustomer> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<FdCustomer> result = new Result<FdCustomer>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			List list = Arrays.asList(ids.split(","));
			FdCustomer fdCustomer = null;
			List<FdCustomerContacts> fdCustomerContactsList = new ArrayList<>();
			LambdaQueryWrapper<FdCustomerContacts> lambdaQueryWrapper=new LambdaQueryWrapper<>();
			List<FdCustomer> collectionList = new ArrayList<>();
			for (int i = 0; i < list.size(); i++){
				fdCustomer=new FdCustomer();
				fdCustomer.setId(list.get(i).toString());
				collectionList.add(fdCustomer);
			}
			for ( FdCustomer fdCustomers : collectionList) {
				fdCustomers.setDelFlag(CommonConstant.DEL_FLAG_1.toString());
				//	获取客户ID查询出关联的联系人ID在进行删除
				lambdaQueryWrapper.eq(FdCustomerContacts::getPkCustomerId,fdCustomer.getId());
				fdCustomerContactsList = fdCustomerContactsService.list(lambdaQueryWrapper);
				for ( FdCustomerContacts fdCustomerContacts : fdCustomerContactsList) {
					fdCustomerContacts.setDelFlag(CommonConstant.DEL_FLAG_1.toString());
					fdCustomerContactsService.updateById(fdCustomerContacts);
				}
				fdCustomerService.updateById(fdCustomers);
			}
			result.success("删除成功!");
		}
		return result;
	}

	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<FdCustomer> queryById(@RequestParam(name="id",required=true) String id) {
		Result<FdCustomer> result = new Result<FdCustomer>();
		FdCustomer fdCustomer = fdCustomerService.getById(id);
		if(fdCustomer==null) {
			result.error500("未找到对应实体");
		}else {
            LambdaQueryWrapper<FdCustomerContacts> query = new LambdaQueryWrapper<>();
            query.eq(FdCustomerContacts::getPkCustomerId,id);
            query.eq(FdCustomerContacts::getIsDefault,"1").eq(FdCustomerContacts::getDelFlag,"0");
            List<FdCustomerContacts> fdCustomerContactsList = fdCustomerContactsService.list(query);
            for ( FdCustomerContacts fdCustomerContacts : fdCustomerContactsList ) {
                fdCustomer.setContacts(fdCustomerContacts.getContactPsn());
                fdCustomer.setTelephone(fdCustomerContacts.getContectTel());
                fdCustomer.setEmail(fdCustomerContacts.getEmail());
            }
			result.setResult(fdCustomer);
			result.setSuccess(true);
		}
		return result;
	}

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

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<FdCustomer> pageList = fdCustomerService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "客户档案列表");
      mv.addObject(NormalExcelConstants.CLASS, FdCustomer.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<FdCustomer> listFdCustomers = ExcelImportUtil.importExcel(file.getInputStream(), FdCustomer.class, params);
              for (FdCustomer fdCustomerExcel : listFdCustomers) {
                  fdCustomerService.save(fdCustomerExcel);
              }
              return Result.ok("文件导入成功！数据行数：" + listFdCustomers.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 chenchuang
  * @Description //TODO 根据客户id查询报价是否有对应的客户
  * @Date 2020/8/19 15:55
  * @Param [id]
  * @return org.jeecg.common.api.vo.Result<java.lang.Boolean>
  */
  @GetMapping(value = "/getProjectIsCustomer")
  public Result<Boolean> getProjectIsCustomer(String id){
  	Result<Boolean> result=new Result<>();
	  try {
	  	//根据客户查询报价数据
		  LambdaQueryWrapper<FdProjectQuotation> lambdaQueryWrapper=new LambdaQueryWrapper<>();
		  lambdaQueryWrapper.eq(FdProjectQuotation::getPkCustomerId,id);
		  lambdaQueryWrapper.eq(FdProjectQuotation::getDelFlag,"0");
		  List<FdProjectQuotation> fdProjectQuotationList=iFdProjectQuotationService.list(lambdaQueryWrapper);
		  //如果有则不能被删除
		  if(fdProjectQuotationList!=null&&fdProjectQuotationList.size()>0){
              result.setResult(true);
          }else{
              result.setResult(false);
          }
	  } catch (Exception e) {
		  e.printStackTrace();
		  result.error500("操作失败："+e.getMessage());
	  }
	  return result;
  }

}
