/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workclientinfo.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.beanvalidator.BeanValidators;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.mapper.JsonMapper;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.TicketQueryUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysimportinfo.entity.SysImportInfo;
import com.jeeplus.modules.sysimportinfo.service.SysImportInfoService;
import com.jeeplus.modules.workclientinfo.entity.*;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
import com.jeeplus.modules.workclientinfo.entity.WorkClientInfo;
import com.jeeplus.modules.workclientinfo.entity.WorkClientLinkman;
import com.jeeplus.modules.workclientinfo.service.WorkClientInfoService;
import com.jeeplus.modules.workreimbursement.utils.VarStr;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.*;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户管理Controller
 * @author 丁旭
 * @version 2017-03-20
 */
@Controller
@RequestMapping(value = "${adminPath}/workclientinfo/workClientInfo")
public class WorkClientInfoController extends BaseController {

	@Autowired
	private WorkClientInfoService workClientInfoService;
	@Autowired
	private SysImportInfoService sysImportInfoService;


	@Autowired
	private HttpServletRequest request;

	@ModelAttribute
	public WorkClientInfo get(@RequestParam(required=false) String id) {
		WorkClientInfo entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workClientInfoService.get(id);
		}
		if (entity == null){
			entity = new WorkClientInfo();
		}
		return entity;
	}
	
	/**
	 * 客户管理列表页面
	 */
	@RequiresPermissions("workclientinfo:workClientInfo:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkClientInfo workClientInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
		WorkClientLinkman workClientLinkman = workClientInfo.getWorkClientLinkman();
		if(workClientLinkman != null){
			workClientLinkman.setId("");
		}
		workClientInfo.setWorkClientLinkman(workClientLinkman);
		if(UserUtils.isManager()){
			model.addAttribute("flag","1");
		}
		Page<WorkClientInfo> page = workClientInfoService.findPage(new Page<WorkClientInfo>(request, response), workClientInfo);
		model.addAttribute("page", page);
		return "modules/workclientinfo/workClientInfoList";
	}

	/**
	 * 查看，增加，编辑客户管理表单页面
	 */
	@RequiresPermissions(value={"workclientinfo:workClientInfo:view","workclientinfo:workClientInfo:add","workclientinfo:workClientInfo:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkClientInfo workClientInfo, Model model) {
		model.addAttribute("workClientInfo", workClientInfo);
		return "modules/workclientinfo/workClientInfoForm";
	}

    /**
     * 查看，增加，编辑客户管理表单页面
     */
    @RequiresPermissions(value={"workclientinfo:workClientInfo:view","workclientinfo:workClientInfo:add","workclientinfo:workClientInfo:edit"},logical=Logical.OR)
    @RequestMapping(value = "detail")
    public String detail(WorkClientInfo workClientInfo, Model model) {
        model.addAttribute("workClientInfo", workClientInfo);
        model.addAttribute("bankSize",workClientInfo.getWorkClientBankList().size());
        model.addAttribute("linkManSize",workClientInfo.getWorkClientLinkmanList().size());
        model.addAttribute("attachmentSize",workClientInfo.getWorkAttachments().size());
        return "modules/workclientinfo/workClientInfoFormDetail";
    }

	/**
	 * 保存客户管理
	 */
	@RequiresPermissions(value={"workclientinfo:workClientInfo:add","workclientinfo:workClientInfo:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkClientInfo workClientInfo,
                       Model model, RedirectAttributes redirectAttributes,
//					   @RequestParam(value = "upload_files") MultipartFile[] upload_files.
                       HttpServletRequest request
                        ) throws Exception{
		if (!beanValidator(model, workClientInfo)){
			return form(workClientInfo, model);
		}

		//上传文件
//		List<WorkClientAttachment> workClientAttachments = workClientInfoService.uploadFile(request, upload_files, workClientInfo.getId(), VarStr.attachmentFlag[0]);
//		List<WorkClientAttachment> workClientAttachmentList = workClientInfo.getWorkClientAttachmentList();
//		workClientAttachments.addAll(workClientAttachmentList);
//		workClientInfo.setWorkClientAttachmentList(workClientAttachments);

		//保存当前人的公司
		workClientInfo.setCompanyId(UserUtils.getSelectCompany().getId());
		workClientInfo.setOfficeId(UserUtils.getSelectOffice().getId());
        if(!workClientInfo.getIsNewRecord()){//编辑表单保存
			WorkClientInfo t = workClientInfoService.get(workClientInfo.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workClientInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workClientInfoService.save(t);//保存
		}else{//新增表单保存
			workClientInfoService.save(workClientInfo);//保存
		}
		addMessage(redirectAttributes, "保存客户管理成功");
		return "redirect:"+Global.getAdminPath()+"/workclientinfo/workClientInfo/?repage";
	}

	/**
	 * 合同新增客户管理
	 */
	@RequestMapping(value = "contractsave")
	@ResponseBody
	public HashMap<Object,Object> contractsave(WorkClientInfo workClientInfo,
                       Model model, RedirectAttributes redirectAttributes,
                       HttpServletRequest request
                        ) throws Exception{
		HashMap<Object, Object> map = Maps.newHashMap();
		try {
			//保存当前人的公司
			workClientInfo.setCompanyId(UserUtils.getSelectCompany().getId());
			workClientInfo.setOfficeId(UserUtils.getSelectOffice().getId());
			if(!workClientInfo.getIsNewRecord()){//编辑表单保存
				WorkClientInfo t = workClientInfoService.get(workClientInfo.getId());//从数据库取出记录的值
				MyBeanUtils.copyBeanNotNull2Bean(workClientInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
				workClientInfoService.save(t);//保存
				map.put("str","修改成功");
			}else{//新增表单保存
				workClientInfoService.save(workClientInfo);//保存
				map.put("str","新增成功");
			}
			map.put("id",workClientInfo.getId());
			map.put("name",workClientInfo.getName());
			map.put("companyType", DictUtils.getMainDictLabel(workClientInfo.getCompanyType(),"company_type",""));
			map.put("companyIndustry", DictUtils.getMainDictLabel(workClientInfo.getCompanyIndustry(),"company_industry",""));
			if(workClientInfo.getArea()!=null){
				map.put("areaName",workClientInfo.getArea().getName());
			}
			map.put("msg","true");
		}catch (Exception e){
			map.put("id",workClientInfo.getId());
			map.put("msg","false");
		}
		return  map;
	}

	@RequestMapping(value = "getRow")
	@ResponseBody
	public String getPNumberr() {
		HashMap<Object, Object> map = Maps.newHashMap();
		String obj = request.getParameter("obj");
		WorkClientInfo workClientInfo = workClientInfoService.get(obj);
		map.put("id",workClientInfo.getId());
		map.put("name",workClientInfo.getName());
		map.put("companyType", DictUtils.getMainDictLabel(workClientInfo.getCompanyType(),"company_type",""));

		map.put("companyIndustry", DictUtils.getMainDictLabel(workClientInfo.getCompanyIndustry(),"company_industry",""));
		if(workClientInfo.getArea()!=null){
			map.put("areaName",workClientInfo.getArea().getName());
		}
		return JsonMapper.toJsonString(map);
	}

	/**
	 * 删除客户管理(被引用过的客户信息不可以被删除，但可以修改。 没有被引用过的客户信息可以删除)
	 */
	@RequiresPermissions("workclientinfo:workClientInfo:del")
	@RequestMapping(value = "delete")
	public String delete(WorkClientInfo workClientInfo, RedirectAttributes redirectAttributes) {

		if(!workClientInfoService.getUsedCount(workClientInfo)){
			workClientInfoService.delete(workClientInfo);
			addMessage(redirectAttributes, "删除客户成功");
		}else{
			addMessage(redirectAttributes,"该客户已经被其他模块引用，删除失败");
		}
		return "redirect:"+Global.getAdminPath()+"/workclientinfo/workClientInfo/?repage";
	}
	
	/**
	 * 批量删除客户管理
	 */
	@RequiresPermissions("workclientinfo:workClientInfo:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workClientInfoService.delete(workClientInfoService.get(id));
		}
		addMessage(redirectAttributes, "删除客户管理成功");
		return "redirect:"+Global.getAdminPath()+"/workclientinfo/workClientInfo/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workclientinfo:workClientInfo:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkClientInfo workClientInfo, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "客户管理"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			if(!"1".equals(UserUtils.getSelectCompany().getId())){
				workClientInfo.setCompanyId(UserUtils.getSelectCompany().getId());
			}
            Page<WorkClientInfo> page = workClientInfoService.findPage(new Page<WorkClientInfo>(request, response, -1), workClientInfo);
    		new ExportExcel(true,"客户管理", WorkClientInfo.class,1).setDataList(true,page.getList()).write(response, fileName,request.getHeader("USER-AGENT")).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出客户管理记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workclientinfo/workClientInfo/?repage";
    }

	/**
	 * 导入Excel数据
	 */
	@RequiresPermissions("workclientinfo:workClientInfo:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			String date = DateUtils.getDate("yyyyMMddHHmmss");
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
//			List<WorkClientInfo> list = ei.getDataList(WorkClientInfo.class);
			List<WorkClientInfo> list = ei.getDataList(WorkClientInfo.class);
			List<WorkClientInfo> errlist = new ArrayList<>();
			for (WorkClientInfo workClientInfo : list){
				try{
					String validator = beanValidatorImport(workClientInfo);
					if (StringUtils.isNotBlank(validator)){
						failureMsg.append("<br/>"+validator+"!");
						failureNum++;
						workClientInfo = toWorkClientInfo(workClientInfo,date,validator);
						errlist.add(workClientInfo);
					}else if (StringUtils.isBlank(workClientInfo.getOurBank())){
						failureMsg.append("<br/>开户银行为空; ");
						failureNum++;
						workClientInfo = toWorkClientInfo(workClientInfo,date,"开户银行为空!");
						errlist.add(workClientInfo);
					}else if (StringUtils.isBlank(workClientInfo.getBankNumber())){
						failureMsg.append("<br/>开户账号为空; ");
						failureNum++;
						workClientInfo = toWorkClientInfo(workClientInfo,date,"开户账号为空!");
						errlist.add(workClientInfo);
					}else if (StringUtils.isBlank(workClientInfo.getLinkname())){
						failureMsg.append("<br/>联系人姓名为空; ");
						failureNum++;
						workClientInfo = toWorkClientInfo(workClientInfo,date,"联系人姓名为空!");
						errlist.add(workClientInfo);
					}else if (StringUtils.isNotBlank(workClientInfo.getUscCode())&&"false".equals(this.checkUscCode(workClientInfo.getUscCode(),""))){
                        failureMsg.append("<br/>重复的统一社会信用代码; ");
                        failureNum++;
                        workClientInfo = toWorkClientInfo(workClientInfo,date,"重复的统一社会信用代码!");
                        errlist.add(workClientInfo);
                    }else {
						workClientInfo.setCompanyId(UserUtils.getSelectCompany().getId());
						workClientInfo.setOfficeId(UserUtils.getSelectOffice().getId());
						workClientInfo.convertClientType();
						List<WorkClientLinkman> linkmanList = Lists.newArrayList();
						workClientInfo.setWorkClientLinkmanList(linkmanList);
						WorkClientLinkman workClientLinkman = new WorkClientLinkman();
						workClientLinkman.setName(workClientInfo.getLinkname());
						workClientLinkman.setEmail(workClientInfo.getLinkemail());
						workClientLinkman.setPosition(workClientInfo.getPosition());
						workClientLinkman.setQq(workClientInfo.getQq());
						workClientLinkman.setLinkPhone(workClientInfo.getLinkPhone());
						workClientLinkman.setLinkMobile(workClientInfo.getLinkMobile());
						linkmanList.add(workClientLinkman);
						List<WorkClientBank> workClientBankList = Lists.newArrayList();
						WorkClientBank workClientBank = new WorkClientBank();
						workClientBank.setBankNumber(workClientInfo.getBankNumber());
						workClientBank.setOurBank(workClientInfo.getOurBank());
						workClientBankList.add(workClientBank);
						workClientInfo.setWorkClientBankList(workClientBankList);
						workClientInfoService.saveImport(workClientInfo);
						successNum++;
					}
				}catch(ConstraintViolationException ex){
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
					workClientInfo = toWorkClientInfo(workClientInfo,date,"导入失败!");
					errlist.add(workClientInfo);
				}catch (Exception ex) {
					logger.info("Exception ex"+ex);
					workClientInfo = toWorkClientInfo(workClientInfo,date,ex+"!");
					failureNum++;
					errlist.add(workClientInfo);
					failureMsg.append(ex+"!");
				}
			}
			SysImportInfo sysImportInfo = new SysImportInfo();
			sysImportInfo.setCompanyId(UserUtils.getSelectCompany().getId());
			sysImportInfo.setOfficeId(UserUtils.getSelectOffice().getId());
			sysImportInfo.setModular("1");
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 个错误信息记录。");
				ExportExcel exportExcel= new ExportExcel(false,"客户信息数据", WorkClientInfo.class, 1).setDataList(errlist);
				OSSClientUtil ossUtil = new OSSClientUtil();

				String fileName=date+"客户信息错误导入日志.xlsx";
				String fileDir = "importInfo/workClintInfoImport/";
				fileDir = fileDir+System.nanoTime()+"/";
				try {
					ByteArrayOutputStream os = new ByteArrayOutputStream();
					exportExcel.write(os);
					byte[] content = os.toByteArray();
					InputStream inputStream = new ByteArrayInputStream(content);
					ossUtil.uploadFile2OSS(inputStream,fileDir, fileName);
				}catch (IOException e){
					e.printStackTrace();
				}catch (Exception e1){
					e1.printStackTrace();
					System.out.println("客户信息错误导入日志文件上传失败！");
				}

				String name = Global.getAliyunUrl()+"/"+fileDir+fileName;
				logger.info("name:"+name);
				sysImportInfo.setUrl(name);
				sysImportInfo.setFileName(fileName);
				sysImportInfo.setErrCount(failureNum+"");
				sysImportInfo.setIsTrue("0");
			}else {
				sysImportInfo.setIsTrue("1");
				sysImportInfo.setErrCount("0");
			}
			/*if(errList.size() > 0){
				failureNum = errList.size() + failureNum;
				failureMsg.insert(0, "，失败 "+failureNum+" 条客户管理记录");
			}*/
			String msg = "已成功导入 "+successNum+" 条客户信息记录"+failureMsg;
			String info = "已成功导入 "+successNum+" 条客户信息记录，失败 "+failureNum+" 个错误信息记录。";
			sysImportInfo.setErrInfo(info);
			sysImportInfoService.save(sysImportInfo);
			addMessage(redirectAttributes, msg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入客户信息失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workclientinfo/workClientInfo/?repage";
    }
	
	/**
	 * 下载导入客户管理数据模板
	 */
	@RequiresPermissions("workclientinfo:workClientInfo:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "客户管理数据导入模板.xlsx";
    		List<WorkClientInfo> list = Lists.newArrayList();
    		new ExportExcel(true,"客户管理数据", WorkClientInfo.class, 1).setDataList(list).write(response, fileName,request.getHeader("USER-AGENT")).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workclientinfo/workClientInfo/?repage";
    }

	/**
	 * 查看导入客户管理数据信息
	 */
	//@RequiresPermissions("importInfo:importInfo:importInfoErr")
    @RequestMapping(value = "importInfoErr")
    public String importInfoErr(SysImportInfo sysImportInfo,HttpServletRequest request, HttpServletResponse response, Model model) {
		SysImportInfo importInfo = new SysImportInfo();
		importInfo.setModular("1");
		Page<SysImportInfo> page = sysImportInfoService.findPage(new Page<SysImportInfo>(request, response), importInfo);
		model.addAttribute("page", page);
		model.addAttribute("modular", "1");
		return "modules/sysimportinfo/sysimportinfoList";
    }




	/**
	 * 选择客户的联系人
	 */
	@ResponseBody
	@RequestMapping(value = "selectLinkman")
	public AjaxJson selectLinkman(String clientId, HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxJson j = new AjaxJson();
		if(StringUtils.isBlank(clientId)){
			clientId = "1";
		}
		List<WorkClientLinkman> list = workClientInfoService.findLinkmanList(new WorkClientInfo(clientId));
		j.put("list", list);
		return j;
	}

	/**
	 * 删除附件
	 * @return
	 */
	@RequestMapping("/deleteAttachment")
	public String deleteAttachment(WorkClientInfo workClientInfo,HttpServletRequest request,RedirectAttributes redirectAttributes,Model model){
		String attchmentId = request.getParameter("attchmentId");
		model.addAttribute("workClientInfo",workClientInfo);
		WorkClientAttachment workClientAttachment = new WorkClientAttachment();
		workClientAttachment.setId(attchmentId);
		workClientAttachment.setDelFlag("1");
		String s = workClientInfoService.deleteAttachment(workClientAttachment);
		addMessage(redirectAttributes, s);
		return "modules/workclientinfo/workClientInfoForm";
	}

	/**
	 * 异步上传文件
	 * @return
	 */
	@RequestMapping("/uploadFile")
	@ResponseBody
	public Map<String,Object> uploadFile(WorkClientInfo workClientInfo,
										 Model model, RedirectAttributes redirectAttributes,
										 HttpServletRequest request,
										 @RequestParam(value = "myFile") CommonsMultipartFile myFile){
		String attchmentId = request.getParameter("attchmentId");
		WorkClientAttachment workClientAttachment = workClientInfoService.uploadFileSingle(request, myFile, workClientInfo.getId(), VarStr.attachmentFlag[0]);
		workClientAttachment.setId(attchmentId);
		String s = workClientInfoService.save(workClientAttachment);
//		addMessage(redirectAttributes,s);
//		model.addAttribute("workClientInfo",workClientInfo);
//		model.addAttribute("msg","success");
		Map map = new HashMap();
		map.put("msg","success");
		return map;
	}

	/**
	 * 同步WorkClientInfo
	 * @return
	 */
	public WorkClientInfo toWorkClientInfo(WorkClientInfo workClientInfo, String date , String errInfo){
		workClientInfo.setNowDate(date);
		workClientInfo.setUserName(UserUtils.getUser().getName());
		workClientInfo.setErrInfo(errInfo);
		return workClientInfo;
	}

	@RequestMapping("linkmanList")
	public String queryLinkmanListByClientId(WorkClientLinkman linkman, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, String searchLabel1, String searchKey1, HttpServletRequest request, HttpServletResponse response, Model model){
		Page<WorkClientLinkman> page = workClientInfoService.findLinkmanPage(new Page<WorkClientLinkman>(request, response), linkman);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", linkman);
		model.addAttribute("page", page);
		return  "modules/sys/gridselect1";
	}

	@RequestMapping("clientInfolist")
	public String queryClientInfolist(WorkClientInfo clientInfo, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, String searchLabel1, String searchKey1, HttpServletRequest request, HttpServletResponse response, Model model){
		Page<WorkClientInfo> page = workClientInfoService.findPage(new Page<WorkClientInfo>(request, response), clientInfo);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", clientInfo);
		model.addAttribute("page", page);
		return  "modules/sys/gridselectClientLink";
	}

    @ResponseBody
	@RequestMapping("checkUscCode")
    public String checkUscCode(String uscCode,String oldUscCode){
        if(uscCode!=null&&uscCode.equals(oldUscCode)){
            return "true";
        }else if(uscCode!=null){
            int cou=workClientInfoService.countByUscCode(uscCode);
            if (cou==0){
                return "true";
            }
        }
	    return "false";
    }

    @RequestMapping("selectclientBankinfo")
    public String queryclientBankinfo(WorkClientBank workClientBank, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, String searchLabel1, String searchKey1, HttpServletRequest request, HttpServletResponse response, Model model){
        Page<WorkClientBank> page = workClientInfoService.findBankInfoPage(new Page<WorkClientBank>(request, response), workClientBank);
        try {
            fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
            fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
            searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
            searchKey = URLDecoder.decode(searchKey, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        model.addAttribute("labelNames", fieldLabels.split("\\|"));
        model.addAttribute("labelValues", fieldKeys.split("\\|"));
        model.addAttribute("fieldLabels", fieldLabels);
        model.addAttribute("fieldKeys", fieldKeys);
        model.addAttribute("url", url);
        model.addAttribute("searchLabel", searchLabel);
        model.addAttribute("searchKey", searchKey);
        model.addAttribute("obj", workClientBank);
        model.addAttribute("page", page);
        return  "modules/sys/gridselectClientBankinfo";
    }

	/**
	 * 根据关键字查询相关企业
	 * @param keyword
	 * @return
	 */
	@ResponseBody
	@RequestMapping("enterpriseSearchByName")
	public String enterpriseSearchByName(String keyword){
		if(StringUtils.isBlank(keyword)){
			return null;
		}
		return  TicketQueryUtils.enterpriseSearchByName(keyword);
	}

	/**
	 * 根据id查询企业税号
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("enterpriseTicketInfo")
	public Object enterpriseTicketInfo(String id){
		if(StringUtils.isBlank(id)){
			return null;
		}
		return TicketQueryUtils.enterpriseTicketInfoQueryById(id);
	}

	/**
	 * 无合同，查询公司所有客户及其关联的联系人
	 * @param linkman
	 * @param url
	 * @param fieldLabels
	 * @param fieldKeys
	 * @param searchLabel
	 * @param searchKey
	 * @param searchLabel1
	 * @param searchKey1
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("queryLinkManByCompany")
	public String queryLinkManByCompany(WorkClientLinkman linkman, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, String searchLabel1, String searchKey1, HttpServletRequest request, HttpServletResponse response, Model model){
		WorkClientInfo clientInfo = new WorkClientInfo();
		clientInfo.setCompanyId(UserUtils.getUser().getCompany().getId());
		linkman.setClientId(clientInfo);
		Page<WorkClientLinkman> page = workClientInfoService.queryLinkManPageByCompany(new Page<WorkClientLinkman>(request, response), linkman);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", linkman);
		model.addAttribute("page", page);
		return  "modules/sys/gridselect1";
	}

	@ResponseBody
	@RequestMapping("checkClient")
	public String  checkClient(WorkClientInfo workClientInfo){
       List<WorkClientInfo> workClientInfos = workClientInfoService.findByName(workClientInfo);
       if(workClientInfos != null && workClientInfos.size()>0){
       	   return "false";
	   }
       return "true";
	}

}