package com.palmnest.service.estateserve.release.impl;

import cn.superdesk.libs.common.json.JsonUtils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.palmnest.application.AppConstants;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.GoodsCodeConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.*;
import com.palmnest.application.dto.input.GoodsReleaseBillInputDto;
import com.palmnest.application.dto.input.GoodsReleaseOpRecorInputDto;
import com.palmnest.application.dto.output.GoodsOperateDto;
import com.palmnest.application.dto.output.GoodsReleaseOutDto;
import com.palmnest.application.dto.output.enterprise.GoodsReleaseVo;
import com.palmnest.dao.estateserve.EnterprisePermissionDao;
import com.palmnest.dao.release.GoodsCompanyDao;
import com.palmnest.model.EnterpriseAudit;
import com.palmnest.model.GoodsReleaseOpRecord;
import com.palmnest.model.Role;
import com.palmnest.model.User;
import com.palmnest.model.dinner.Department;
import com.palmnest.model.enterprise.VirPermConfig;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.model.release.GoodsDetail;
import com.palmnest.model.release.GoodsRelease;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.RoleManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.dinner.manager.DeptManager;
import com.palmnest.service.estateserve.*;
import com.palmnest.service.estateserve.release.GoodsDetailManager;
import com.palmnest.service.estateserve.release.GoodsReleaseManager;
import com.palmnest.service.estateserve.release.GoodsReleaseService;
import com.palmnest.service.redis.BaseRedisService;

import lombok.extern.slf4j.Slf4j;


import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

@Slf4j
@Service("goodsReleaseService")
public class GoodsReleaseServiceImpl implements GoodsReleaseService {


	private static final String GCWX = "wpfy";

	//dev开发环境test测试
	public static final String CLIENTNO = PropertiesKit.readPropertiesValue("clientNo", "wechat.properties");

	@Autowired
	private RoleManager                 roleManager;
	@Autowired
	private GoodsReleaseManager         goodsReleaseManager;
	@Autowired
	private GoodsReleaseOpRecordManager goodsReleaseOpRecordManager;
	@Autowired
	private GoodsDetailManager          goodsDetailManager;
	@Autowired
	private ScWxuserManager             scWxuserManager;
	@Autowired
	private VirtualArchManager          virtualArchManager;
	@Autowired
	private EnterpriseAuditManager      enterpriseAuditManager;
	@Autowired
	private BaseRedisService            baseRedisService;
	@Autowired
	private UserManager                 userManager;
	@Autowired
	private AppUserManager              appUserManager;

	@Autowired
	private DeptManager deptManager;

	@Autowired
	private GoodsCompanyDao companyDao;
	@Autowired
	private OrganizationManager         organizationManager;
	@Autowired
	private EnterprisePermissionManager enterprisePermissionManager;
	@Autowired
	private EnterprisePermissionDao     enterprisePermissionDao;



	@Override
	public AppResultDto apply(GoodsReleaseBillInputDto dto, MultipartHttpServletRequest request) {//只有微信能发起 物品放行申请

		log.info("GoodsReleaseServiceImpl apply======");
		log.info("GoodsReleaseServiceImpl apply[参数dto:]{}======",dto.toString());

		String           picUrl    = "";
		Iterator<String> fileNames = request.getFileNames();
		//String []applyImgDesc=request.getParameterValues("applyImgDesc");
		String    applyImgDescJson = request.getParameter("applyImgDesc");
		List<Map> imgDescMap       = com.alibaba.fastjson.JSON.parseArray(applyImgDescJson, Map.class);

		String    applyGoodsJson = request.getParameter("applyGoods");//申请放行物品列表
		List<Map> applyGoodsMap  = com.alibaba.fastjson.JSON.parseArray(applyGoodsJson, Map.class);

		boolean isUpdate = false;
		if (dto.getUpdateType() == 2 && null == dto.getId()) {
			return AppResultUtil.createErrorDto(AppConstants.REPAIR_BILL_ERROR, "参数id不能为空");
		}
		if (dto.getUpdateType() == 2) {
			isUpdate = true;
		}

		if(null!= dto.getIsToepidemic() && dto.getIsToepidemic().equals(3)){
			dto.setIsSevenDayCheckResult(3);
		}

		// 获取图片数组
		String[] files = request.getParameterValues("files");

		try {
			GoodsRelease release = new GoodsRelease();
			BeanUtils.copyProperties(release, dto);

			if(isUpdate){
				Long decode_id = grDecodeId(dto.getId());
				release.setId(decode_id);
			}


			int fileNum = 0;
//	        while(fileNames.hasNext()) {
//	        	MultipartFile multipartFile = request.getFile(fileNames.next());
//
//	        	//获得文件原始名称
//	            InputStream stream = null;
//	            String fileExt = null;
//	            String fileName = "";
//	            if (multipartFile != null) {
//					stream = multipartFile.getInputStream();
//	                fileName = multipartFile.getOriginalFilename();
//						fileName = new String(fileName.getBytes(), "utf-8");
//	                fileExt = StringUtils.isNotEmpty(fileName) ? fileName
//	                        .substring(fileName.lastIndexOf("."))
//	                        : StringUtils.EMPTY;
//	            }
//
//	            FileUploadUtils fileUploadUtils = new FileUploadUtils();
//	            fileUploadUtils.init();
//	            String url = fileUploadUtils.uploadFile(stream, fileExt)+"@"+getImgDesc(imgDescMap,fileNum);//用
//	            picUrl+=";"+fileUploadUtils.fullVisitPath(url);
//
//	            ++fileNum;
//	        }

			long startTime = System.currentTimeMillis();
			if (files != null && files.length > 0) {
				for (int i = 0; i < files.length; i++) {
					FileUploadUtils fileUploadUtils = new FileUploadUtils();
					fileUploadUtils.init();

					String  base64ImgUrl = files[i];
					boolean isUpImg      = false;
					if (base64ImgUrl.indexOf("http://") != -1) {
						isUpImg = true;
					}

					if (!isUpImg) {
						if (StringUtils.isNotBlank(base64ImgUrl)) {
							String url = FileUploadUtils.getBase64ImageUrl(base64ImgUrl);

							File file = new File(FileUploadUtils.getATTACHMENT_ROOT() + url);
							if (file != null && file.length() > (500 * 1024)) {
								log.info("图片大小为 =========>:" + file.length());
								FileUploadUtils.compressPic(file);
							}

							if (StringUtils.isNotEmpty(url)) {//外部访问的全路径
								url += "@" + getImgDesc(imgDescMap, fileNum);
							}

							picUrl += ";" + fileUploadUtils.fullVisitPath(url);
							++fileNum;
						}
					} else {
						if (StringUtils.isNotEmpty(base64ImgUrl)) {//外部访问的全路径
							String upImgurl = base64ImgUrl + "@" + getImgDesc(imgDescMap, fileNum);

							//picUrl += ";" + fileUploadUtils.fullVisitPath(url);
							picUrl += ";" + upImgurl;
							++fileNum;
						}


					}

				}
			}

			long endTime = System.currentTimeMillis();
			log.info("电子放行条图片上传处理时间==========>:" + (endTime - startTime));

			if (picUrl.length() > 1) {
				release.setApplypicUrl(picUrl.substring(1));
			}

			String code = CodeGenerateUtils.generate(GCWX);
			release.setCode(code);
			release.setReleaseStatus(GoodsCodeConstants.ST_AUDITING);//审核中

			String openId = request.getParameter("openId");
			WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
			if (wxUser != null) {
				release.setCreatorBillId(Long.parseLong(wxUser.getId() + ""));
				release.setCreator(wxUser.getNickName());
				release.setModifier(wxUser.getNickName());
			}
			release.setOrgId(dto.getOrgId());
			release.setVirAccountId(dto.getVirAccountId());
			release.setCreateTime(new Date());
			release.setModifyTime(new Date());
			TbOrganization org = organizationManager.getOrganizationById(dto.getOrgId());
			if (org.getAccountType() == 1 && dto.getUserId() != null) {
				AppUser user = appUserManager.get(dto.getUserId());
				//release.setCreatorBillId(Long.parseLong(dto.getUserId()+""));
				//设置企业id
				VirtualArchitecture vir = virtualArchManager.get(user.getVirtualArchId());
				release.setCompanyid(Long.parseLong(vir.getId() + ""));
				//设置申请人姓名电话
				release.setApplyUser(user.getUserName());
				release.setApplyTel(user.getUserMobile());
				release.setCreator(user.getUserName());
				release.setModifier(user.getUserName());
			}

			String types = "1,2";
			if (release.getApplyType() == 1) {
				types = "3,4";//电子企业 goodconfig 为3
			}
			List<Map<String, Object>> list = enterprisePermissionDao.getGoodsConfig(dto.getOrgId().longValue(), types,dto.getProcessName());
			if (list != null && list.size() > 0) {
				release.setType(Integer.parseInt(list.get(0).get("type").toString()));
				release.setRoleId(Integer.parseInt(list.get(0).get("roleId").toString()));

				if(null !=list.get(0).get("roleName")){
                    release.setRoleName(list.get(0).get("roleName").toString());
                }
				release.setSort(Integer.parseInt(list.get(0).get("sort").toString()));
			}

			GoodsRelease bill = goodsReleaseManager.save(release);


			if (!isUpdate) {
				//保存物品明细
				saveGoodsDetail(applyGoodsMap, bill.getId());
			}


			EnterpriseAudit record = new EnterpriseAudit();
			if (wxUser != null) {
				record.setCreator(wxUser.getId());
				record.setContent("微信用户 " + wxUser.getNickName());//审批内容'
			}
			//个人账号
			if (org.getAccountType() == 1 && dto.getUserId() != null) {
				AppUser user = appUserManager.get(dto.getUserId());
				record.setCreator(dto.getUserId());
				record.setContent(user.getUserName());
			}
			record.setCreateTime(new Date());
			record.setType("3");//类型1企业入驻2企业迁出3物品放行
			record.setSourseId(Integer.parseInt(String.valueOf(bill.getId())));


			if (isUpdate) {
				record.setReasonType(4);//审批操作类型--修改申请通行
			} else {
				record.setReasonType(3);//审批操作类型
			}
			//record.setRemark(dto.getRemark());

			if (isUpdate) {
				//删除历史流程记录
				EnterpriseAudit delRecord = new EnterpriseAudit();
				delRecord.setSourseId(Integer.parseInt(String.valueOf(bill.getId())));
				enterpriseAuditManager.remove(delRecord);
			}

			//保存流程记录
			enterpriseAuditManager.save(record);


			//微信物品放行申请后 要发模板消息给负责人审批
			//TODO 判断物品放行权限
			//dto.setId(bill.getId());
			//goodsReleaseManager.sendWechat(dto);//这里报错不影响正常流程
			//

			return AppResultUtil.createSuccesDto(convert(bill));
		} catch (Exception e) {
			log.info("GoodsReleaseServiceImpl apply Error ==========>:" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.REPAIR_BILL_ERROR, "放行申请失败:" + LogExceptionStackUtil.LogExceptionStack(e));
		}
	}

