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

import com.alibaba.fastjson.JSON;
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.ymt.api.dto.TzBaseEnterpriseInfoDto;
import com.yeejoin.amos.boot.module.ymt.api.entity.BaseUnitLicence;
import com.yeejoin.amos.boot.module.ymt.api.entity.ESCylinderFillingRecordDto;
import com.yeejoin.amos.boot.module.ymt.api.entity.ESCylinderInfoDto;
import com.yeejoin.amos.boot.module.ymt.api.entity.MsgLog;
import com.yeejoin.amos.boot.module.ymt.biz.service.impl.BaseUnitLicenceServiceImpl;
import com.yeejoin.amos.boot.module.ymt.biz.service.impl.ESCylinderServiceImpl;
import com.yeejoin.amos.boot.module.ymt.biz.service.impl.TzBaseEnterpriseInfoServiceImpl;
import com.yeejoin.amos.boot.module.ymt.flc.api.dto.CylinderFillingRecordDto;
import com.yeejoin.amos.boot.module.ymt.flc.api.dto.CylinderInfoDto;
import com.yeejoin.amos.boot.module.ymt.flc.api.dto.CylinderUnitDto;
import com.yeejoin.amos.boot.module.ymt.flc.api.entity.CylinderInfo;
import com.yeejoin.amos.boot.module.ymt.flc.api.entity.CylinderUnit;
import com.yeejoin.amos.boot.module.ymt.flc.biz.service.impl.*;
import com.yeejoin.amos.boot.module.ymt.flc.biz.service.impl.*;
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.text.SimpleDateFormat;
import java.util.*;

/**
 * 气瓶基本信息
 *
 * @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;

	/**
	 * 新增气瓶基本信息
	 *
	 * @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);
		}



//		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)
    @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(i);
			cylinderInfoPage.setSize(1000);
			cylinderInfoPage = cylinderInfoServiceImpl.getCyinderInfoList(cylinderInfoPage);
			if (!ObjectUtils.isEmpty(cylinderInfoPage)) {
				cylinderInfoServiceImpl.saveCylinderInfo2ES(cylinderInfoPage.getRecords());
			}
//            for (CylinderInfoDto ci : cylinderInfoPage.getRecords()) {
//                cylinderInfoServiceImpl.saveCylinderInfoToES(ci);
//            }
		}
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getCyinderInfo")
    @ApiOperation(httpMethod = "GET", value = "气瓶基本信息存入es入口", notes = "气瓶基本信息存入es入口")
    public Page<CylinderInfoDto> getCyinderInfo() {
        Page<CylinderInfoDto> cylinderInfoPage = new Page<>();
        cylinderInfoPage.setCurrent(1);
        cylinderInfoPage.setSize(1000);
        cylinderInfoPage = cylinderInfoServiceImpl.getCyinderInfoList(cylinderInfoPage);
        for (CylinderInfoDto ci : cylinderInfoPage.getRecords()) {
            cylinderInfoServiceImpl.saveCylinderInfoToES(ci);
        }
        return cylinderInfoServiceImpl.getCyinderInfoList(cylinderInfoPage);
    }


    /**
     * 气瓶基本信息
     *
     * @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)
    @GetMapping(value = "/saveCyinderFillingRecord")
    @ApiOperation(httpMethod = "GET", value = "气瓶充装信息存入es", notes = "气瓶充装信息存入es")
    public void saveCyinderFillingRecord() {
		Page<ESCylinderFillingRecordDto> recordDtoPage = new Page<>();
		Integer count = cylinderFillingRecordServiceImpl.getCylinderFillingRecordTotal();
		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++) {
			recordDtoPage.setCurrent(1);
			recordDtoPage.setSize(1000);
//			CylinderFillingRecordDto cylinderFillingRecordDto = new CylinderFillingRecordDto();
//			if (StringUtils.isEmpty(cylinderFillingRecordDto.getSequenceCode())) {
//				cylinderFillingRecordDto.setAppId("9B150BB7D0C21A7A62BD6837E14A44BF");
//			}
			Page<ESCylinderFillingRecordDto> cyinderFillingRecord = cylinderFillingRecordServiceImpl.getCyinderFillingRecord(recordDtoPage);
			if (!ObjectUtils.isEmpty(cyinderFillingRecord)) {
				cylinderFillingRecordServiceImpl.saveCylinderFillingRecord2ES(cyinderFillingRecord.getRecords());
			}
		}
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getCyinderFillingRecord")
    @ApiOperation(httpMethod = "GET", value = "气瓶充装信息存入es入口", notes = "气瓶充装信息存入es入口")
    public Page<ESCylinderFillingRecordDto> getCyinderFillingRecord() {
        Page<ESCylinderFillingRecordDto> cylinderInfoPage = new Page<>();
        cylinderInfoPage.setCurrent(1);
        cylinderInfoPage.setSize(10);
        Page<ESCylinderFillingRecordDto> cyinderFillingRecord = cylinderFillingRecordServiceImpl.getCyinderFillingRecord(cylinderInfoPage);
        for (ESCylinderFillingRecordDto ci : cyinderFillingRecord.getRecords()) {
            cylinderFillingRecordServiceImpl.saveCylinderFillingRecordToES(ci);
        }
        return cyinderFillingRecord;
    }


    /**
     * 气瓶基本信息
     *
     * @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, 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, 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.synUnitFillingCheckData();
		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.synUnitFillingCheckData();
				cylinderInfoServiceImpl.synFillingUnloadUnitData();
			}
		}).start();
		return ResponseHelper.buildResponse(true);
	}

}
