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

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.bos.BOSClientUtil;
import com.jeeplus.common.config.Global;
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.IdGen;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
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.entity.Role;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
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.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.modules.workcontractinfo.service.WorkContractInfoService;
import com.jeeplus.modules.workfullmanage.entity.WorkFullManage;
import com.jeeplus.modules.workfullmanage.service.WorkFullConstructService;
import com.jeeplus.modules.workfullmanage.service.WorkFullDesignService;
import com.jeeplus.modules.workfullmanage.service.WorkFullManageService;
import com.jeeplus.modules.workfullmanage.service.WorkFullSurveyService;
import com.jeeplus.modules.workproject.entity.WorkProject;
import com.jeeplus.modules.workproject.service.WorkProjectService;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import org.apache.commons.lang.ArrayUtils;
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.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

/**
 * 全过程管理Controller
 * @author mapengbo
 * @version 2017-10-24
 */
@Controller
@RequestMapping(value = "${adminPath}/workfullmanage/workFullManage")
public class WorkFullManageController extends BaseController {

	@Autowired
	private WorkFullManageService workFullManageService;

	@Autowired
	private WorkClientInfoService workClientInfoService;

	@Autowired
	private WorkProjectService workProjectService;
	@Autowired
	private HttpServletRequest request;

	@Autowired
	private WorkContractInfoService workContractInfoService;

	@Autowired
	private SystemService systemService;

	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;

	@Autowired
	private WorkFullDesignService workFullDesignService;
	@Autowired
	private WorkFullConstructService workFullConstructService;
	@Autowired
	private WorkFullSurveyService workFullSurveyService;