	public void saveGoodsDetail(List<Map> applyGoodsMap, long billId) {
		if (null != applyGoodsMap && applyGoodsMap.size() > 0) {
			for (Map map : applyGoodsMap) {
				String      name   = (String) map.get("name");
				String      amount = (String) map.get("amount");
				String      company = (String) map.get("company");
				GoodsDetail detail = new GoodsDetail();
				detail.setGoodsName(name);
				detail.setAmount(Integer.parseInt(amount));
				detail.setReleaseId(billId);
				detail.setCompany(company);
				goodsDetailManager.saveModel(detail);
			}
		}
	}

	/*public void sendWechat(GoodsReleaseBillInputDto dto){

		log.info("sendWechat===========");
		申请人姓名：{{keyword1.DATA}}
		放行企业：{{keyword2.DATA}}
		申请时间：{{keyword3.DATA}}
		放行物品：{{keyword4.DATA}}
		申请人电话：{{keyword5.DATA}}
		try{
			List<WxtemplateMessageTypeModel> templateList=replayContentDao.getWxTemplateByTempId(0, "_H0CxhtnoKCKBUyrg44HSdRrEVD6Qi4LID93ANobOZg");

			//根据企业id查出相应的负责人----要给两个负责人发送
			if(StringUtils.isNotEmpty(String.valueOf(dto.getCompanyid()))){
				List<VirtUserInfo> list= virtUserDao.getVirUserByVirId(Integer.valueOf(String.valueOf(dto.getCompanyid())));
				if(list!=null&&list.size()>0){
					for(int k=0;k<list.size();k++){
						VirtUserInfo virUserInfo=list.get(k);
						int userId=virUserInfo.getUserId();//这个是tb_user表中的id
						WxUser wxUser=scWxuserManager.getScWxuserByUserId(userId);
						if(wxUser!=null){
							if(!CollectionUtils.isEmpty(templateList)){
								String templateId=(String) templateList.get(0).getTemplateid();
								Map<String,String> paramMap=new HashMap<String,String>();
								paramMap.put("developId", wxUser.getDevelopId());
								paramMap.put("openId", wxUser.getOpenId());
								paramMap.put("templateId", templateId);
								paramMap.put("url", "");
								paramMap.put("keyword1",dto.getApplyUser());

								VirtualArchitecture vir=virtualArchManager.get(Integer.parseInt(String.valueOf(dto.getCompanyid())));
								if(null!=vir && StringUtils.isNotEmpty(vir.getName())){
									paramMap.put("keyword2",vir.getName());
								}else{
									paramMap.put("keyword2","");
								}
								paramMap.put("keyword3",DateHelper.formatDate(new Date(), DateHelper.CURRENT_DATE));
								paramMap.put("keyword4",elementGroupManager.getElementId(dto.getReleaseType()).getItemname());
								paramMap.put("keyword5",dto.getApplyTel());
								paramMap.put("remark", "请您及时处理！");
								String str=weChatApiManager.sendTemplateMsg11(paramMap);
								JSONObject json = JSONObject.parseObject(str);
								String errmsg=json.get("errmsg").toString();

								log.info(errmsg);
							}
						}
					}
				}
			}
		}catch(Exception e){
			log.info(LogExceptionStackUtil.LogExceptionStack(e));
		}

	}*/

