package com.yeejoin.amos.boot.module.cylinder.flc.biz.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.dto.AttachmentDto;
import com.yeejoin.amos.boot.module.common.biz.service.impl.SourceFileServiceImpl;
import com.yeejoin.amos.boot.module.cylinder.api.dto.CylinderFillingMessageModel;
import com.yeejoin.amos.boot.module.cylinder.api.dto.PageParam;
import com.yeejoin.amos.boot.module.cylinder.api.service.CylinderFillingMessageService;
import com.yeejoin.amos.boot.module.cylinder.flc.api.dto.*;
import com.yeejoin.amos.boot.module.cylinder.flc.biz.service.impl.*;
import com.yeejoin.amos.boot.module.cylinder.api.dto.TzBaseEnterpriseInfoDto;
import com.yeejoin.amos.boot.module.cylinder.api.entity.BaseUnitLicence;
import com.yeejoin.amos.boot.module.cylinder.api.entity.ESCylinderFillingRecordDto;
import com.yeejoin.amos.boot.module.cylinder.api.entity.ESCylinderInfoDto;
import com.yeejoin.amos.boot.module.cylinder.api.entity.MsgLog;
import com.yeejoin.amos.boot.module.cylinder.biz.service.impl.BaseUnitLicenceServiceImpl;
import com.yeejoin.amos.boot.module.cylinder.biz.service.impl.ESCylinderServiceImpl;
import com.yeejoin.amos.boot.module.cylinder.biz.service.impl.TzBaseEnterpriseInfoServiceImpl;
import com.yeejoin.amos.boot.module.cylinder.flc.api.entity.CylinderInfo;
import com.yeejoin.amos.boot.module.cylinder.flc.api.entity.CylinderUnit;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 气瓶基本信息
 *
 * @author system_generator
 * @date 2021-12-14
 */
@RestController
@Api(tags = "气瓶基本信息Api")
@RequestMapping(value = "/cylinder-info")
public class CylinderInfoController extends BaseController {

	@Autowired
    CylinderInfoServiceImpl cylinderInfoServiceImpl;

	@Autowired
    CylinderUnitServiceImpl cylinderUnitServiceImpl;

	@Autowired
    CylinderInspectionServiceImpl cylinderInspectionServiceImpl;

	@Autowired
    CylinderFillingRecordServiceImpl cylinderFillingRecordServiceImpl;

	@Autowired
	ESCylinderServiceImpl esCylinderService;

	private Map<Integer, String> regionMap;

	private Map<String,String> licenceDateMap;

	@Autowired
	BaseUnitLicenceServiceImpl baseUnitLicenceService;

	@Autowired
	private SourceFileServiceImpl sourceFileService;

	@Autowired
	DataDictionaryServiceImpl iDataDictionaryService;

	@Autowired
	CylinderTagsServiceImpl cylinderTagsServiceImpl;

	@Autowired
	TzBaseEnterpriseInfoServiceImpl baseEnterpriseInfoService;

	@Autowired
	private RedisUtils redisUtils;

	@Autowired
	private CylinderAreaDataServiceImpl cylinderAreaDataService;
	@Autowired
	CylinderFillingMessageService cylinderFillingMessageService;
	/**
	 * 新增气瓶基本信息
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增气瓶基本信息", notes = "新增气瓶基本信息")
	public ResponseModel<CylinderInfoDto> save(@RequestBody CylinderInfoDto model) {
		model = cylinderInfoServiceImpl.createWithModel(model);
		return ResponseHelper.buildResponse(model);
	}

	/**
	 * 根据sequenceNbr更新
	 *
	 * @param sequenceNbr 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PutMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新气瓶基本信息", notes = "根据sequenceNbr更新气瓶基本信息")
	public ResponseModel<CylinderInfoDto> updateBySequenceNbrCylinderInfo(@RequestBody CylinderInfoDto model,
			@PathVariable(value = "sequenceNbr") Long sequenceNbr) {
		model.setSequenceNbr(sequenceNbr);
		return ResponseHelper.buildResponse(cylinderInfoServiceImpl.updateWithModel(model));
	}

	/**
	 * 根据sequenceNbr删除
	 *
	 * @param sequenceNbr 主键
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@DeleteMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除气瓶基本信息", notes = "根据sequenceNbr删除气瓶基本信息")
	public ResponseModel<Boolean> deleteBySequenceNbr(HttpServletRequest request,
			@PathVariable(value = "sequenceNbr") Long sequenceNbr) {
		return ResponseHelper.buildResponse(cylinderInfoServiceImpl.removeById(sequenceNbr));
	}

	/**
	 * 根据sequenceNbr查询
	 *
	 * @param sequenceNbr 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个气瓶基本信息", notes = "根据sequenceNbr查询单个气瓶基本信息")
	public ResponseModel<CylinderInfoDto> selectOne(@PathVariable Long sequenceNbr) {
		return ResponseHelper.buildResponse(cylinderInfoServiceImpl.queryBySeq(sequenceNbr));
	}

	/**
	 * 列表分页查询
	 *
	 * @param current 当前页
	 * @param current 每页大小
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/page")
	@ApiOperation(httpMethod = "GET", value = "气瓶基本信息分页查询", notes = "气瓶基本信息分页查询")
	public ResponseModel<Page<CylinderInfoDto>> queryForPage(@RequestParam(value = "current") int current,
			@RequestParam(value = "size") int size) {
		Page<CylinderInfoDto> page = new Page<CylinderInfoDto>();
		page.setCurrent(current);
		page.setSize(size);
		return ResponseHelper.buildResponse(cylinderInfoServiceImpl.queryForCylinderInfoPage(page));
	}

	/**
	 * 列表全部数据查询
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "气瓶基本信息列表全部数据查询", notes = "气瓶基本信息列表全部数据查询")
	@GetMapping(value = "/list")
	public ResponseModel<List<CylinderInfoDto>> selectForList() {
		return ResponseHelper.buildResponse(cylinderInfoServiceImpl.queryForCylinderInfoList());
	}

//	/**
//	 * 获取气瓶增加减少总量及环比
//	 *
//	 * @return
//	 */
//	@TycloudOperation(ApiLevel = UserType.AGENCY)
//	@GetMapping(value = "/getCylinderInfo/{regionCode}")
//	@ApiOperation(httpMethod = "GET", value = "获取气瓶增加减少总量及环比1", notes = "获取气瓶增加减少总量及环比")
//	public ResponseModel<Map> getCylinderInfo(@PathVariable String regionCode) {
//		Map result = new HashMap();
//		Integer cylinderTotal = cylinderInfoServiceImpl.getInfoTotalByRegionCode(regionCode);
//		Double lastInfoTotal = Double.valueOf(cylinderInfoServiceImpl.getLastMonthInfoTotal(regionCode));
//		Double monthBeforeLastInfo = Double.valueOf(cylinderInfoServiceImpl.getMonthBeforeLastInfoTotal(regionCode));
//		Double percent = 0d;
//		if(monthBeforeLastInfo != 0) {
//			percent = (lastInfoTotal - monthBeforeLastInfo) / monthBeforeLastInfo;
//			BigDecimal bg = new BigDecimal(percent);
//			percent = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//		}
//		result.put("unitTotal",cylinderTotal);
//		result.put("change",lastInfoTotal-monthBeforeLastInfo);
//		result.put("percent",percent);
//		return ResponseHelper.buildResponse(result);
//	}
//
//	/**
//	 * 获取企业增加减少总量及环比
//	 *
//	 * @return
//	 */
//	@TycloudOperation(ApiLevel = UserType.AGENCY)
//	@GetMapping(value = "/getCylinderUnitInfo/{regionCode}")
//	@ApiOperation(httpMethod = "GET", value = "获取企业增加减少总量及环比1", notes = "获取企业增加减少总量及环比")
//	public ResponseModel<Map> getCylinderUnitInfo1(@PathVariable String regionCode) {
//		Map result = new HashMap();
//		Integer cylinderUnitTotal = cylinderUnitServiceImpl.getUnitTotalByRegionCode(regionCode);
//		Double lastUnitTotal = Double.valueOf(cylinderUnitServiceImpl.getLastMonthUnitTotal(regionCode));
//		Double monthUnitLastInfo = Double.valueOf(cylinderUnitServiceImpl.getMonthBeforeLastUnitTotal(regionCode));
//		Double percent = 0d;
//		if(monthUnitLastInfo != 0) {
//			percent = (lastUnitTotal - monthUnitLastInfo) / monthUnitLastInfo;
//			BigDecimal bg = new BigDecimal(percent);
//			percent = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//		}
//		result.put("unitTotal",cylinderUnitTotal);
//		result.put("change",lastUnitTotal-monthUnitLastInfo);
//		result.put("percent",percent);
//		return ResponseHelper.buildResponse(result);
//	}