	@ModelAttribute
	public WorkFullManage get(@RequestParam(required=false) String id) {
		WorkFullManage entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workFullManageService.get(id);
		}
		if (entity == null){
			entity = new WorkFullManage();
		}
		return entity;
	}
	
	/**
	 * 项目登记列表页面
	 */
	@RequiresPermissions("workfullmanage:workFullManage:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkFullManage workFullManage, HttpServletRequest request, HttpServletResponse response, Model model) {
		//只是普通员工
		if(!UserUtils.getSelectRoleInfo()){
			String id = UserUtils.getUser().getId();
			workFullManage.setQueryCon(id);
			workFullManage.setMasterId(UserUtils.getUser().getId());
		}
		//添加只查询当前公司的数据
		Page<WorkFullManage> page = workFullManageService.findPage(new Page<WorkFullManage>(request, response), workFullManage);
		model.addAttribute("page", page);
		return "modules/workfullmanage/workFullManageList";
	}

	/**
	 * 查看，增加，编辑项目登记表单页面
	 */
	@RequiresPermissions(value={"workfullmanage:workFullManage:view","workfullmanage:workFullManage:add","workfullmanage:workFullManage:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkFullManage workFullManage, Model model) {
		getSort(workFullManage);
		String view = "workFullManageForm";
		String tabId = request.getParameter("tabId");
		if("0".equals(tabId)){
			view = "workFullManageFormDetail";
		}else if("1".equals(tabId)){
			view = "projectStart";
		}else if("2".equals(tabId)){
			view = "projectPre";
		}else if("3".equals(tabId)){
			view = "workClientInfoAndContractInfoFormDetail";
		}else if("4".equals(tabId)){
			view = "projectStartDetail";
		}else if("5".equals(tabId)){
			view = "projectPreDetail";
		}
		model.addAttribute("workFullManage", workFullManage);
		if(workFullManage.getWorkClientInfo()!=null && workFullManage.getWorkClientInfo().getWorkClientLinkmanList()!=null){
			String linkmanListJson = workFullManageService.parseList2Json(workFullManage.getWorkClientInfo());
			model.addAttribute("linkmanList",linkmanListJson);
		}
		if(workFullManage.getWorkBuildInfo()!=null && workFullManage.getWorkBuildInfo().getWorkClientLinkmanList()!=null){
			String buildLinkmanListJson = workFullManageService.parseList2Json(workFullManage.getWorkBuildInfo());
			model.addAttribute("build_linkmanList",buildLinkmanListJson);
		}
		return "modules/workfullmanage/"+view;
	}

	/**
	 * 保存项目登记
	 */
	@RequiresPermissions(value={"workfullmanage:workFullManage:add","workfullmanage:workFullManage:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkFullManage workFullManage,
					   Model model,
//					   @RequestParam("upload_files") MultipartFile[] upload_files,
					   RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workFullManage)){
			return form(workFullManage, model);
		}

		if(workFullManage != null){
			if(!Strings.isNullOrEmpty(workFullManage.getTotalFullId())){
				WorkFullManage wc = workFullManageService.get(workFullManage.getTotalFullId());
				String isTotal = wc.getIsTotal();
				int count = 2;
				if (StringUtils.isNotBlank(isTotal)){
					count = Integer.parseInt(isTotal) + 1;
				}
				workFullManage.setIsTotal(count+"");
				workFullManage.setIsTotalName(toChinese(count+"")+"级项目");
				if(!Strings.isNullOrEmpty(wc.getTotalFullIds())){
					workFullManage.setTotalFullIds(wc.getTotalFullIds()+","+workFullManage.getTotalFullId());
				}else{
					workFullManage.setTotalFullIds(wc.getTotalFullIds()+","+workFullManage.getTotalFullId());
				}
				workFullManage.setCommonFlag(wc.getCommonFlag());
			}else{
				workFullManage.setIsTotal("1");
				workFullManage.setTotalFullId("0");
				workFullManage.setIsTotalName("总项目");
				workFullManage.setCommonFlag(IdGen.uuid());
			}
		}
		getSort(workFullManage);
		String masterId = "";
		if(!Strings.isNullOrEmpty(workFullManage.getHostMaster())){
			String[] split = workFullManage.getHostMaster().split(",");
			//主办负责人的部门负责人编号
			masterId += workFullManageService.getPeopleMaster(split) + ",";
		}
		if(!Strings.isNullOrEmpty(workFullManage.getFollowMaster())){
			String[] split1 = workFullManage.getFollowMaster().split(",");
			masterId += workFullManageService.getPeopleMaster(split1) + ",";
		}
		if(!Strings.isNullOrEmpty(workFullManage.getHostMember())){
			String[] split2 = workFullManage.getHostMember().split(",");
			masterId += workFullManageService.getPeopleMaster(split2) + ",";
		}
		if(!Strings.isNullOrEmpty(workFullManage.getFollowMember())){
			String[] split3 = workFullManage.getFollowMember().split(",");
			masterId += workFullManageService.getPeopleMaster(split3);
		}
		workFullManage.setMasterId(masterId);
		workFullManage.setOfficeId(UserUtils.getSelectOffice().getId());
		if(!workFullManage.getIsNewRecord()){//编辑表单保存
			WorkFullManage t = workFullManageService.get(workFullManage.getId());//从数据库取出记录的值
			//修改 判断当前人是否是项目登记人和项目负责人
			/*String currentUser = UserUtils.getUser().getId(); //当前登录人
			if(t.getHostMaster().indexOf(currentUser) == -1 && !workFullManage.getCreateBy().getId().equals(currentUser)){
				addMessage(redirectAttributes, "对不起，您没有权限操作！！！");
				return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullManage/?repage";
			}*/
			MyBeanUtils.copyBeanNotNull2Bean(workFullManage, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			//上传文件
//			List<WorkClientAttachment> workClientAttachments = workClientInfoService.uploadFile(request, upload_files, workFullManage.getId(), VarStr.attachmentFlag[2]);
//			List<WorkClientAttachment> workClientAttachmentList = workFullManage.getWorkClientAttachmentList();
//			workClientAttachments.addAll(workClientAttachmentList);
//			workFullManage.setWorkClientAttachmentList(workClientAttachments);


			WorkProject workProject = workProjectService.get(t.getWorkProject().getId());
			workProject.setName(t.getFullProjectName());
			workProject.setUpdateBy(t.getUpdateBy());
			workProject.setUpdateDate(t.getUpdateDate());
			workProjectService.update(workProject);//保存项目总表
			workFullManageService.save(t);//保存
		}else{//新增表单保存
			//上传文件
//			List<WorkClientAttachment> workClientAttachments = workClientInfoService.uploadFile(request, upload_files, workFullManage.getId(), VarStr.attachmentFlag[2]);
//			List<WorkClientAttachment> workClientAttachmentList = workFullManage.getWorkClientAttachmentList();
//			workClientAttachments.addAll(workClientAttachmentList);
//			workFullManage.setWorkClientAttachmentList(workClientAttachments);
			workFullManage.setFullProjectStatus("1"); //1为项目立项状态
			workFullManage.setCompanyId(UserUtils.getSelectCompany().getId()); //存入公司编号

			WorkProject workProject = new WorkProject();
			workProject.setContractId(workFullManage.getWorkContractInfo());
			workProject.setName(workFullManage.getFullProjectName());
			workProject.setNumber(workFullManage.getFullProjectNumber());
			workProject.setCreateBy(workFullManage.getCreateBy());
			workProject.setCreateDate(workFullManage.getCreateDate());
			workProject.setDelFlag(workFullManage.getDelFlag());
			workProject.setUpdateBy(workFullManage.getUpdateBy());
			workProject.setUpdateDate(workFullManage.getUpdateDate());
			workProject.setRemarks(workFullManage.getRemarks());
			workProject.setCompanyId(UserUtils.getSelectCompany().getId());
			workProject.setSort("全过程管理");
			workProjectService.save(workProject);//保存项目总表
			workFullManage.setWorkProject(workProject);
			workFullManageService.save(workFullManage);//保存
		}

		addMessage(redirectAttributes, "保存项目登记成功");
		return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullManage/?repage";
	}

	public WorkFullManage getSort(WorkFullManage workFullManage){
		if (!Strings.isNullOrEmpty(workFullManage.getTotalFullId()) && 30 == workFullManage.getSort()){
			// 获取排序号，最末节点排序号+30
			if (StringUtils.isBlank(workFullManage.getId())){
				WorkFullManage workFullManageChild = new WorkFullManage();
				workFullManageChild.setTotalFullId(workFullManage.getTotalFullId());
				List<WorkFullManage> list = workFullManageService.findByList(workFullManage);
				if (list.size() > 0){
					workFullManage.setSort(list.get(list.size()-1).getSort());
					if (workFullManage.getSort() != null){
						workFullManage.setSort(workFullManage.getSort() + 1);
					}
				}
			}
		}
		return workFullManage;
	}

	/**
	 * 删除项目登记
	 */
	@RequiresPermissions("workfullmanage:workFullManage:del")
	@RequestMapping(value = "delete")
	public String delete(WorkFullManage workFullManage, RedirectAttributes redirectAttributes) {
		WorkProject workProject = workFullManage.getWorkProject();
		workProjectService.delete(workProject);//删除总项目表数据
		workFullManageService.delete(workFullManage);
		addMessage(redirectAttributes, "删除项目登记成功");
		/*String currentUser = UserUtils.getUser().getId(); //当前登录人
		if(workFullManage.getHostMaster().indexOf(currentUser) == -1 || !workFullManage.getCreateBy().getId().equals(currentUser)){
			addMessage(redirectAttributes, "对不起，您没有权限操作！！！");
			return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullManage/?repage";
		}
		if("4".equals(workFullManage.getFullProjectStatus()) && workFullManage.getHostMaster().indexOf(currentUser) != -1){//项目归档
			WorkProject workProject = workFullManage.getWorkProject();
			workProjectService.delete(workProject);//删除总项目表数据
			workFullManageService.delete(workFullManage);
			addMessage(redirectAttributes, "删除项目登记成功");
		}else{
			addMessage(redirectAttributes, "对不起，您没有权限操作！！！");
			return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullManage/?repage";
		}*/
		return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullManage/?repage";
	}
	
	/**
	 * 批量删除项目登记
	 */
	@RequiresPermissions("workfullmanage:workFullManage:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			WorkProject workProject = workFullManageService.get(id).getWorkProject();
			workProjectService.delete(workProject);//删除总项目表数据
			workFullManageService.delete(workFullManageService.get(id));
		}
		addMessage(redirectAttributes, "删除项目登记成功");
		return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullManage/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workfullmanage:workFullManage:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkFullManage workFullManage, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "项目登记"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkFullManage> page = workFullManageService.findPage(new Page<WorkFullManage>(request, response, -1), workFullManage);
    		new ExportExcel("项目登记", WorkFullManage.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出项目登记记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullManage/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workfullmanage:workFullManage:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WorkFullManage> list = ei.getDataList(WorkFullManage.class);
			for (WorkFullManage workFullManage : list){
				try{
					workFullManageService.save(workFullManage);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条项目登记记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条项目登记记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入项目登记失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullManage/?repage";
    }
	
	/**
	 * 下载导入项目登记数据模板
	 */
	@RequiresPermissions("workfullmanage:workFullManage:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "项目登记数据导入模板.xlsx";
    		List<WorkFullManage> list = Lists.newArrayList(); 
    		new ExportExcel("项目登记数据", WorkFullManage.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullManage/?repage";
    }

	/**
	 * 获取项目信息
	 * @return
	 */
	@RequestMapping(value = "getContractInfo")
	@ResponseBody
	public String getContractInfo() {
		HashMap<Object, Object> map = Maps.newHashMap();
		String obj = request.getParameter("obj");
		WorkContractInfo workContractInfo = workContractInfoService.get(obj);
		//User u = UserUtils.get(workContractInfo.getCreateBy().getId());

		map.put("contractNum",workContractInfo.getContractNum());
		WorkClientInfo workClientInfo = new WorkClientInfo();
		if(workContractInfo.getClient() != null){
			workClientInfo = workClientInfoService.get(workContractInfo.getClient().getId());
		}
		String clientName = "";
		if (workClientInfo!=null) {
			clientName = workClientInfo.getName();
		}
		map.put("clientName",clientName);
		map.put("clientId",workClientInfo.getId());
		WorkClientLinkman workClientLinkman = new WorkClientLinkman();
		workClientLinkman.setClientId(workClientInfo);
		List<WorkClientLinkman> Linkmanlist = workClientInfoService.findByClient(workClientLinkman);
		if(Linkmanlist.size() > 0){
			if(Linkmanlist.get(0) != null){
				map.put("linkmanPosition",Linkmanlist==null?"":Linkmanlist.get(0).getPosition());
				map.put("linkmanName",Linkmanlist==null?"":Linkmanlist.get(0).getName());
				map.put("linkmanPhone",Linkmanlist==null?"":Linkmanlist.get(0).getLinkPhone());
				map.put("linkmanEmail",Linkmanlist==null?"":Linkmanlist.get(0).getEmail());
				map.put("QQ",Linkmanlist==null?"":Linkmanlist.get(0).getQq());
			}
		}
		map.put("creditRank", DictUtils.getDictLabel(workClientInfo.getCreditRank(),"credit_rank",""));
		return JsonMapper.toJsonString(map);
	}


	/**
	 * 获取客户信息
	 * @return
	 */
	@RequestMapping(value = "getWorkClientInfo")
	@ResponseBody
	public String getWorkClientInfo(){
		String obj = request.getParameter("obj");
		WorkClientInfo workClientInfo = workClientInfoService.get(obj);
		String resultJsonStr = workFullManageService.parseList2Json(workClientInfo);
		return resultJsonStr;
	}

	/**
	 * 异步上传文件
	 * @return
	 */
	@RequestMapping("/uploadFile")
	@ResponseBody
	public Map<String,Object> uploadFile(WorkFullManage workFullManage,
										 Model model, RedirectAttributes redirectAttributes,
										 HttpServletRequest request,
										 @RequestParam(value = "myFile") CommonsMultipartFile myFile){
		String attchmentFlag = request.getParameter("file_type");
		WorkClientAttachment workClientAttachment = workClientInfoService.uploadFileSingle(request, myFile, workFullManage.getId(), attchmentFlag);
		String ids = request.getParameter("ids");
		if(StringUtils.isNotBlank(ids)){
			workClientAttachment.setId(ids);
		}
		String s = workClientInfoService.save(workClientAttachment);
		Map map = new HashMap();
		map.put("msg","success");
		map.put("s",s);
		return map;
	}

	/**
	 * 查看上传附件的信息
	 * @return
	 */
	@RequestMapping("/queryInfoToFile")
	public String queryInfoToFile(WorkFullManage workFullManage, Model model){
		String attachment = request.getParameter("attachment");
		WorkClientAttachment workClientAttachment = new WorkClientAttachment();
		workClientAttachment.setAttachmentId(workFullManage.getId());
		workClientAttachment.setAttachmentFlag(attachment);
		List<WorkClientAttachment> list = workFullManageService.findList(workClientAttachment);
		model.addAttribute("list",list);
		model.addAttribute("id",workFullManage.getId());
		return "modules/workfullmanage/projectPreList";
	}

	/**
	 * 修改项目状态
	 * @param workFullManage
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping("/updStatusById")
	@ResponseBody
	public boolean updStatusById(WorkFullManage workFullManage,RedirectAttributes redirectAttributes){
		String status = request.getParameter("status");
		workFullManage.setFullProjectStatus(status); //将项目状态改为项目准备
		int j = workFullManageService.updStatusById(workFullManage);
		boolean s = (j > 0) ? true : false;
		String str = "";
		if("2".equals(status)){
			str = "项目立项完成";
		}else if("3".equals(status)){
			str = "项目准备完成";
		}
		String hostMaster = workFullManage.getHostMaster();
		String hostMember = workFullManage.getHostMember();
		String followMember = workFullManage.getFollowMember();
		String followMaster = workFullManage.getFollowMaster();
		String[] split = hostMaster.split(",");
		String[] split1 = hostMember.split(",");
		String[] split2 = followMember.split(",");
		String[] split3 = followMaster.split(",");
		Object[] objects = ArrayUtils.addAll(split, split1);
		Object[] objects1 = ArrayUtils.addAll(split2, split3);
		Object[] objects2 = ArrayUtils.addAll(objects, objects1);
		Set<String> set = new HashSet<>();
		for (int i = 0; i < objects2.length; i++) {
			if(objects2[i] == null || "".equals(objects2[i])){
				continue;
			}
			set.add(objects2[i].toString());
		}
		//移除项目登记人
		if(set.contains(workFullManage.getCreateBy().getId())){
			set.remove(workFullManage.getCreateBy().getId());
		}
		Iterator<String> iterator = set.iterator();
		while (iterator.hasNext()){
			String next = iterator.next();
			workProjectNotifyService
					.save(UtilNotify
							.saveNotify(workFullManage.getId(),
									UserUtils.get(next),
									workFullManage.getCompanyId(),
									str,
									"同意",
									"17",
									"0",
									"待通知",
									""));
		}
//		addMessage(redirectAttributes, s);
//		return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullManage/?repage";
		return s;
	}

	/**
	 * 下载附件
	 */
	@RequestMapping("/downLoadAttach")
	public String downLoadAttach(String file,HttpServletResponse response) throws IOException {
//		file = file.replace("amp;","");
//		String fileName = file.substring(file.lastIndexOf("/") + 1, file.length());
//		String aliyunUrl = Global.getAliyunUrl();
//		String aliDownloadUrl = Global.getAliDownloadUrl();
//		String cons = "";
//		if (file.contains(aliyunUrl)){
//			cons = aliyunUrl;
//		}else if (file.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")){
//			cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
//		}else {
//			cons = aliDownloadUrl;
//		}
//		String key = file.split(cons+"/")[1];
//		logger.info("-----------------------------------------");
//		logger.info("fileName="+fileName);
//		logger.info("key="+key);
//		logger.info("-----------------------------------------");
//		new OSSClientUtil().downByStream(key,fileName,response,request.getHeader("USER-AGENT"));
//		return null;
		OutputStream out = null;
		InputStream in = null;
		try {
			file = URLDecoder.decode(file,"UTF-8");
			String path = file.substring(file.indexOf(".com") + 4, file.length());
			String fileName = URLEncoder.encode(file.substring(file.lastIndexOf("/") + 1, file.length()),"UTF-8");
			BOSClientUtil bosClientUtil = new BOSClientUtil();
			in = bosClientUtil.getObject(path);
			response.reset();//重置 响应头
			response.setContentType("application/x-download");
			response.setHeader("Content-disposition", "attachment; filename=" + fileName);
			out = response.getOutputStream();
			byte[] b = new byte[1024];
			int len;
			while ((len = in.read(b)) > 0){
				response.getOutputStream().write(b, 0, len);
			}
			in.close();
			out.close();
		}catch (IOException e){
			e.printStackTrace();
		}finally {
			if (out != null) {
				out.close();
			}
			if (in != null) {
				in.close();
			}
		}
      return  null;


	}

	/**
	 * 删除文件
	 * @param file
	 */
	@RequestMapping("/deleteFile")
	@ResponseBody
	public String deleteFile(@RequestParam("file") String file){
		HashMap<Object, Object> map = Maps.newHashMap();
		String aliyunUrl = Global.getAliyunUrl();
		String aliDownloadUrl = Global.getAliDownloadUrl();
		String cons = "";
		if (file.contains(aliyunUrl)){
			cons = aliyunUrl;
		}else if (file.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")){
			cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
		}else {
			cons = aliDownloadUrl;
		}
		String s = file.split(cons + "/")[1];
		String attach = request.getParameter("attach");
		workClientInfoService.deleteFile(s,attach);
		map.put("str",true);
		return JsonMapper.toJsonString(map);
	}

	/**
	 * 查询档案管理员
	 * @param file
	 */
	@RequestMapping("/queryManageUser")
	@ResponseBody
	public String queryManageUser(@RequestParam("file") String file){
		HashMap<Object, Object> map = Maps.newHashMap();
		String aliyunUrl = Global.getAliyunUrl();
		String aliDownloadUrl = Global.getAliDownloadUrl();
		String cons = "";
		if (file.contains(aliyunUrl)){
			cons = aliyunUrl;
		}else if (file.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")){
			cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
		}else {
			cons = aliDownloadUrl;
		}
		String s = file.split(cons + "/")[1];
		String attach = request.getParameter("attach");
		workClientInfoService.deleteFile(s,attach);
		map.put("str",true);
		//获取公司编号
		String id = UserUtils.getSelectCompany().getId();
		//查询公司下的档案管理员

		return JsonMapper.toJsonString(map);
	}

	/**
	 * 选择报销项目
	 */
	@RequestMapping(value = "selectproject")
	public String selectproject(WorkFullManage projectId, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey,String isTotal, HttpServletRequest request, HttpServletResponse response, Model model) {
		projectId.setCompanyId(UserUtils.getSelectCompany().getId());
		projectId.setIsTotal(isTotal);
		Page<WorkFullManage> page = workFullManageService.findPageByproject(new Page<WorkFullManage>(request, response),  projectId);
		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", projectId);
		model.addAttribute("isTotal", isTotal);
		model.addAttribute("allowInput", true);
		model.addAttribute("page", page);
		return "modules/sys/gridselectcallproject";
	}

	/**
	 * 选择报销项目
	 */
	@RequestMapping(value = "selectprojectTotal")
	public String selectprojectTotal(WorkFullManage projectId, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey,String isTotal, HttpServletRequest request, HttpServletResponse response, Model model) {
		projectId.setCompanyId(UserUtils.getSelectCompany().getId());
		projectId.setIsTotal("1");
		Page<WorkFullManage> page = workFullManageService.findPageByproject(new Page<WorkFullManage>(request, response),  projectId);
		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", projectId);
		model.addAttribute("isTotal", isTotal);
		model.addAttribute("allowInput", true);
		model.addAttribute("page", page);
		return "modules/sys/gridselectcallproject";
	}


	private String toChinese(String string) {
		String[] s1 = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
		String[] s2 = { "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千" };

		String result = "";

		int n = string.length();
		for (int i = 0; i < n; i++) {

			int num = string.charAt(i) - '0';

			if (i != n - 1 && num != 0) {
				result += s1[num] + s2[n - 2 - i];
			} else {
				result += s1[num];
			}
			System.out.println("  "+result);
		}
		return result;

	}
}