	@Override
	public GoodsReleaseOutDto convert(GoodsRelease goodsBill) {

		GoodsReleaseOutDto dto = new GoodsReleaseOutDto();
		try {

			//dto.setId(goodsBill.getId());


			String gen_id = URLEncoder.encode(GenPass.Encrypt(goodsBill.getId().toString()), "UTF-8");
			dto.setId(gen_id);

			dto.setReleaseCode(goodsBill.getCode());//放行单编码
			//dto.setReleaseTypeName(elementGroupManager.getElementId(goodsBill.getReleaseType()).getItemname());
			dto.setCreateTime(DateHelper.formatDate(goodsBill.getCreateTime(), DateHelper.DATE_STRING));


			dto.setApplyUser(goodsBill.getApplyUser());
			dto.setApplyTel(goodsBill.getApplyTel());



			dto.setApplyUserInfo(goodsBill.getApplyUser() + " " + goodsBill.getApplyTel());////'申请人信息(姓名加手机',

			dto.setApplyUserInfo(goodsBill.getApplyUser() + " " + goodsBill.getApplyTel());////'申请人信息(姓名加手机',
			dto.setCompanyHeadUser(goodsBill.getCompanyHeadUser());

			VirtualArchitecture vir = virtualArchManager.get(Integer.parseInt(String.valueOf(goodsBill.getCompanyid())));
			if (null != vir && StringUtils.isNotEmpty(vir.getName())) {
				dto.setCompanyName(vir.getName());
			}

			if (null != vir && StringUtils.isNotEmpty(vir.getRoomNames())) {
				dto.setRoomNames(vir.getRoomNames());
			}

			//部门处理
			AppUser appUser = appUserManager.get(goodsBill.getUserId());
			if(null != appUser){
				dto.setLoginName(appUser.getLoginName());
			}
			if (null != appUser && appUser.getDepartmentId() != null) {
				Department dept = deptManager.get(Long.parseLong(appUser.getDepartmentId().toString()));
				if (dept != null) {
					dto.setDepName(dept.getName());
				}
			}
			dto.setReleaseDesc(goodsBill.getReleaseDesc());

			dto.setReleaseStatus(goodsBill.getReleaseStatus());
			dto.setApplypicUrl(goodsBill.getApplypicUrl());
			dto.setReleasepicUrl(goodsBill.getReleasepicUrl());
			dto.setType(goodsBill.getType());
			dto.setRoleId(goodsBill.getRoleId());
			dto.setRoleName(goodsBill.getRoleName());
			dto.setSort(goodsBill.getSort());
			dto.setReleaseUserName(goodsBill.getReleaseUserName());
			dto.setNativePlaceNumber(goodsBill.getNativePlaceNumber());
			dto.setHabitationNumber(goodsBill.getHabitationNumber());
			dto.setProcessName(goodsBill.getProcessName());


			if (org.apache.commons.lang3.StringUtils.isNotEmpty(goodsBill.getNativePlace())) {//籍贯  ---->省市县
				dto.setNativePlace(goodsBill.getNativePlace().replace(";", ""));
			} else {
				dto.setNativePlace("");
			}

			dto.setPersonType(goodsBill.getPersonType());
			if (goodsBill.getPersonType() == 1) {
				dto.setPersonTypeName("留在本市人员");
			} else if (goodsBill.getPersonType() == 2) {
				dto.setPersonTypeName("返回本市人员");
			} else {
				dto.setPersonTypeName("");
			}

			//7日内核酸监测结果   0-阴  1-阳 2-未检测 3-空
			dto.setIsSevenDayCheckResult(goodsBill.getIsSevenDayCheckResult());
			if (goodsBill.getIsSevenDayCheckResult() == 0) {
				dto.setIsSevenDayCheckResultName("阴");
			} else if (goodsBill.getIsSevenDayCheckResult() == 1) {
				dto.setIsSevenDayCheckResultName("阳");
			} else if(goodsBill.getIsSevenDayCheckResult() == 2) {
				dto.setIsSevenDayCheckResultName("未检测");
			}else{
				dto.setIsSevenDayCheckResultName("");
			}

			if (org.apache.commons.lang3.StringUtils.isNotEmpty(goodsBill.getLeaveCityTime())) {
				dto.setLeaveCityTime(goodsBill.getLeaveCityTime());
			} else {
				dto.setLeaveCityTime("");
			}
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(goodsBill.getReturnCityTime())) {
				dto.setReturnCityTime(goodsBill.getReturnCityTime());
			} else {
				dto.setReturnCityTime("");
			}
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(goodsBill.getHabitation())) {//春节居住地 ---->省市县
				dto.setHabitation(goodsBill.getHabitation().replace(";", ""));
			} else {
				dto.setHabitation("");
			}

			dto.setIsToepidemic(goodsBill.getIsToepidemic());
			if (goodsBill.getIsToepidemic() == 1) {
				dto.setIsToepidemicName("武汉");
			} else if (goodsBill.getIsToepidemic() == 2) {
				dto.setIsToepidemicName("湖北非武汉");
			} else if (goodsBill.getIsToepidemic() == 3) {
				dto.setIsToepidemicName("无");
			} else if (goodsBill.getIsToepidemic() == 4) {
				dto.setIsToepidemicName("有");
			} else {
				dto.setIsToepidemicName("");
			}
			dto.setIsHaveSymptom(goodsBill.getIsHaveSymptom());
			dto.setApplyType(goodsBill.getApplyType());
			dto.setSymptomName(goodsBill.getSymptomName());
			dto.setPassNum(goodsBill.getPassNum());

			List<EnterpriseAudit> records = enterpriseAuditManager.getEnterAuditList("3", Integer.parseInt(String.valueOf(goodsBill.getId())));
			List<GoodsOperateDto> dtos    = new ArrayList<GoodsOperateDto>();
			for (EnterpriseAudit record : records) {
				String auditResult = "";
				if (record.getReasonType() == 1) {
					auditResult = "审核通过";
				} else if (record.getReasonType() == 0) {
					auditResult = "拒绝放行";
				} else if (record.getReasonType() == 3) {
					if (goodsBill.getApplyType() == 1) {
						auditResult = "通行申请";
					} else {
						auditResult = "放行申请";
					}

				} else if (record.getReasonType() == 4) {
					auditResult = "修改通行申请";
				}
				GoodsOperateDto dt = new GoodsOperateDto(DateHelper.formatDate(record.getCreateTime(), DateHelper.DATE_STRING), record.getContent(), auditResult, record.getRemark());
				dtos.add(dt);
			}
			dto.setOperateDto(dtos);

			//获取放行物品列表
			List<GoodsDetail> details = goodsDetailManager.getGoodsDetailByBillId(goodsBill.getId());
			dto.setGoodsDetails(details);