	/**
	 * 获取气瓶增加减少总量及环比
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getCylinderInfo")
	@ApiOperation(httpMethod = "GET", value = "获取气瓶增加减少总量及环比", notes = "获取气瓶增加减少总量及环比")
	public ResponseModel<Boolean> getCylinderInfo1() {
		cylinderInfoServiceImpl.getCylinderInfo();
		return ResponseHelper.buildResponse(true);
	}

	/**
	 * 获取企业增加减少总量及环比
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getCylinderUnitInfo")
	@ApiOperation(httpMethod = "GET", value = "获取企业增加减少总量及环比", notes = "获取企业增加减少总量及环比")
	public ResponseModel<Boolean> getCylinderUnitInfo() {
		cylinderInfoServiceImpl.getCylinderUnitInfo();
		return ResponseHelper.buildResponse(true);
	}

//	// 数据完整性计算 气瓶企业信息 气瓶基本信息 标签 检验 充装 充装审核
//	/**
//	 * 数据完整性计算
//	 *
//	 * @return
//	 */
//	@TycloudOperation(ApiLevel = UserType.AGENCY)
//	@GetMapping(value = "/addIntegrityInfo")
//	@ApiOperation(httpMethod = "GET", value = "数据完整性计算", notes = "数据完整性计算")
//	public ResponseModel<Boolean> addIntegrityInfo() {
//		// 气瓶企业单位 20字段
////		List<CylinderUnit> unitList = cylinderUnitServiceImpl.list();
////		unitList.stream().forEach(u -> {
////
////			double total = 20;
////			double count = 0d;
////			if(StringUtils.isNotEmpty(u.getRegionCode())) count ++;
////			if(StringUtils.isNotEmpty(u.getUnitName())) count ++;
////			if(u.getUnitType() != null) count ++;
////			if(StringUtils.isNotEmpty(u.getCreditCode())) count ++;
////			if(StringUtils.isNotEmpty(u.getAddress())) count ++;
////			if(StringUtils.isNotEmpty(u.getUnitPerson())) count ++;
////			if(StringUtils.isNotEmpty(u.getPersonMobilePhone())) count ++;
////			if(StringUtils.isNotEmpty(u.getPersonTelephone())) count ++;
////			if(StringUtils.isNotEmpty(u.getPostalCode())) count ++;
////			if(StringUtils.isNotEmpty(u.getUnitAbbreviation())) count ++;
////			if(StringUtils.isNotEmpty(u.getFillingLicense())) count ++;
////			if(u.getFillingPermitDate() != null) count ++;
////			if(StringUtils.isNotEmpty(u.getFillingPermScope())) count ++;
////			if(StringUtils.isNotEmpty(u.getInspectionLicense())) count ++;
////			if(StringUtils.isNotEmpty(u.getInspectionScope())) count ++;
////			if(u.getEffectiveDate() != null) count ++;
////			if(u.getManufacturingDate() != null) count ++;
////			if(StringUtils.isNotEmpty(u.getManufacturingLicense())) count ++;
////			if(StringUtils.isNotEmpty(u.getManufacturingScope())) count ++;
////			if(StringUtils.isNotEmpty(u.getManufacturingUnitCode())) count ++;
////
////			double integrity = count / total;
////			BigDecimal bg = new BigDecimal(integrity);
////			integrity = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
////			u.setIntegrity(integrity);
////			cylinderUnitServiceImpl.updateById(u);
////		});
//		//气瓶基本信息 17 字段
////		List<CylinderInfo> infoList = cylinderInfoServiceImpl.list();
////		infoList.stream().forEach(i -> {
////			double total = 17;
////			double count = 0d;
////
////			if(StringUtils.isNotEmpty(i.getUnitName())) count ++;
////			if(StringUtils.isNotEmpty(i.getFactoryNum())) count ++;
////			if(i.getCylinderStatus() != null) count ++;
////			if(i.getCylinderVariety() != null) count ++;
////			if(StringUtils.isNotEmpty(i.getQrCode())) count ++;
////			if(StringUtils.isNotEmpty(i.getElectronicLabelCode())) count ++;
////			if(StringUtils.isNotEmpty(i.getFillingMedium())) count ++;
////			if(i.getPressure() != null) count ++;
////			if(i.getVolume() != null) count ++;
////			if(i.getManufacturingDate() != null) count ++;
////			if(i.getManufacturingUnit() != null) count ++;
////			if(StringUtils.isNotEmpty(i.getLicense())) count ++;
////			if(i.getCylinderWeight() != null) count ++;
////			if(StringUtils.isNotEmpty(i.getUnitInnerCode())) count ++;
////			if(i.getInspectionDate() != null) count ++;
////			if(i.getNextInspectionDate() != null) count ++;
////			if(StringUtils.isNotEmpty(i.getSequenceCode())) count ++;
////			double integrity = count / total;
////			BigDecimal bg = new BigDecimal(integrity);
////			integrity = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
////			i.setIntegrity(integrity);
////			cylinderInfoServiceImpl.updateById(i);
////
////
////		});
//
//		// 气瓶标签信息 5
////		List<CylinderTags> infoList = cylinderTagsServiceImpl.list();
////		infoList.stream().forEach(i -> {
////			double total = 5;
////			double count = 0d;
////			if(StringUtils.isNotEmpty(i.getUnitName())) count ++;
////			if(StringUtils.isNotEmpty(i.getFactoryNum())) count ++;
////			if(StringUtils.isNotEmpty(i.getQrCode())) count ++;
////			if(StringUtils.isNotEmpty(i.getElectronicLabelCode())) count ++;
////			if(StringUtils.isNotEmpty(i.getSequenceCode())) count ++;
////			double integrity = count / total;
////			BigDecimal bg = new BigDecimal(integrity);
////			integrity = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
////			i.setIntegrity(integrity);
////			cylinderTagsServiceImpl.updateById(i);
////			});
//		// 气瓶检验信息 7 暂无数据
//		// 气瓶充装前检查 13
//		Integer totalCount = cylinderFillingServiceImpl.count();
//		IPage<CylinderFilling> fillingPage = new Page<>();
//		Integer times = 0;
//		if(ValidationUtil.isEmpty(totalCount) && totalCount != 0) {
//			times = totalCount/1000;
//			int last = totalCount%1000;
//			if(last > 0 ) {
//				times ++;
//			}
//		} else if(totalCount != 0) {
//			times = totalCount;
//		}
//
//		for(int j = 0; j <= times ;  j ++  ) {
//			fillingPage.setCurrent(j);
//			fillingPage.setSize(1000);
//			fillingPage =  cylinderFillingServiceImpl.page(fillingPage);
//			for (CylinderFilling i:fillingPage.getRecords()
//			) {
//				double total = 13;
//				double count = 0d;
//				if(StringUtils.isNotEmpty(i.getFillingUnitName())) count ++;
//				if(StringUtils.isNotEmpty(i.getSequenceCode())) count ++;
//				if(StringUtils.isNotEmpty(i.getIsValid())) count ++;
//				if(i.getSame() != null) count ++;
//				if(i.getIsRegulations() != null) count ++;
//				if(i.getIsComplianceWithgbt() != null) count ++;
//				if(i.getHaveStillPressure() != null) count ++;
//				if(i.getIsComplete() != null) count ++;
//				if(i.getHaveSecurityDocuments() != null) count ++;
//				if(StringUtils.isNotEmpty(i.getInspectorUser())) count ++;
//				if(i.getInspectionDate() != null) count ++;
//				double integrity = count / total;
//				BigDecimal bg = new BigDecimal(integrity);
//				integrity = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//				i.setIntegrity(integrity);
//				cylinderFillingServiceImpl.updateById(i);
//			}
//		}
//
//		return ResponseHelper.buildResponse(true);
//	}