			return dto;

		} catch (Exception e) {

		}
		return dto;


	}

	@Override
	public Page findPageBy(Map<String, Object> params, int pageSize, int pageNo) {

		Page page = goodsReleaseManager.findPageBy(params, pageSize, pageNo);

		List<Object> list = page.getItems();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> obj = (Map<String, Object>) list.get(i);
				String              id  = obj.get("id").toString();//订单id

				if (StringUtils.isNotEmpty(id)) {
					String gen_id = id;
					try {
						gen_id = URLEncoder.encode(GenPass.Encrypt(id), "UTF-8");
					} catch (Exception e) {
						log.info("goodsReleaseManager.findPageBy gen_id error");
						e.printStackTrace();
					}

					obj.put("id", gen_id);//保存加密后的id
				}

				if(null != obj.get("applypicUrl") && StringUtils.isNotEmpty(obj.get("applypicUrl").toString())){
					String applypicUrl=obj.get("applypicUrl").toString();
					log.info("findPageBy-applypicUrl:"+applypicUrl);
					if(StringUtils.isNotBlank(applypicUrl)){
						String url="";
						String [] arr=applypicUrl.split(";");
						if(null != arr && arr.length > 0){
							for(int k=0;k<arr.length;k++){
								String imgUrl=arr[k];
								if(StringUtils.isEmpty(imgUrl) || "null".equals(imgUrl)){
									continue;
								}
								if(arr[k].indexOf("http") == -1){
									continue;
								}
								log.info("findPageBy-applypicUrl-imgUrl:"+imgUrl);
								String [] imgArr = imgUrl.split("@");
								if(null != imgArr && imgArr.length > 0){
									log.info("findPageBy-applypicUrl-imgArr[0]:"+imgArr[0]);
									url=url+imgArr[0]+";";
								}

							}
						}
						obj.put("applypicUrl", url);
					}else{
						obj.put("applypicUrl", applypicUrl);
					}
				}

				if(null != obj.get("releasepicUrl") && StringUtils.isNotEmpty(obj.get("releasepicUrl").toString())){
					String releasepicUrl=obj.get("releasepicUrl").toString();
					if(StringUtils.isNotBlank(releasepicUrl)){
						String url="";
						String [] arr=releasepicUrl.split(";");
						if(null != arr && arr.length > 0){
							for(int k=0;k<arr.length;k++){
								String imgUrl=arr[k];
								if(StringUtils.isEmpty(imgUrl) || "null".equals(imgUrl)){
									continue;
								}
								if(imgUrl.indexOf("http") == -1){
									continue;
								}
								log.info("findPageBy-imgUrl:"+imgUrl);
								String [] imgArr = imgUrl.split("@");
								if(null != imgArr && imgArr.length > 0){
									log.info("findPageBy-applypicUrl-imgArr[0]:"+imgArr[0]);
									url=url+imgArr[0]+";";
								}
							}
						}
						obj.put("releasepicUrl", url);
					}else{
						obj.put("releasepicUrl", releasepicUrl);
					}
				}
			}
		}

		return page;
	}


	@Override
	public Page findRecordPageBy(Map<String, Object> params, int pageSize, int pageNo) {

		return goodsReleaseManager.findRecordPageBy(params, pageSize, pageNo);
	}

	@Override
	public Page findStatisticsPageBy(Map<String, Object> params, int pageSize, int pageNo) {

		return goodsReleaseManager.findStatisticsPageBy(params, pageSize, pageNo);
	}

	@Override
	public GoodsReleaseOutDto findById(String id) {

		Long decode_id = grDecodeId(id);

		return this.convert(goodsReleaseManager.get(decode_id));
	}

	@Override
	public AppResultDto agree(GoodsReleaseBillInputDto dto, MultipartHttpServletRequest request) {


		log.info("GoodsReleaseServiceImpl agree======");
		log.info("GoodsReleaseServiceImpl agree[参数dto:]{}======",dto.toString());

		String           picUrl    = "";
		Iterator<String> fileNames = request.getFileNames();
		//String []releaseImgDesc=request.getParameterValues("releaseImgDesc");
		String roleType = request.getParameter("roleType");

		// 角色类型( 1客服 5安保
		if (dto.getBillFrom().equals(CodeConstants.PC) || dto.getBillFrom().equals(CodeConstants.WECHAT)) {//pc默认是客服
			roleType = "1";
		}

		String    releaseImgDescJson = request.getParameter("releaseImgDesc");
		List<Map> imgDescMap         = com.alibaba.fastjson.JSON.parseArray(releaseImgDescJson, Map.class);

		try {

			Long decode_id = grDecodeId(dto.getId());

			//第一个是微信端的判断
			GoodsRelease bill = goodsReleaseManager.get(decode_id);


			if ((bill.getType() == null || bill.getRoleId() == null || bill.getSort() == null) && bill.getReleaseStatus().equals(10)) {
				return AppResultUtil.createErrorDto(AppConstants.AGREE_RELEASE, "未配置审核流程");
			}

			// 审批中或待放行状态（安保同意
			if (!(bill.getReleaseStatus().equals(GoodsCodeConstants.ST_AUDITING) || bill.getReleaseStatus().equals(GoodsCodeConstants.ST_WAIT))) {
				return AppResultUtil.createErrorDto(AppConstants.AGREE_RELEASE, "同意放行失败，只有审批中或待放行状态可以同意放行");
			}


			boolean isSecurity = false;//是否安保
			boolean isCustomer = false;//是否客服

			// 角色类型( 1客服 5安保
			if (StringUtils.isNotEmpty(roleType) && roleType.equals("5")) {
				isSecurity = true;
				//图片处理
				int fileNum = 0;
				while (fileNames.hasNext()) {
					MultipartFile multipartFile = request.getFile(fileNames.next());

					//获得文件原始名称
					InputStream stream   = null;
					String      fileExt  = null;
					String      fileName = "";
					if (multipartFile != null) {
						stream = multipartFile.getInputStream();
						fileName = multipartFile.getOriginalFilename();
						fileName = new String(fileName.getBytes(), "utf-8");
						fileExt = StringUtils.isNotEmpty(fileName) ? fileName
								.substring(fileName.lastIndexOf("."))
								: StringUtils.EMPTY;
					}

					FileUploadUtils fileUploadUtils = new FileUploadUtils();
					fileUploadUtils.init();

					//String url = fileUploadUtils.uploadFile(stream, fileExt)+"@"+releaseImgDesc[fileNum];
					String url = fileUploadUtils.uploadFile(stream, fileExt) + "@" + getImgDesc(imgDescMap, fileNum);
					picUrl += ";" + fileUploadUtils.fullVisitPath(url);

					++fileNum;
				}

				if (picUrl.length() > 1) {
					bill.setReleasepicUrl(picUrl.substring(1));
				}

				//图片处理
			} else if (StringUtils.isNotEmpty(roleType) && roleType.equals("1")) { //客服

				// 流程和鉴权管理
				if (dto.getBillFrom().equals(CodeConstants.WECHAT)) {

					//微信端
					if (bill.getType().equals(1) || bill.getType().equals(3)) {

						//企业审核
						if (!bill.getRoleId().equals(dto.getRoleId())) {
							return AppResultUtil.createErrorDto(AppConstants.AGREE_RELEASE, "审核流程不符合");
						}
					} else {
						return AppResultUtil.createErrorDto(AppConstants.AGREE_RELEASE, "审核流程不符合");
					}

				} else {

					//app端
					if (bill.getType().equals(2) || bill.getType().equals(4)) {

						//物业审核
						if (!bill.getRoleId().equals(dto.getRoleId())) {
							return AppResultUtil.createErrorDto(AppConstants.AGREE_RELEASE, "审核流程不符合");
						}
					} else {
						return AppResultUtil.createErrorDto(AppConstants.AGREE_RELEASE, "审核流程不符合");
					}
				}

				//全部审核流程走完
				String types = "1,2";
				if (bill.getApplyType() == 1) {
					types = "3,4";//电子企业 goodconfig 为3
				}

				List<Map<String, Object>> list = enterprisePermissionDao.getGoodsConfig(bill.getOrgId().longValue(), types,bill.getProcessName());

				if (list.size() > bill.getSort()) {

					bill.setType(Integer.parseInt(list.get(bill.getSort()).get("type").toString()));
					bill.setRoleId(Integer.parseInt(list.get(bill.getSort()).get("roleId").toString()));


					if(null !=  list.get(bill.getSort()).get("roleName")){
						bill.setRoleName(list.get(bill.getSort()).get("roleName").toString());
					}

					bill.setSort(Integer.parseInt(list.get(bill.getSort()).get("sort").toString()));

				} else {

					bill.setType(null);
					bill.setRoleId(null);
					bill.setRoleName(null);
					bill.setSort(null);

					isCustomer = true;
				}
			}

			//APP-物品放行-已经放行的申请，客服在通过推送消息点击去还可以继续审核--加一个判断
			if (isCustomer) {
				if (!(bill.getReleaseStatus().equals(GoodsCodeConstants.ST_AUDITING))) {
					return AppResultUtil.createErrorDto(AppConstants.AGREE_RELEASE, "同意放行失败，当前物品放行申请已处理");
				}
			}

			//Element et=elementGroupManager.getElementId(bill.getReleaseType());			

//			if(dto.getBillFrom().equals(CodeConstants.WECHAT)){//企业负责人
//
//				//if(et.getItemcode().equals(GoodsCodeConstants.RELEASETYPE_Z)){//杂物货物类
//					//bill.setReleaseStatus(GoodsCodeConstants.ST_WAIT);//待放行
////				}else{
////					bill.setReleaseStatus(GoodsCodeConstants.ST_AUDITING);//审核中
////				}
//
//			}else

			if (isCustomer) {

				// 就客服 状态是待放行
				bill.setReleaseStatus(GoodsCodeConstants.ST_WAIT);

			} else if (isSecurity) {

				// 安保 ==> 已放行
				bill.setReleaseStatus(GoodsCodeConstants.ST_YETRELEASE);
			}


			//String openId = request.getParameter("openId");


			EnterpriseAudit record = new EnterpriseAudit();

			if (dto.getBillFrom().equals(CodeConstants.PC)) {

				Role role = roleManager.get(dto.getRoleId().longValue());
				User user = (User) request.getSession().getAttribute("UserCache");

				record.setCreator(Integer.parseInt(String.valueOf(user.getId())));
				record.setContent(role.getSucName() + " " + user.getFullName());//审批内容'

			} else if (dto.getBillFrom().equals(CodeConstants.WECHAT)) {

				VirPermConfig config = enterprisePermissionManager.get(dto.getRoleId().longValue());

				if (dto.getUserId() != null) {

					AppUser appUser = appUserManager.get(dto.getUserId());

					record.setCreator(dto.getUserId());
					record.setContent(config.getName() + " " + appUser.getUserName());//审批内容'

					bill.setCompanyHeadUser(appUser.getUserName() + "(已通过)");

				} else {

					WxUser wxUser = scWxuserManager.getScWxuserByOpenId(dto.getOpenId());

					record.setCreator(wxUser.getId());
					record.setContent(config.getName() + " " + wxUser.getNickName());//审批内容'

					bill.setCompanyHeadUser(wxUser.getNickName() + "(已通过)");
				}
				//record.setContent("企业负责人 "+wxUser.getNickName());//审批内容'

			} else if (dto.getBillFrom().equals(CodeConstants.ANDROID) || dto.getBillFrom().equals(CodeConstants.iOS)) {

				String userName = baseRedisService.get(request.getHeader("token"));

				if (userName == null) {
					return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
				}

				User user = userManager.getUserByUsername2(userName);

				record.setCreator(Integer.parseInt(String.valueOf(user.getId())));

				if (isSecurity) {

					record.setContent("安保 " + user.getFullName());//审批内容'

					bill.setReleaseUser(user.getId());//放行安保id 用来过滤
					bill.setReleaseDate(new Date());

				} else {

					Role role = roleManager.get(dto.getRoleId().longValue());

					String roleName = "物业";
					if(org.apache.commons.lang3.StringUtils.isNotBlank(role.getSucName())){
						roleName =  role.getSucName();
					}
					//record.setContent("客服 "+user.getFullName());//审批内容'
					record.setContent(roleName + " " + user.getFullName());//审批内容'
				}
			}
			record.setCreateTime(new Date());

			// 类型 1企业入驻 2企业迁出 3物品放行
			record.setType("3");
			record.setSourseId(Integer.parseInt(String.valueOf(bill.getId())));

			// 审批操作类型
			record.setReasonType(1);
			record.setRemark(dto.getRemark());

			// 2019.6.19富德人寿安保放行添加放行人名称
			bill.setReleaseUserName(dto.getReleaseUserName());

			goodsReleaseManager.updateModel(bill);
			enterpriseAuditManager.save(record);

			if (bill.getReleaseStatus().equals(GoodsCodeConstants.ST_WAIT)) {

				//待放行
				//发同意的模板消息 给申请人
				//TODO
				if (null != bill.getCreatorBillId()) {
					goodsReleaseManager.sendAgreeWechat(bill, "");
				}

			} else if (bill.getReleaseStatus().equals(GoodsCodeConstants.ST_AUDITING)) {

				//如果还是审批中 给客服发ap消息
				//找有物品放行权限的人 发app审批消息		
				//TODO 消息点击后，状态判断
				//goodsReleaseManager.sendNextAgreeWechat(bill,"");
				//push(bill);
			} else if (bill.getReleaseStatus().equals(GoodsCodeConstants.ST_YETRELEASE)) {

				//配置模板
				if (null != bill.getCreatorBillId()) {
					goodsReleaseManager.sendReleaseWechat(bill, dto.getRemark());

				}
			}

			return AppResultUtil.createSuccesDto(convert(bill));

		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.REPAIR_BILL_ERROR, "放行申请失败:" + LogExceptionStackUtil.LogExceptionStack(e));
		}


	}

	private String getImgDesc(List<Map> wateList, int index) {

		Map jb = (Map) wateList.get(index);

		String imgDesc = (String) jb.get("imgDesc");

		return imgDesc;
	}


	@Override
	public AppResultDto releaseOperation(GoodsReleaseOpRecorInputDto dto,
										 HttpServletRequest request) {


		String userName = baseRedisService.get(request.getHeader("token"));

		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}

		User user = userManager.getUserByUsername2(userName);

		Long         decode_id = grDecodeId(dto.getId());
		GoodsRelease bill      = goodsReleaseManager.get(decode_id);


		//审批中或待放行状态（安保同意
		if (!bill.getReleaseStatus().equals(GoodsCodeConstants.ST_WAIT)) {
			return AppResultUtil.createErrorDto(AppConstants.AGREE_RELEASE, "只有待放行状态可以操作");
		}


		GoodsReleaseOpRecord record = new GoodsReleaseOpRecord();

		record.setCreateTime(new Date());
		record.setOperationType(dto.getOperationType());//操作类型 1同意 2不同意
		record.setReleaseUseId(user.getId().intValue());
		record.setTemperature(dto.getTemperature());
		record.setApplyPersonId(bill.getUserId());
		record.setOrgId(bill.getOrgId());
		record.setCompanyId(bill.getCompanyid().intValue());
		record.setReleasebillId(bill.getId().intValue());

		goodsReleaseOpRecordManager.save(record);

		if (dto.getOperationType().equals(1)) {
			scanDoNum(bill.getId());//同意放行计数
		}


		return AppResultUtil.createSuccesDto("操作成功", record);
	}

	@Override
	public AppResultDto refuse(GoodsReleaseBillInputDto dto, HttpServletRequest request) {

		log.info("GoodsReleaseServiceImpl refuse======");
		log.info("GoodsReleaseServiceImpl refuse[参数dto:]{}======",dto.toString());

		Long decode_id = grDecodeId(dto.getId());

		GoodsRelease bill = goodsReleaseManager.get(decode_id);

		if ((bill.getType() == null || bill.getRoleId() == null || bill.getSort() == null) && bill.getReleaseStatus().equals(10)) {
			return AppResultUtil.createErrorDto(AppConstants.AGREE_RELEASE, "未配置审核流程");
		}

		if (!(bill.getReleaseStatus().equals(GoodsCodeConstants.ST_AUDITING) || bill.getReleaseStatus().equals(GoodsCodeConstants.ST_WAIT))) {
			return AppResultUtil.createErrorDto(AppConstants.REFUSE_RELEASE, "拒绝放行失败，只有审批中或待放行状态可以拒绝放行");
		}

		bill.setReleaseStatus(GoodsCodeConstants.ST_REFUSE);

		String roleType = request.getParameter("roleType");

		//WxUser wxUser = scWxuserManager.getScWxuserByOpenId(dto.getOpenId());

		EnterpriseAudit record = new EnterpriseAudit();

		boolean isSecurity = false;//是否安保

		//角色类型(1客服 5安保
		if (StringUtils.isNotEmpty(roleType) && roleType.equals("5")) {
			isSecurity = true;
		} else if (StringUtils.isNotEmpty(roleType) && roleType.equals("1")) {

			//流程和鉴权管理
			if (dto.getBillFrom().equals(CodeConstants.WECHAT)) {

				if (bill.getType().equals(1)) {

					if (!bill.getRoleId().equals(dto.getRoleId())) {
						return AppResultUtil.createErrorDto(AppConstants.AGREE_RELEASE, "审核流程不符合");
					}

				} else {
					return AppResultUtil.createErrorDto(AppConstants.AGREE_RELEASE, "审核流程不符合");
				}

			} else {

				if (bill.getType().equals(2)) {

					if (!bill.getRoleId().equals(dto.getRoleId())) {
						return AppResultUtil.createErrorDto(AppConstants.AGREE_RELEASE, "审核流程不符合");
					}

				} else {
					return AppResultUtil.createErrorDto(AppConstants.AGREE_RELEASE, "审核流程不符合");
				}
			}
		}

		if (dto.getBillFrom().equals(CodeConstants.PC)) {

			Role role = roleManager.get(dto.getRoleId().longValue());

			User user = (User) request.getSession().getAttribute("UserCache");

			record.setCreator(Integer.parseInt(String.valueOf(user.getId())));
			record.setContent(role.getSucName() + " " + user.getFullName());//审批内容'

		} else if (dto.getBillFrom().equals(CodeConstants.WECHAT)) {

			VirPermConfig config = enterprisePermissionManager.get(dto.getRoleId().longValue());

			if (dto.getUserId() != null) {

				AppUser appUser = appUserManager.get(dto.getUserId());

				record.setCreator(dto.getUserId());
				record.setContent(config.getName() + " " + appUser.getUserName());//审批内容'

				bill.setCompanyHeadUser(appUser.getUserName() + "(已通过)");

			} else {

				WxUser wxUser = scWxuserManager.getScWxuserByOpenId(dto.getOpenId());

				record.setCreator(wxUser.getId());
				record.setContent(config.getName() + " " + wxUser.getNickName());//审批内容'

				bill.setCompanyHeadUser(wxUser.getNickName() + "(已通过)");
			}
//    		WxUser wxUser = scWxuserManager.getScWxuserByOpenId(dto.getOpenId());
//    		record.setCreator(wxUser.getId());
//    		record.setContent("企业负责人 "+wxUser.getNickName());//审批内容'
//    		bill.setCompanyHeadUser(wxUser.getNickName()+"(已拒绝)");
		} else if (dto.getBillFrom().equals(CodeConstants.ANDROID) || dto.getBillFrom().equals(CodeConstants.iOS)) {

			String userName = baseRedisService.get(request.getHeader("token"));

			if (userName == null) {
				return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
			}

			User user = userManager.getUserByUsername2(userName);

			record.setCreator(Integer.parseInt(String.valueOf(user.getId())));

			if (isSecurity) {

				record.setContent("安保 " + user.getFullName());//审批内容'

				bill.setReleaseUser(user.getId());//放行安保id 用来过滤
				bill.setReleaseDate(new Date());

			} else {

				Role role = roleManager.get(dto.getRoleId().longValue());

				String roleName = "物业";
				if(org.apache.commons.lang3.StringUtils.isNotBlank(role.getSucName())){
					roleName =  role.getSucName();
				}

				//record.setContent("客服 "+user.getFullName());//审批内容'
				record.setContent(roleName + " " + user.getFullName());//审批内容'
			}

			bill.setReleaseUserName(dto.getReleaseUserName());
		}

		record.setCreateTime(new Date());
		record.setType("3");// 类型 1企业入驻 2企业迁出 3物品放行
		record.setSourseId(Integer.parseInt(String.valueOf(bill.getId())));
		record.setReasonType(0);// 审批操作类型 1通过 0拒绝 3申请
		record.setRemark(dto.getRemark());

		goodsReleaseManager.updateModel(bill);
		enterpriseAuditManager.save(record);

		// 发拒绝的模板消息 给申请人
		// 配置模板
		if (null != bill.getCreatorBillId()) {
			goodsReleaseManager.sendRefuseWechat(bill, dto.getRemark());
		}

		return AppResultUtil.createSuccesDto(convert(bill));
	}

	private Long grDecodeId(String oldId) {

		Long decode_id = null;
		try {
			decode_id = Long.decode(GenPass.Decrypt(URLDecoder.decode(oldId, "UTF-8")));
		} catch (Exception e) {
			decode_id = Long.decode(oldId);
			e.printStackTrace();
		}
		return decode_id;
	}

	@Override
	public Integer findCountBy(Map<String, Object> params) {
		return goodsReleaseManager.findCountBy(params);
	}

	@Override
	public List<User> getReleaseUser(Integer orgId, String sysCodes) {
		List<User> users = userManager.findByFunction(orgId, sysCodes);
		return users;
	}

	/**
	 * 给客服发app审批消息
	 */
	@Async
	public void push(String id) throws Exception {

		log.info("WxGoodsReleaseController push======{}",id);

		//查询有物品审批权限的人
		Long         decode_id = grDecodeId(id);
		GoodsRelease bill      = goodsReleaseManager.get(decode_id);
		if (bill.getType() != null && bill.getRoleId() != null && bill.getSort() != null) {

			if (bill.getType().equals(2)) {

				List<User> users = new ArrayList<>();

				users = userManager.findByRoleId(bill.getRoleId(),bill.getOrgId());
				//		List<User> users = userManager.findByFunction(bill.getOrgId(),CodeConstants.RELEASEAD_PERMISSION);

				String title = "您有一个物品放行单需要审核";

				VirtualArchitecture vir = virtualArchManager.get(Integer.parseInt(String.valueOf(bill.getCompanyid())));

				String content = "申请人姓名：" + bill.getApplyUser() + "," + "放行企业:" + vir.getName();

				PushMessageHelper helper=new PushMessageHelper();
				helper.pushMessage(bill.getId(), CodeConstants.RELEASEAD_PERMISSION, users, title, content);
			} else {


				AppUser   user = appUserManager.get(bill.getUserId());
				//Long  virPermId  = user.getVirPermId();
				//Integer virPermId =  this.getGoodsConfigByTypes(Long.valueOf(bill.getOrgId()), "1");//配置是不是部门管理员
				Integer virPermId = 0;
				List<Map<String, Object>> listvirPermIds =  this.getGoodsConfigByTypes(Long.valueOf(bill.getOrgId()), "1");//配置是不是部门管理员
				if(listvirPermIds.size()>=1){
					virPermId = Integer.valueOf(listvirPermIds.get(0).get("roleId").toString().split(",")[0]);
				}
				boolean isDepPermId = false;
				if(null != virPermId){
					VirPermConfig config = enterprisePermissionManager.get(Long.valueOf(virPermId));
					if(null != config && StringUtils.isNotEmpty(config.getCode())){
						if(config.getCode().equals("BMGLY")){//部门管理员
							isDepPermId = true;
						}
					}
				}

				List<WxUser> wxUsers = new ArrayList<>();
				StringBuffer rankBuffer = new StringBuffer();
				if(isDepPermId){ //部门管理员
					//找到部门的rank
					if(null != user.getDepartmentId()){
						Department dept = deptManager.get(Long.valueOf(user.getDepartmentId()));
						if(null != dept && StringUtils.isNotEmpty(dept.getRank())){//用户部门的rank
							String rank = dept.getRank();
							String [] rankS = rank.split("-");

							String rankBj = "";
							if(rankS.length>1){
								rankBuffer.append("(");
								for(int i=0 ;i<rankS.length;i++){
									System.out.println(rankS[i]);
									rankBj =rankBj +  rankS[i] + "-";
									if(i==0){
										continue;
									}
									if(i == 1){
										rankBuffer.append(" dp.rank = '"+rankBj.replaceAll("[-]$", "")+"' ");
									}else if (i > 1){
										rankBuffer.append(" or dp.rank = '"+rankBj.replaceAll("[-]$", "")+"' ");
									}

								}
								rankBuffer.append(")");
							}

							if(StringUtils.isEmpty(rankBuffer.toString())){
								rankBuffer.append(" 1=2 ");//没有值不推送
							}
							System.out.println("rankBuffer.toString()=>"+rankBuffer.toString());
							wxUsers = scWxuserManager.getWxUserByPermId(bill.getRoleId(), bill.getCompanyid().intValue(),rankBuffer.toString());

						}
					}
				}else{

					wxUsers = scWxuserManager.getWxUserByPermId(bill.getRoleId(), bill.getCompanyid().intValue(),"");
				}

				//如果是部门管理员 要找本级-上级-上级-上级
				//如果是其他直接找有权限的用户
				log.info("WxGoodsReleaseController wxUsers.长度======{}",wxUsers.size());
				for (WxUser wxUser : wxUsers) {
					goodsReleaseManager.sendNextAgreeWechat(bill, wxUser);
				}

			}
		}
	}

	/**
	 * TODO 标记 查询 某项目 有没有某类型 流程权限?
	 *
	 * @param orgId
	 * @param applyType
	 * @return
	 */
	@Override
	public boolean getGoodsConfig(Long orgId, Integer applyType) {

		// TODO 标记 1,2是什么鬼 查数据库得知 1.企业审核;2.物业审核 TODO 3,4 又是什么
		String types = "1,2";

		// 电子企业? 这个说明是什么鬼? goodconfig 为3
		if (applyType == 1) {
			types = "3,4";
		}

		List<Map<String, Object>> list = enterprisePermissionDao.getGoodsConfig(orgId, types,"");

		if (list != null && list.size() > 0) {
			return true;
		}

		return false;
	}

	/**
	 * TODO 标记 查询 某项目 有没有某类型 流程权限?
	 *
	 * @param orgId
	 * @return
	 */
	@Override
	public List<Map<String, Object>> getGoodsConfigByTypes(Long orgId, String types) {

		List<Map<String, Object>> list  = enterprisePermissionDao.getGoodsConfigByTypes(orgId, types);

		return list;
	}


	@Override
	public boolean check(Integer virtualArchId) {
		Integer flag = enterprisePermissionDao.check(virtualArchId);

		if (flag > 0) {
			return true;
		}
		return false;
	}

	@Override
	public void scanDoNum(Long id) {
		GoodsRelease bill = goodsReleaseManager.get(id);
		bill.setPassNum(bill.getPassNum() + 1);
		goodsReleaseManager.updateModel(bill);
	}

	@Override
	public List<GoodsRelease> getGoodsReleaseByParams(Map<String, Object> params) {

		return goodsReleaseManager.getGoodsReleaseByParams(params);
	}

	@Override
	public GoodsReleaseVo getGoodsCompany(Long orgId) {
		GoodsReleaseVo vo=new GoodsReleaseVo();
		List<Map<String, Object>> list= companyDao.getGoodsCompany(orgId);
		if (list != null && list.size() > 0) {

			if(null != list.get(0) && null != list.get(0).get("companyName")){

				String companyName= list.get(0).get("companyName").toString();

				vo.setType("1");
				if(null != list.get(0) && null != list.get(0).get("type")){
					vo.setType(list.get(0).get("type").toString());
				}

				if(companyName!=null){
					vo.setGoodsCompany(Arrays.asList(companyName.split(",")));
				}
			}

		}
		return vo;
	}

	@Override
	public AppResultDto reportExcel(Map<String, Object> params) {

		//return goodsReleaseManager.reportExcel(params);


		List<Map<String, Object>> list      = goodsReleaseManager.reportExcel(params);
		HSSFWorkbook              wb        = new HSSFWorkbook();
		String                    sheetName = "申请管理";
		String[] titles = {"申请编码", "申请时间", "申请人", "企业", "籍贯",
				"人员类型", "何时离开本市,", "何时返回本市", "春节假期居住地",
				"有无去过疫情严重区域", "7日内核酸检测结果","是否有如下症状", "其他情况备注", "审批状态"};
		String[] fieldNames = {"releaseCode", "createTime", "applyUserInfo", "companyName", "nativePlace",
				"personTypeName", "leaveCityTime", "returnCityTime", "habitation",
				"isToepidemicName", "isSevenDayCheckResultName","symptomName", "releaseDesc", "releaseStatus"};
		try {
			File file = getApplyPassManageFile();
			ExcelUtils.exportExcel(file, wb, sheetName, list, titles, fieldNames, "1");
			return AppResultUtil.createSuccesDto(file.getPath());
		} catch (Exception e) {
			log.info("ConditionerAddTimeServiceImpl exportReportList ======");
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "导出数据失败");
		}


	}


	@Override
	public AppResultDto reportStatistics(Map<String, Object> params) {

		//return goodsReleaseManager.reportExcel(params);


		List<Map<String, Object>> list       = goodsReleaseManager.reportStatistics(params);
		HSSFWorkbook              wb         = new HSSFWorkbook();
		String                    sheetName  = "通行统计";
		String[]                  titles     = {"通行日期", "通行企业", "通行人数", "通行次数"};
		String[]                  fieldNames = {"createTime", "virName", "applyPersonNum", "passNum"};
		try {
			File file = getReleaseStatisticsFile();
			ExcelUtils.exportExcel(file, wb, sheetName, list, titles, fieldNames, "1");
			return AppResultUtil.createSuccesDto(file.getPath());
		} catch (Exception e) {
			log.info("ConditionerAddTimeServiceImpl exportReportList ======");
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "导出数据失败");
		}


	}

	@Override
	public AppResultDto reportRecord(Map<String, Object> params) {

		//return goodsReleaseManager.reportExcel(params);


		List<Map<String, Object>> list       = goodsReleaseManager.reportRecord(params);
		HSSFWorkbook              wb         = new HSSFWorkbook();
		String                    sheetName  = "通行记录";
		String[]                  titles     = {"通行时间", "通行企业", "通行人", "手机号", "体温", "状态", "放行人"};
		String[]                  fieldNames = {"createTime", "virName", "applyUser", "applyTel", "temperature", "status", "releaseUser"};
		try {
			File file = getRecordFile();
			ExcelUtils.exportExcel(file, wb, sheetName, list, titles, fieldNames, "1");
			return AppResultUtil.createSuccesDto(file.getPath());
		} catch (Exception e) {
			log.info("ConditionerAddTimeServiceImpl exportReportList ======");
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "导出数据失败");
		}


	}

	public File getRecordFile() throws IOException {
		String classpath = getClass().getResource("/").getPath();
		log.info("begin exportExcel  classpath:" + classpath);
		if (StringUtils.isNotEmpty(classpath)) {
			log.info("begin exportExcel  CLIENTNO:" + CLIENTNO);
			if ("dev".equals(CLIENTNO)) {
				String str = classpath.substring(0, 1);
				if ("/".equals(str)) {
					classpath = classpath.replaceFirst("/", "");
				}
			}
		}
		log.info("path:" + classpath);
		String webappRoot = classpath.replaceAll("WEB-INF/classes", "");
		log.info("path:" + webappRoot);
		String path = webappRoot + "upload/ApplyPassRecord.xls";
		if (StringUtils.isNotEmpty(path)) {
			path = path.replace("//", "/");
		}

		log.info("path:" + path);
		File file = new File(new ExcelUtils().getPath(path));
		System.out.println("path:" + path);
		return file;
	}


	public File getGoodsReleasListFile() throws IOException {
		String classpath = getClass().getResource("/").getPath();
		log.info("begin exportExcel  classpath:" + classpath);
		if (StringUtils.isNotEmpty(classpath)) {
			log.info("begin exportExcel  CLIENTNO:" + CLIENTNO);
			if ("dev".equals(CLIENTNO)) {
				String str = classpath.substring(0, 1);
				if ("/".equals(str)) {
					classpath = classpath.replaceFirst("/", "");
				}
			}
		}
		log.info("path:" + classpath);
		String webappRoot = classpath.replaceAll("WEB-INF/classes", "");
		log.info("path:" + webappRoot);
		String path = webappRoot + "upload/GoodsReleasList.xls";
		if (StringUtils.isNotEmpty(path)) {
			path = path.replace("//", "/");
		}

		log.info("path:" + path);
		File file = new File(new ExcelUtils().getPath(path));
		System.out.println("path:" + path);
		return file;
	}


	public File getApplyPassManageFile() throws IOException {
		String classpath = getClass().getResource("/").getPath();
		log.info("begin exportExcel  classpath:" + classpath);
		if (StringUtils.isNotEmpty(classpath)) {
			log.info("begin exportExcel  CLIENTNO:" + CLIENTNO);
			if ("dev".equals(CLIENTNO)) {
				String str = classpath.substring(0, 1);
				if ("/".equals(str)) {
					classpath = classpath.replaceFirst("/", "");
				}
			}
		}
		log.info("path:" + classpath);
		String webappRoot = classpath.replaceAll("WEB-INF/classes", "");
		log.info("path:" + webappRoot);
		String path = webappRoot + "upload/ApplyPassManage.xls";
		if (StringUtils.isNotEmpty(path)) {
			path = path.replace("//", "/");
		}

		log.info("path:" + path);
		File file = new File(new ExcelUtils().getPath(path));
		System.out.println("path:" + path);
		return file;
	}

	public File getReleaseStatisticsFile() throws IOException {
		String classpath = getClass().getResource("/").getPath();
		log.info("begin exportExcel  classpath:" + classpath);
		if (StringUtils.isNotEmpty(classpath)) {
			log.info("begin exportExcel  CLIENTNO:" + CLIENTNO);
			if ("dev".equals(CLIENTNO)) {
				String str = classpath.substring(0, 1);
				if ("/".equals(str)) {
					classpath = classpath.replaceFirst("/", "");
				}
			}
		}
		log.info("path:" + classpath);
		String webappRoot = classpath.replaceAll("WEB-INF/classes", "");
		log.info("path:" + webappRoot);
		String path = webappRoot + "upload/ReleaseStatistics.xls";
		if (StringUtils.isNotEmpty(path)) {
			path = path.replace("//", "/");
		}

		log.info("path:" + path);
		File file = new File(new ExcelUtils().getPath(path));
		System.out.println("path:" + path);
		return file;
	}

	@Override
	public AppResultDto exportList(Map<String, Object> params) {


		//List<Map<String, Object>> list      = goodsReleaseManager.reportExcel(params);
		//Page             page = conditionerAddTimeManager.reportDetailFindPageBy(params, 10000, 1);
		Page             page = this.findPageBy(params, 10000, 1);
		List<Map<String, Object>> list  = page.getItems();
		HSSFWorkbook              wb        = new HSSFWorkbook();
		String                    sheetName = "放行记录";
		String[] titles = {"放行编号","发起时间", "发起人", "手机号码", "放行企业", "房间号",
				"放行描述", "放行物品", "状态","审核放行记录","申请图片(以';'分隔)","放行图片(以';'分隔)"};
		String[] fieldNames = {"releaseCode", "createTime", "applyUser", "applyTel","companyName","roomNames",
				"releaseDesc","releaseGoods", "releaseStatusName","operateStrs","applypicUrl","releasepicUrl"};
		try {
			File file = getGoodsReleasListFile();

			ExcelUtils.exportExcel(file, wb, sheetName, list, titles, fieldNames, "0");
			return AppResultUtil.createSuccesDto(file.getPath());
		} catch (Exception e) {
			log.info("ConditionerAddTimeServiceImpl exportReportList ======");
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "导出数据失败");
		}


	}


}