	/**
	 * 数据完整性同步
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/addIntegrityData")
	@ApiOperation(httpMethod = "GET", value = "数据完整性同步", notes = "数据完整性同步")
	public ResponseModel<Boolean> addIntegrityData() {
		cylinderInfoServiceImpl.addIntegrityData();
		return ResponseHelper.buildResponse(true);
	}

	/**
	 * 数据完整性同步
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/synAreaData")
	@ApiOperation(httpMethod = "GET", value = "同步区域数据", notes = "同步区域数据")
	public ResponseModel<Boolean> synAreaData() {
		cylinderInfoServiceImpl.synAreaData();
		return ResponseHelper.buildResponse(true);
	}

	/**
	 * 装卸液体数据同步
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/synFillingUnloadData")
	@ApiOperation(httpMethod = "GET", value = "装卸液体数据同步", notes = "装卸液体数据同步")
	public ResponseModel<Boolean> synFillingUnloadData() {
		cylinderInfoServiceImpl.synFillingUnloadData();
		return ResponseHelper.buildResponse(true);
	}

	/**
	 * 列表分页查询
	 *
	 * @param pageNum  当前页
	 * @param pageSize 每页大小
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/cyinderRecordList")
	@ApiOperation(httpMethod = "GET", value = "获取登陆人所在气瓶充装信息", notes = "获取登陆人所在气瓶充装信息")
	public ResponseModel<IPage<CylinderFillingRecordDto>> cyinderRecordList(
			@RequestParam(value = "pageNum") int pageNum, @RequestParam(value = "pageSize") int pageSize, String sort,
			CylinderFillingRecordDto cylinderFillingRecordDto) {
		Page<CylinderFillingRecordDto> page = new Page<>();
		page.setCurrent(pageNum);
		page.setSize(pageSize);
		String sortParam = "";
		String sortRule = "";
		if (sort != null) { // 排序失效
			String[] date = sort.split(",");
			if (date[1].equals("ascend")) {
				sortParam = "r." + RedisKey.humpToLine(date[0]);
				sortRule = "asc";
			} else {
				sortParam = "r." + RedisKey.humpToLine(date[0]);
				sortRule = "desc";
			}
		} else {
			sortParam = "r.sync_date";
			sortRule = "desc";
		}
		if (StringUtils.isEmpty(cylinderFillingRecordDto.getSequenceCode())) {
			cylinderFillingRecordDto.setAppId("9B150BB7D0C21A7A62BD6837E14A44BF");
		}
		Page<CylinderFillingRecordDto> pageBean = cylinderFillingRecordServiceImpl.queryListByQueryDto(page,
				cylinderFillingRecordDto, sortParam, sortRule);
		Page<CylinderFillingRecordDto> result = new Page<>(pageNum, pageSize);
		long totle = pageBean.getTotal();
		result.setRecords(pageBean.getRecords());
		result.setTotal(totle);
		return ResponseHelper.buildResponse(result);
	}

	/**
	 * 气瓶基本信息
	 *
	 * @param pageNum  当前页
	 * @param pageSize 每页大小
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/cyinderInfoList")
	@ApiOperation(httpMethod = "GET", value = "获取登陆人所在气瓶基本信息", notes = "获取登陆人所在气瓶基本信息")
	public ResponseModel<IPage<CylinderInfoDto>> cyinderInfoList(@RequestParam(value = "pageNum") String pageNum,
			@RequestParam(value = "pageSize") String pageSize, String sort, CylinderInfoDto cylinderInfoDto) {
		List<String> appids = new ArrayList<>();
		FeignClientResult<AgencyUserModel> result1= Privilege.agencyUserClient.getme();
		if(result1.getResult()!=null) {
			List<CompanyModel> list = result1.getResult().getCompanys();
			if (list != null && !list.isEmpty()) {
				CompanyModel company = list.get(0);
				if(company.getCompanyCode().length()>6) {
					cylinderInfoDto.setCreditCode(company.getCompanyCode());
				}
			}
		}
		if(ValidationUtil.isEmpty(cylinderInfoDto.getRegionCode()) && ValidationUtil.isEmpty(cylinderInfoDto.getCreditCode()) && cylinderInfoDto.getIsWarn()==0){
			return ResponseHelper.buildResponse(new Page<CylinderInfoDto>(Long.valueOf(pageNum),Long.valueOf(pageSize)));
		}
		QueryWrapper<CylinderInfo> cylinderInfoQueryWrapper = new QueryWrapper<>();
		if (StringUtils.isNotEmpty(cylinderInfoDto.getRegionCode())) {
			List<CylinderUnit> unitList = cylinderUnitServiceImpl.list(new LambdaQueryWrapper<CylinderUnit>()
					.like(CylinderUnit::getRegionCode, cylinderInfoDto.getRegionCode()));
			unitList.forEach(u -> {
				appids.add(u.getAppId());
			});
			if (appids.size() == 0) {
				appids.add("-1");
			}
			cylinderInfoDto.setAppIds(appids);
		}else {
			if (!ObjectUtils.isEmpty(cylinderInfoDto.getAppId())){
				appids.add(cylinderInfoDto.getAppId());
			}
		}



//		setQueryWrapper(cylinderInfoQueryWrapper, cylinderInfoDto, sort);
		Page<CylinderInfoDto> pageBean;
		if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
			pageBean = new Page<>(0, Long.MAX_VALUE);
		} else {
			pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
		}
		if(cylinderInfoDto.getIsWarn()!=0){
			pageBean = cylinderInfoServiceImpl.cyinderOutInfoList(pageBean,cylinderInfoDto,sort,appids);
		} else {
			pageBean = cylinderInfoServiceImpl.cyinderInfoList(pageBean,cylinderInfoDto,sort,appids);
		}
		return ResponseHelper.buildResponse(pageBean);
//		IPage<CylinderInfo> page;
//		if (cylinderInfoDto.getIsWarn() == 0) {
//			page = cylinderInfoServiceImpl.page(pageBean, cylinderInfoQueryWrapper);
//		} else {
//			page = cylinderInspectionServiceImpl.queryOutOfDateCylinder(pageBean, cylinderInfoDto.getAppId());
//		}
////		int num = cylinderInfoServiceImpl.count(cylinderInfoQueryWrapper);
////		pageBean.setTotal(num);
//
//		IPage<CylinderInfoDto> result = BeanDtoVoUtils.cyinderInfoIPageDto(page);
//		result.getRecords().forEach(i -> {
//			DataDictionary fillingMedia = iDataDictionaryService.getOne(new LambdaQueryWrapper<DataDictionary>()
//					.eq(DataDictionary::getCode, i.getFillingMedia()).eq(DataDictionary::getType, "CZJZMC"));
//			i.setFillingMediaName(fillingMedia != null ? fillingMedia.getName() : null);
//			DataDictionary cylinderVariety = iDataDictionaryService.getOne(new LambdaQueryWrapper<DataDictionary>()
//					.eq(DataDictionary::getSequenceNbr, i.getCylinderVariety()));
//			i.setCylinderVarietyName(cylinderVariety != null ? cylinderVariety.getName() : null);
//			DataDictionary cylinderStatus = iDataDictionaryService.getOne(
//					new LambdaQueryWrapper<DataDictionary>().eq(DataDictionary::getSequenceNbr, i.getCylinderStatus()));
//			i.setCylinderStatusStr(cylinderStatus != null ? cylinderStatus.getName() : null);
//			CylinderTags cylinderTags = cylinderTagsServiceImpl.getOne(
//					new LambdaQueryWrapper<CylinderTags>().eq(CylinderTags::getSequenceCode, i.getSequenceCode()));
//			i.setQrCode(cylinderTags != null ? cylinderTags.getQrCode() : null);
//			i.setElectronicLabelCode(cylinderTags != null ? cylinderTags.getElectronicLabelCode() : null);
//		});
//		return ResponseHelper.buildResponse(result);
	}

    /**
     * 气瓶基本信息存入es
     *
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping(value = "/saveCyinderInfo")
    @ApiOperation(httpMethod = "GET", value = "气瓶基本信息存入es", notes = "气瓶基本信息存入es")
    public void saveCyinderInfo() {
		Page<CylinderInfoDto> cylinderInfoPage = new Page<>();
		Integer count = cylinderInfoServiceImpl.getInfoTotal();
		Integer times = 0;
		if (count != 0) {
			times = count / 1000;
			int last = count % 1000;
			if (last > 0) {
				times++;
			}
		} else {
			return;
		}
		for (int i = 0; i <= times; i++) {
			cylinderInfoPage.setCurrent(0);
			cylinderInfoPage.setSize(1000);
			cylinderInfoPage = cylinderInfoServiceImpl.getCyinderInfoList(cylinderInfoPage);
			if (!ObjectUtils.isEmpty(cylinderInfoPage) && !ObjectUtils.isEmpty(cylinderInfoPage.getRecords())) {
				cylinderInfoServiceImpl.saveCylinderInfo2ES(cylinderInfoPage.getRecords());
			}
		}
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @GetMapping(value = "/getCyinderInfo")
    @ApiOperation(httpMethod = "GET", value = "气瓶基本信息存入es入口", notes = "气瓶基本信息存入es入口")
    public ResponseModel getCyinderInfo() {
        Page<CylinderInfoDto> cylinderInfoPage = new Page<>();
        cylinderInfoPage.setCurrent(1);
        cylinderInfoPage.setSize(1000);
        cylinderInfoPage = cylinderInfoServiceImpl.getCyinderInfoList(cylinderInfoPage);
		if (!ObjectUtils.isEmpty(cylinderInfoPage) && cylinderInfoPage.getRecords().size() > 0) {
			cylinderInfoServiceImpl.saveCylinderInfo2ES(cylinderInfoPage.getRecords());
		}
        return ResponseHelper.buildResponse(true);
    }


    /**
     * 气瓶基本信息
     *
     * @param pageNum  当前页
     * @param pageSize 每页大小
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getEsCyinderInfoList")
    @ApiOperation(httpMethod = "GET", value = "获取登陆人所在气瓶基本信息", notes = "获取登陆人所在气瓶基本信息")
    public ResponseModel<Page<ESCylinderInfoDto>> getEsCyinderInfoList(@RequestParam(value = "pageNum") int pageNum,
                                                                        @RequestParam(value = "pageSize") int pageSize,
                                                                        CylinderInfoDto cylinderInfoDto) {
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        if (ObjectUtils.isEmpty(reginParams)) {
            return null;
        }
		CompanyModel companyModel = reginParams.getUserModel().getCompanys().get(0);
		String companyCode = companyModel.getCompanyCode();
		if ("organization".equals(companyModel.getLevel())) {
			return ResponseHelper.buildResponse(null);
		} else if ("company".equals(companyModel.getLevel())) {
			cylinderInfoDto.setCreditCode(companyCode);
		}
		if (ValidationUtil.isEmpty(cylinderInfoDto.getRegionCode()) && ValidationUtil.isEmpty(cylinderInfoDto.getCreditCode()) && cylinderInfoDto.getIsWarn() == 0) {
			return ResponseHelper.buildResponse(new Page<ESCylinderInfoDto>());
        }
        Page<ESCylinderInfoDto> pageResult = cylinderInfoServiceImpl.queryByKeys(cylinderInfoDto, pageNum, pageSize);
        return ResponseHelper.buildResponse(pageResult);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY ,needAuth = false)
    @GetMapping(value = "/saveCylinderFillingRecord")
    @ApiOperation(httpMethod = "GET", value = "气瓶充装信息存入es", notes = "气瓶充装信息存入es")
    public ResponseModel<Object> saveCylinderFillingRecord() {
		return  ResponseHelper.buildResponse(cylinderFillingRecordServiceImpl.getCylinderFillingRecordAll());
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @GetMapping(value = "/getCylinderFillingRecord")
    @ApiOperation(httpMethod = "GET", value = "气瓶充装信息存入es入口", notes = "气瓶充装信息存入es入口")
    public ResponseModel<Object> getCylinderFillingRecord() {
        return ResponseHelper.buildResponse(cylinderFillingRecordServiceImpl.getCylinderFillingRecordTest());
    }


    /**
     * 气瓶基本信息
     *
     * @param pageNum  当前页
     * @param pageSize 每页大小
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getEsCyinderRecordList")
    @ApiOperation(httpMethod = "GET", value = "获取登陆人所在气瓶充装信息", notes = "获取登陆人所在气瓶充装信息")
    public ResponseModel<IPage<ESCylinderFillingRecordDto>> getEsCyinderRecordList(@RequestParam(value = "pageNum") int pageNum,
                                                                                   @RequestParam(value = "pageSize") int pageSize,
                                                                                   ESCylinderFillingRecordDto esCylinderFillingRecordDto) {
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        if (ObjectUtils.isEmpty(reginParams)) {
            return null;
        }
		CompanyModel companyModel = reginParams.getUserModel().getCompanys().get(0);
		String companyCode = companyModel.getCompanyCode();
		if ("organization".equals(companyModel.getLevel())) {
			return ResponseHelper.buildResponse(null);
		} else if ("company".equals(companyModel.getLevel())) {
			esCylinderFillingRecordDto.setCreditCode(companyCode);
		} else {
			esCylinderFillingRecordDto.setRegionCode(companyCode);
		}

        Page<ESCylinderFillingRecordDto> pageResult = cylinderFillingRecordServiceImpl.queryByKeys(esCylinderFillingRecordDto, pageNum, pageSize);
        return ResponseHelper.buildResponse(pageResult);
    }


	private QueryWrapper<CylinderInfo> setQueryWrapper(QueryWrapper<CylinderInfo> queryWrapper,
			CylinderInfoDto cylinderInfo, String sort) {
		if (cylinderInfo.getAppIds() != null && cylinderInfo.getAppIds().size() > 0) {
			queryWrapper.in("app_id", cylinderInfo.getAppIds());
		}
		if (sort != null) { // 排序失效
			String[] date = sort.split(",");
			if ("ascend".equals(date[1])) {
				queryWrapper.orderByAsc(RedisKey.humpToLine(date[0]));
			} else {
				queryWrapper.orderByDesc(RedisKey.humpToLine(date[0]));
			}
		} else {
			queryWrapper.orderByDesc("sync_date");
		}
		if (!ValidationUtil.isEmpty(cylinderInfo.getAppId())) {
			queryWrapper.eq("app_id", cylinderInfo.getAppId());
		}
//        if (!ValidationUtil.isEmpty(cylinderInfo.getInspectionDateStart())) {
//            queryWrapper.ge("inspection_date", cylinderInfo.getInspectionDateStart());
//        }
//        if (!ValidationUtil.isEmpty(cylinderInfo.getInspectionDateEnd())) {
//            queryWrapper.le("inspection_date", cylinderInfo.getInspectionDateEnd());
//        }
		if (!ValidationUtil.isEmpty(cylinderInfo.getUnitName())) { // 产权单位
			queryWrapper.like("unit_name", cylinderInfo.getUnitName());
		}
		if (!ValidationUtil.isEmpty(cylinderInfo.getFactoryNum())) {// 出厂编号
			queryWrapper.like("factory_num", cylinderInfo.getFactoryNum());
		}
		if (!ValidationUtil.isEmpty(cylinderInfo.getCylinderVariety())) {// 气瓶品种
			queryWrapper.eq("cylinder_variety", cylinderInfo.getCylinderVariety());
		}
//        if (!ValidationUtil.isEmpty(cylinderInfo.getQrCode())) {// 二维码编号
//            queryWrapper.like("qrCode", cylinderInfo.getQrCode());
//        }
//        if (!ValidationUtil.isEmpty(cylinderInfo.getElectronicLabelCode())) {// 电子标签编号
//            queryWrapper.like("electronic_label_code", cylinderInfo.getElectronicLabelCode());
//        }
		if (!ValidationUtil.isEmpty(cylinderInfo.getSequenceCode())) {// 气瓶唯一标识码
			queryWrapper.like("sequence_code", cylinderInfo.getSequenceCode());
		}
		if (!ValidationUtil.isEmpty(cylinderInfo.getUnitInnerCode())) {// 单位内部编号
			queryWrapper.like("unit_inner_code", cylinderInfo.getUnitInnerCode());
		}
		if (!ValidationUtil.isEmpty(cylinderInfo.getCylinderStatus())) {// 气瓶状态
			queryWrapper.eq("cylinder_status", cylinderInfo.getCylinderStatus());
		}
		if (!ValidationUtil.isEmpty(cylinderInfo.getManufacturingUnit())) {// 制造单位
			queryWrapper.like("manufacturing_unit", cylinderInfo.getManufacturingUnit());
		}
		if (!ValidationUtil.isEmpty(cylinderInfo.getCreditCode())) {// 统一社会信用代码
			queryWrapper.like("credit_code", cylinderInfo.getCreditCode());
		}
		return queryWrapper;
	}

	/**
	 * 获取气瓶详细信息
	 *
	 * @param sequenceNbr
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/cyinderInfo/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET", value = "获取气瓶详细信息", notes = "获取气瓶详细信息")
	public ResponseModel<CylinderInfoDto> cyinderInfoList(@PathVariable Long sequenceNbr) {
		CylinderInfo cylinderInfo = cylinderInfoServiceImpl.getById(sequenceNbr);
		Map<String, List<AttachmentDto>> imgMap = sourceFileService.getAttachments(cylinderInfo.getSequenceNbr());

		CylinderInfoDto target = new CylinderInfoDto();
		// 把原对象数据拷贝到新对象
		BeanUtils.copyProperties(cylinderInfo, target);
//        if (0 == cylinderInfo.getCylinderStatus()) {
//            target.setCylinderStatusStr("在用");
//        } else if (1 == cylinderInfo.getCylinderStatus()) {
//            target.setCylinderStatusStr("停用");
//        } else if (2 == cylinderInfo.getCylinderStatus()) {
//            target.setCylinderStatusStr("注销");
//        } else if (3 == cylinderInfo.getCylinderStatus()) {
//            target.setCylinderStatusStr("报废");
//        } else {
//            target.setCylinderStatusStr("");
//        }

//        if (1 == cylinderInfo.getCylinderVariety()) {
//            target.setCylinderVarietyStr("无缝气瓶");
//        } else if (2 == cylinderInfo.getCylinderVariety()) {
//            target.setCylinderVarietyStr("焊接气瓶");
//        } else if (3 == cylinderInfo.getCylinderVariety()) {
//            target.setCylinderVarietyStr("缠绕气瓶");
//        } else if (4 == cylinderInfo.getCylinderVariety()) {
//            target.setCylinderVarietyStr("绝热气瓶");
//        } else if (5 == cylinderInfo.getCylinderVariety()) {
//            target.setCylinderVarietyStr("内装填料气瓶");
//        } else {
//            target.setCylinderVarietyStr("");
//        }
//        Date nextDate = target.getNextInspectionDate();
//        long dates = nextDate.getTime() - System.currentTimeMillis();
//        if (dates >= 1000 * 60 * 60 * 24 * 30) {
//            target.setInspectionStatas(1);
//        } else if (0 < dates && dates < 1000 * 60 * 60 * 24 * 30) {
//            target.setInspectionStatas(2);
//        } else {
//            target.setInspectionStatas(0);
//        }
//        target.setAttachments(imgMap);

		return ResponseHelper.buildResponse(target);
	}

	/**
	 * 获取登陆人所在气瓶充装单位信息
	 *
	 * @param pageNum  当前页
	 * @param pageSize 每页大小
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/cyinderUnitList")
	@ApiOperation(httpMethod = "GET", value = "获取登陆人所在气瓶充装单位信息", notes = "获取登陆人所在气瓶充装单位信息")
	public ResponseModel<IPage<CylinderUnitDto>> cyinderUnitList(@RequestParam(value = "pageNum") String pageNum,
			@RequestParam(value = "pageSize") String pageSize, String sort, CylinderUnitDto cylinderUnitDto) {
		Page<CylinderUnit> pageBean;
		IPage<CylinderUnit> page;
		QueryWrapper<CylinderUnit> cylinderUnitQueryWrapper = new QueryWrapper<>();

		setQueryWrapper(cylinderUnitQueryWrapper, cylinderUnitDto, sort);
		if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
			pageBean = new Page<>(0, Long.MAX_VALUE);
		} else {
			pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
		}
		page = cylinderUnitServiceImpl.page(pageBean, cylinderUnitQueryWrapper);
		int num = cylinderUnitServiceImpl.count(cylinderUnitQueryWrapper);
		pageBean.setTotal(num);
		IPage<CylinderUnitDto> result = this.cyinderInfoIPageDto(page);
		return ResponseHelper.buildResponse(result);
	}

	/**
	 * 获取气瓶充装单位许可信息详情
	 *
	 * @param sequenceNbr
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getCylinderUnitLic/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET", value = "获取气瓶充装单位详情", notes = "获取气瓶充装单位详情")
	public ResponseModel<TzBaseEnterpriseInfoDto> getCylinderUnitLic(@PathVariable Long sequenceNbr) {
		return ResponseHelper.buildResponse(cylinderUnitServiceImpl.getCylinderUnitLic(sequenceNbr));
	}

	/**
	 * 获取气瓶充装单位详情
	 *
	 * @param sequenceNbr
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/cylinderUnit/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET", value = "获取气瓶充装单位详情", notes = "获取气瓶充装单位详情")
	public ResponseModel<CylinderUnitDto> cyinderUnitList(@PathVariable Long sequenceNbr) {
		CylinderUnit cylinderUnit = cylinderUnitServiceImpl.getById(sequenceNbr);
		if (this.regionMap == null) {
			this.regionMap = new HashMap<>();
			Collection<RegionModel> regions = Systemctl.regionClient.queryForTree(null).getResult();
			regions.stream().forEach(t -> {
				this.addRegionsMap(regionMap, t);
			});
		}
		CylinderUnitDto target = new CylinderUnitDto();
		// 把原对象数据拷贝到新对象
		BeanUtils.copyProperties(cylinderUnit, target);
		String regionCode = cylinderUnit.getRegionCode();
		String[] regionCodes = regionCode.split("#");
		regionCode = "";
		for (int i = 0; i < regionCodes.length; i++) {
			regionCode += this.regionMap.get(Integer.parseInt(regionCodes[i]));
		}
		target.setRegionCode(regionCode);
//        if (1 == cylinderUnit.getUnitType()) {
//            target.setUnitTypeStr("液化石油气瓶充装单位");
//        } else if (2 == cylinderUnit.getUnitType()) {
//            target.setUnitTypeStr("液化石油气瓶检验单位");
//        } else if (3 == cylinderUnit.getUnitType()) {
//            target.setUnitTypeStr("液化石油气瓶生产单位");
//        } else {
//            target.setUnitTypeStr("");
//        }
//        target.setCylinderNumber((long) cylinderInfoServiceImpl.count(new LambdaQueryWrapper<CylinderInfo>().eq(CylinderInfo::getAppId, target.getAppId())));
		Page<CylinderInfo> pageBean = new Page<>(0, Long.MAX_VALUE);
		Page<CylinderInfo> page = cylinderInspectionServiceImpl.queryOutOfDateCylinder(pageBean,
				cylinderUnit.getAppId());
		long outOfDate = page.getTotal();
		target.setCylinderOutOfDate(String.valueOf(outOfDate));
//        Date nextDate = target.getFillingPermitDate();
//        long dates = nextDate.getTime() - System.currentTimeMillis();
//        if (dates >= 1000 * 60 * 60 * 24 * 200) {
//            target.setLicenseStatus(1);
//        } else if (0 < dates && dates < 1000 * 60 * 60 * 24 * 200) {
//            target.setLicenseStatus(2);
//        } else {
//            target.setLicenseStatus(0);
//        }

		return ResponseHelper.buildResponse(target);
	}

	private QueryWrapper<CylinderUnit> setQueryWrapper(QueryWrapper<CylinderUnit> queryWrapper,
			CylinderUnitDto cylinderUnitDto, String sort) {
		if (sort != null) { // 排序失效
			String[] date = sort.split(",");
			if (date[1].equals("ascend")) {
				queryWrapper.orderByAsc(RedisKey.humpToLine(date[0]));
			} else {
				queryWrapper.orderByDesc(RedisKey.humpToLine(date[0]));
			}
		} else {
			queryWrapper.orderByDesc("sync_date");
		}

//        if (!ValidationUtil.isEmpty(cylinderUnitDto.getFillingPermitDateStart())) { // 许可有效期
//            queryWrapper.ge("filling_permit_date", cylinderUnitDto.getFillingPermitDateStart());
//        }
//
//        if (!ValidationUtil.isEmpty(cylinderUnitDto.getFillingPermitDateEnd())) {
//            queryWrapper.le("filling_permit_date", cylinderUnitDto.getFillingPermitDateEnd());
//        }

		if (!ValidationUtil.isEmpty(cylinderUnitDto.getUnitName())) { // 企业名称
			queryWrapper.like("unit_name", cylinderUnitDto.getUnitName());
		}

//        if (!ValidationUtil.isEmpty(cylinderUnitDto.getUnitType())) {// 企业类型
//            queryWrapper.eq("unit_type", cylinderUnitDto.getUnitType());
//        }

		if (!ValidationUtil.isEmpty(cylinderUnitDto.getCreditCode())) {// 统一社会信用代码
			queryWrapper.like("credit_code", cylinderUnitDto.getCreditCode());
		}
		if (!ValidationUtil.isEmpty(cylinderUnitDto.getAddress())) {// 详细地址
			queryWrapper.like("address", cylinderUnitDto.getAddress());
		}
		if (!ValidationUtil.isEmpty(cylinderUnitDto.getUnitPerson())) {// 企业负责人
			queryWrapper.like("unit_person", cylinderUnitDto.getUnitPerson());
		}
		if (!ValidationUtil.isEmpty(cylinderUnitDto.getPersonMobilePhone())) {// 负责人手机
			queryWrapper.like("person_mobile_phone", cylinderUnitDto.getPersonMobilePhone());
		}
//        if (!ValidationUtil.isEmpty(cylinderUnitDto.getFillingLicense())) {// 许可证号
//            queryWrapper.like("filling_license", cylinderUnitDto.getFillingLicense());
//        }
//        if (!ValidationUtil.isEmpty(cylinderUnitDto.getFillingPermScope())) {// 许可范围
//            queryWrapper.like("filling_perm_scope", cylinderUnitDto.getFillingPermScope());
//        }
		if (!ValidationUtil.isEmpty(cylinderUnitDto.getRegionCode())) {// 所属区域
			queryWrapper.like("region_code", cylinderUnitDto.getRegionCode());
		}
		return queryWrapper;
	}

	private IPage<CylinderUnitDto> cyinderInfoIPageDto(IPage<CylinderUnit> page) {

		if (this.regionMap == null) {
			this.regionMap = new HashMap<>();
			Collection<RegionModel> regions = Systemctl.regionClient.queryForTree(null).getResult();
			regions.stream().forEach(t -> {
				this.addRegionsMap(regionMap, t);
			});
		}

		if(ValidationUtil.isEmpty(this.licenceDateMap)){
			licenceDateMap = new HashMap<>();
			LambdaQueryWrapper<BaseUnitLicence> wrapper = new LambdaQueryWrapper<>();
			wrapper.select(BaseUnitLicence::getUnitCode,BaseUnitLicence::getExpiryDate)
					.groupBy(BaseUnitLicence::getUnitCode)
					.orderByDesc(BaseUnitLicence::getExpiryDate);
			List<BaseUnitLicence> baseUnitLicenceList = baseUnitLicenceService.list(wrapper);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			for(BaseUnitLicence baseUnitLicence:baseUnitLicenceList){
				licenceDateMap.put(baseUnitLicence.getUnitCode(),sdf.format(baseUnitLicence.getExpiryDate()));
			}
		}

		return page.convert(item -> {
			try {
				CylinderUnitDto target = new CylinderUnitDto();
				// 把原对象数据拷贝到新对象
				BeanUtils.copyProperties(item, target);
				String regionCode = item.getRegionCode();
				String[] regionCodes = regionCode.split("#");
				regionCode = "";
				for (int i = 0; i < regionCodes.length; i++) {
					regionCode += this.regionMap.get(Integer.parseInt(regionCodes[i]));
				}
				target.setRegionCode(regionCode);
				target.setFillingPermitDate(licenceDateMap.get(target.getCreditCode()));
//                if (1 == item.getUnitType()) {
//                    target.setUnitTypeStr("液化石油气瓶充装单位");
//                } else if (2 == item.getUnitType()) {
//                    target.setUnitTypeStr("液化石油气瓶检验单位");
//                } else if (3 == item.getUnitType()) {
//                    target.setUnitTypeStr("液化石油气瓶生产单位");
//                } else {
//                    target.setUnitTypeStr("");
//                }
				target.setCylinderNumber(cylinderInfoServiceImpl
						.count(new LambdaQueryWrapper<CylinderInfo>().eq(CylinderInfo::getAppId, target.getAppId())));
				return target;
			} catch (Exception e) {
				return null;
			}
		});
	}

	private void addRegionsMap(Map<Integer, String> regionMap, RegionModel region) {
		regionMap.put(region.getRegionCode(), region.getRegionName());
		if (region.getChildren() != null) {
			region.getChildren().stream().forEach(c -> {
				addRegionsMap(regionMap, c);
			});
		}
	}

	/**
	 * 企业气瓶总量数据同步
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/synUnitCylinderInfoData")
	@ApiOperation(httpMethod = "GET", value = "企业气瓶总量数据同步", notes = "企业气瓶总量数据同步")
	public ResponseModel<Boolean> synUnitCylinderInfoData() {
		cylinderInfoServiceImpl.synUnitCylinderInfoData();
		return ResponseHelper.buildResponse(true);
	}

	/**
	 * 企业气瓶充装数据同步
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/synUnitCylinderFillingData")
	@ApiOperation(httpMethod = "GET", value = "企业气瓶充装数据同步", notes = "企业气瓶充装数据同步")
	public ResponseModel<Boolean> synUnitCylinderFillingData() {
		cylinderInfoServiceImpl.synUnitCylinderFillingData();
		return ResponseHelper.buildResponse(true);
	}

	/**
	 * 企业气瓶标签数量比同步
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/synUnitCylinderTagsData")
	@ApiOperation(httpMethod = "GET", value = "企业气瓶标签数量比同步", notes = "企业气瓶标签数量比同步")
	public ResponseModel<Boolean> synUnitCylinderTagsData() {
		cylinderInfoServiceImpl.synUnitCylinderTagsData();
		return ResponseHelper.buildResponse(true);
	}

	/**
	 * 企业数据完整度同步
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/synUnitIntegrityData")
	@ApiOperation(httpMethod = "GET", value = "企业数据完整度同步", notes = "企业数据完整度同步")
	public ResponseModel<Boolean> synUnitIntegrityData() {
		cylinderInfoServiceImpl.synUnitIntegrityData();
		return ResponseHelper.buildResponse(true);
	}

	/**
	 * 气瓶充装检查情况同步
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/synUnitFillingCheckData")
	@ApiOperation(httpMethod = "GET", value = "气瓶充装检查情况同步", notes = "气瓶充装检查情况同步")
	public ResponseModel<Boolean> synUnitFillingCheckData() {
		cylinderInfoServiceImpl.fillingCheckDataSynHandler();
		return ResponseHelper.buildResponse(true);
	}

	/**
	 * 装卸液体企业数据同步
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/synFillingUnloadUnitData")
	@ApiOperation(httpMethod = "GET", value = "装卸液体企业数据同步", notes = "装卸液体企业数据同步")
	public ResponseModel<Boolean> synFillingUnloadUnitData() {
		cylinderInfoServiceImpl.synFillingUnloadUnitData();
		return ResponseHelper.buildResponse(true);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "气瓶超期数量统计")
	@GetMapping(value = "/{earlyWarningLevel}/statistics")
	public ResponseModel<Integer> getOverDateStatisticsNumber(@PathVariable String earlyWarningLevel) {
		return ResponseHelper.buildResponse(cylinderInfoServiceImpl.getOverDateStatisticsNumber(earlyWarningLevel));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "按照预警类型查询气瓶分页列表", notes = "按照预警类型查询气瓶分页列表")
	@GetMapping(value = "/{earlyWarningLevel}/page")
	public ResponseModel<Page<CylinderInfoDto>> getOverDateStatisticsNumber(
			@RequestParam(value = "current") int current, @RequestParam(value = "size") int size,
			@PathVariable String earlyWarningLevel) {
		Page<CylinderInfoDto> page = new Page<>();
		page.setCurrent(current);
		page.setSize(size);
		return ResponseHelper.buildResponse(cylinderInfoServiceImpl.earlyWarningLevelPageList(page, earlyWarningLevel));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "气瓶详情")
	@GetMapping(value = "/{sequenceCode}/detail")
	public ResponseModel<CylinderInfoDto> getDetail(@PathVariable String sequenceCode) {
		return ResponseHelper.buildResponse(cylinderInfoServiceImpl.getDetail(sequenceCode));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "气瓶处置日志")
	@GetMapping(value = "/msg/{sequenceCode}/list")
	public ResponseModel<List<MsgLog>> getMsgList(@PathVariable String sequenceCode,
			@RequestParam(value = "terminalType", required = false) String terminalType) {
		return ResponseHelper.buildResponse(cylinderInfoServiceImpl.getMsgList(sequenceCode, terminalType));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "PUT", value = "下次检验日期更新", notes = "下次检验日期更新")
	@PutMapping(value = "/nextInspectionDate/update")
	public ResponseModel<Boolean> nextInspectionDateUpdate(@RequestBody List<CylinderInfoDto> cylinderInfoDtos) {
		return ResponseHelper.buildResponse(cylinderInfoServiceImpl.nextInspectionDateUpdate(cylinderInfoDtos));
	}

	/**
	 * 气瓶信息放入es
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@RequestMapping(value = "/init", method = RequestMethod.PUT)
	@ApiOperation(httpMethod = "PUT", value = "气瓶信息放入es", notes = "气瓶信息放入es")
	public void init(Integer num) {
		IPage<CylinderInfo> cylinderInfoPage = new Page<>();
		Integer count = cylinderInfoServiceImpl.count();
		Integer times = 0;
		if (ValidationUtil.isEmpty(num) && count != 0) {
			times = count / 500;
			int last = count % 500;
			if (last > 0) {
				times++;
			}
		} else if (count != 0) {
			times = num;
		}

		for (int i = 0; i < times; i++) {
			cylinderInfoPage.setCurrent(i);
			cylinderInfoPage.setSize(500);
			cylinderInfoPage = cylinderInfoServiceImpl.page(cylinderInfoPage);
			esCylinderService.saveEsCylinderToES(cylinderInfoPage.getRecords());
		}
	}

	@Autowired
	private ScheduleService scheduleService;

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "气瓶/设备/许可预警测试接口（实际应为定时任务）")
	@GetMapping(value = "/test")
	public void test() {
		scheduleService.calEarlyWarningLevel();
	}

	/**
	 * 企业数据完整度同步
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/addAll")
	@ApiOperation(httpMethod = "GET", value = "企业数据完整度同步", notes = "企业数据完整度同步")
	public ResponseModel<Boolean> addAll() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				cylinderInfoServiceImpl.synFillingUnloadData();
				cylinderInfoServiceImpl.synAreaData();
				cylinderInfoServiceImpl.addIntegrityData();
				cylinderInfoServiceImpl.getCylinderUnitInfo();
				cylinderInfoServiceImpl.getCylinderInfo();
				cylinderInfoServiceImpl.synUnitCylinderInfoData();
				cylinderInfoServiceImpl.synUnitCylinderFillingData();
				cylinderInfoServiceImpl.synUnitCylinderTagsData();
				cylinderInfoServiceImpl.synUnitIntegrityData();
				cylinderInfoServiceImpl.fillingCheckDataSynHandler();
				cylinderInfoServiceImpl.synFillingUnloadUnitData();
			}
		}).start();
		return ResponseHelper.buildResponse(true);
	}


	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "超期列表")
	@GetMapping(value = "/timeOutList")
	public ResponseModel<Object> timeOutList(@RequestParam("number") Long number, @RequestParam("size") Long size, @RequestParam(value = "companyId", required = false) String companyId, @RequestParam(value = "regionCode", required = false) String regionCode) {
		Page<Map<String, Object>> page = new Page<>(number, size);
		HashMap<String, Object> map = new HashMap<>();
		HashMap<String, Object> result = new HashMap<>();

		Page<Map<String, Object>> mapPage = cylinderInfoServiceImpl.getBaseMapper().timeOutList(page, companyId, regionCode);
		// 组装分页信息
		map.put("current", page.getCurrent());
		map.put("pageSize", page.getSize());
		map.put("total", mapPage.getTotal());
		map.put("pagination", false);
		map.put("totalPage", mapPage.getPages());
		map.put("dataList", mapPage.getRecords());
		result.put("dataGridMock", map);
		// 组装表头信息
		ArrayList<Map<String, Object>> maps = new ArrayList<>();
		HashMap<String, Object> status = new HashMap<>();
		status.put("fid", "status");
		status.put("dataIndex", "status");
		status.put("name", "状态");
		status.put("title", "状态");
		status.put("type", "dataGrid");
		status.put("key", "status");
		maps.add(status);
		// 检验有效期
		HashMap<String, Object> expire_day = new HashMap<>();
		expire_day.put("fid", "expire_day");
		expire_day.put("dataIndex", "expire_day");
		expire_day.put("name", "检验有效期");
		expire_day.put("title", "检验有效期");
		expire_day.put("type", "dataGrid");
		expire_day.put("key", "expire_day");
		maps.add(expire_day);
		// 气瓶编码
		HashMap<String, Object> sequence_code = new HashMap<>();
		sequence_code.put("fid", "sequence_code");
		sequence_code.put("dataIndex", "sequence_code");
		sequence_code.put("name", "气瓶编码");
		sequence_code.put("title", "气瓶编码");
		sequence_code.put("type", "dataGrid");
		sequence_code.put("key", "sequence_code");
		maps.add(sequence_code);
		// 产权单位
		HashMap<String, Object> unit_name = new HashMap<>();
		unit_name.put("fid", "unit_name");
		unit_name.put("dataIndex", "unit_name");
		unit_name.put("name", "产权单位");
		unit_name.put("title", "产权单位");
		unit_name.put("type", "dataGrid");
		unit_name.put("key", "unit_name");
		maps.add(unit_name);


		result.put("colModel", maps);
		return ResponseHelper.buildResponse(result);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "许可列表")
	@GetMapping(value = "/licenceList")
	public ResponseModel<Object> licenceList(@RequestParam("number") Long number, @RequestParam("size") Long size, @RequestParam(value = "companyId", required = false) String companyId) {
		Page<Map<String, Object>> page = new Page<>(number, size);
		HashMap<String, Object> map = new HashMap<>();
		HashMap<String, Object> result = new HashMap<>();

		Page<Map<String, Object>> mapPage = cylinderInfoServiceImpl.getBaseMapper().licenceList(page, companyId);
		// 组装分页信息
		map.put("current", page.getCurrent());
		map.put("pageSize", page.getSize());
		map.put("total", mapPage.getTotal());
		map.put("pagination", false);
		map.put("totalPage", mapPage.getPages());
		map.put("dataList", mapPage.getRecords());
		result.put("dataGridMock", map);
		// 组装表头信息
		ArrayList<Map<String, Object>> maps = new ArrayList<>();
		HashMap<String, Object> status = new HashMap<>();
		status.put("fid", "status");
		status.put("dataIndex", "status");
		status.put("name", "状态");
		status.put("title", "状态");
		status.put("type", "dataGrid");
		status.put("key", "status");
		maps.add(status);
		// 许可范围
		HashMap<String, Object> filling_perm_scope = new HashMap<>();
		filling_perm_scope.put("fid", "filling_perm_scope");
		filling_perm_scope.put("dataIndex", "filling_perm_scope");
		filling_perm_scope.put("name", "检验有效期");
		filling_perm_scope.put("title", "检验有效期");
		filling_perm_scope.put("type", "dataGrid");
		filling_perm_scope.put("key", "expire_day");
		maps.add(filling_perm_scope);
		// 许可有效期
		HashMap<String, Object> filling_permit_date = new HashMap<>();
		filling_permit_date.put("fid", "filling_permit_date");
		filling_permit_date.put("dataIndex", "filling_permit_date");
		filling_permit_date.put("name", "许可范围");
		filling_permit_date.put("title", "许可范围");
		filling_permit_date.put("type", "dataGrid");
		filling_permit_date.put("key", "sequence_code");
		maps.add(filling_permit_date);
		// 气瓶企业
		HashMap<String, Object> unit_name = new HashMap<>();
		unit_name.put("fid", "unit_name");
		unit_name.put("dataIndex", "unit_name");
		unit_name.put("name", "气瓶企业");
		unit_name.put("title", "气瓶企业");
		unit_name.put("type", "dataGrid");
		unit_name.put("key", "unit_name");
		maps.add(unit_name);

		result.put("colModel", maps);
		return ResponseHelper.buildResponse(result);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "统计")
	@GetMapping(value = "/countNumber")
	public ResponseModel<Object> countNumber(@RequestParam("status") String status, @RequestParam(value = "companyId", required = false) String companyId, @RequestParam(value = "regionCode", required = false) String regionCode) {
		HashMap<String, Object> map = new HashMap<>();
		int number = cylinderInfoServiceImpl.getBaseMapper().countNumber(status, companyId, regionCode);
		map.put("status", number);
		return ResponseHelper.buildResponse(map);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "先清除表数据，再主动向以天为维度的企业气瓶统计表中刷入当前时间前30天的数据")
	@GetMapping(value = "/thirtyDayEnterpriseCylinderDataRefreshTask")
	public ResponseModel<Object> thirtyDayEnterpriseCylinderDataRefreshTask() {
		cylinderInfoServiceImpl.fillingRecordDataSynHandler();
		return ResponseHelper.buildResponse("ok");
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "以天为维度的企业气瓶统计表中刷入某天的数据，" +
			"支持传参：1、某天day（必填）：刷入时间，例如2024-06-07；2、企业appId(非必填，如果不填则刷入所有企业的day数据):刷入企业的appId")
	@GetMapping(value = "/oneDayEnterpriseCylinderDataRefreshTask")
	public ResponseModel<Object> oneDayEnterpriseCylinderDataRefreshTask(
			@RequestParam(value = "day",required = true) String day,
			@RequestParam(value = "appId",required = false) String appId) {
		cylinderInfoServiceImpl.oneDayEnterpriseCylinderDataRefreshTask(day, appId);
		return ResponseHelper.buildResponse("ok");
	}

	/**
	 * 地市气瓶,气站信息统计
	 *
	 * @author LiuLin
	 * @date 2025-05-31
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getCityCylinderData")
	@ApiOperation(httpMethod = "GET", value = "获取地市气瓶,气站信息统计", notes = "获取地市气瓶,气站信息统计")
	public ResponseModel<Collection<CityCylinderInfoDto>> getCityCylinderData(@RequestParam( value="level") String level) {
		List<CityCylinderInfoDto> result = cylinderAreaDataService.getCityCylinderData(level);
		return ResponseHelper.buildResponse(result);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getCylinderStatisticsData")
	@ApiOperation(httpMethod = "GET", value = "获取气瓶统计数据-按照企业名称统计", notes = "获取气瓶统计数据-按照企业名称统计")
	public ResponseModel<List<Map<String, Object>>> getCylinderStatisticsData(@RequestParam( value="regionCode") String regionCode) throws IOException {
		List<Map<String, Object>> result = cylinderAreaDataService.getCylinderStatisticsData(regionCode);
		return ResponseHelper.buildResponse(result);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/getCylinderStatisticsDataByCity")
	@ApiOperation(httpMethod = "POST", value = "获取气瓶统计数据-按照城市统计", notes = "获取气瓶统计数据-按照城市统计")
	public ResponseModel<Map<String, Object>> getCylinderStatisticsDataByCity(@RequestBody Map<String, Object> map) throws Exception {
		Object regionCode = map.get("cityCode");
		if (ObjectUtils.isEmpty(regionCode)) {
			regionCode = "610000";
		}

		Map<String, Object> result = cylinderAreaDataService.getCylinderStatisticsDataByCity(regionCode.toString());
		return ResponseHelper.buildResponse(result);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/getCylinderStatisticsDataByCityForTotal")
	@ApiOperation(httpMethod = "POST", value = "获取气瓶统计数据-按照城市统计", notes = "获取气瓶统计数据-按照城市统计-地图统计")
	public ResponseModel<Map<String, Object>> getCylinderStatisticsDataByCityForTotal(@RequestBody Map<String, Object> map) throws Exception {
		Object regionCode = map.get("cityCode");
		if (ObjectUtils.isEmpty(regionCode)) {
			regionCode = "610000";
		}

		Map<String, Object> result = cylinderAreaDataService.getCylinderStatisticsDataByCityForTotal(regionCode.toString());
		return ResponseHelper.buildResponse(result);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/getCylinderStatisticsDataByCityForMap")
	@ApiOperation(httpMethod = "POST", value = "获取气瓶统计数据-按照城市统计", notes = "获取气瓶统计数据-按照城市统计-地图")
	public ResponseModel<List<Map<String, Object>>> getCylinderStatisticsDataByCityForMap(@RequestBody Map<String, Object> map) throws Exception {
		Object regionCode = map.get("cityCode");
		if (ObjectUtils.isEmpty(regionCode)) {
			regionCode = "610000";
		}

		List<Map<String, Object>> result = cylinderAreaDataService.getCylinderStatisticsDataByCityForMap(regionCode.toString());
		return ResponseHelper.buildResponse(result);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "市级为维度，各市的充装次数和累计充装量，当前日期向前推31天的数据总和")
	@GetMapping(value = "/countFillingTimesAndQuantityByCity")
	public ResponseModel<Map<String, Object>> countFillingTimesAndQuantityByCity() {
		return ResponseHelper.buildResponse(cylinderInfoServiceImpl.countFillingTimesAndQuantityByCity());
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "30天的充装量、卸液量数据")
	@GetMapping(value = "/fillingTimesAndQuantity")
	public ResponseModel<List<CylinderFillingRecordStatisticsDto> > fillingTimesAndQuantity(@RequestParam("regionCode") String reginCode) {
		return ResponseHelper.buildResponse(cylinderInfoServiceImpl.fillingTimesAndQuantity(reginCode));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "资质附件，轮播图用")
	@GetMapping(value = "/getAttachmentByUnitCode")
	public ResponseModel<List<Map<String, Object>>> getAttachmentByUnitCode(@RequestParam(value = "companyId") String companyId) {
		List<Map<String, Object>> result = new ArrayList<>();
		String attachmentByUnitCode = cylinderInfoServiceImpl.getBaseMapper().getAttachmentByUnitCode(companyId);
		if (attachmentByUnitCode != null && !attachmentByUnitCode.isEmpty()) {
			JSONArray jsonArray = JSON.parseArray(attachmentByUnitCode);
			if (jsonArray != null) {
				for (int i = 0; i < jsonArray.size(); i++) {
					Map<String, Object> temp = (Map<String, Object>) jsonArray.get(i);
					HashMap<String, Object> map = new HashMap<>();
					map.put("type", "img");
					map.put("key", i + 1);
					map.put("title", temp.get("name"));
					map.put("url", temp.get("url"));
					result.add(map);
				}
			}
		}
		return ResponseHelper.buildResponse(result);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "同步气瓶数据日志")
	@GetMapping(value = "/logs")
	@DS("cyl")
	public ResponseModel<IPage<CylinderFillingMessageModel>> getUploadCylinderLogs(PageParam pageParam, String regionCode )  {
		IPage<CylinderFillingMessageModel> result = cylinderFillingMessageService.getUploadCylinderLogs(pageParam, regionCode);
		return ResponseHelper.buildResponse(result);
	};


}
