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

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.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertCalledDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertCalledQueryDto;
import com.yeejoin.amos.boot.module.tzs.api.entity.AlertCalled;
import com.yeejoin.amos.boot.module.tzs.biz.utils.AlertBeanDtoVoUtils;
import com.yeejoin.amos.boot.module.tzs.biz.utils.BeanDtoVoUtils;
import com.yeejoin.amos.boot.module.tzs.flc.api.dto.CylinderFillingRecordDto;
import com.yeejoin.amos.boot.module.tzs.flc.api.dto.CylinderInfoDto;
import com.yeejoin.amos.boot.module.tzs.flc.api.entity.CylinderFillingRecord;
import com.yeejoin.amos.boot.module.tzs.flc.api.entity.CylinderInfo;
import com.yeejoin.amos.boot.module.tzs.flc.biz.service.impl.CylinderFillingRecordServiceImpl;
import com.yeejoin.amos.boot.module.tzs.flc.biz.service.impl.CylinderInfoServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
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.util.Date;
import java.util.List;

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

	@Autowired
	CylinderInfoServiceImpl cylinderInfoServiceImpl;

	@Autowired
	CylinderFillingRecordServiceImpl cylinderFillingRecordServiceImpl;




    /**
     * 新增气瓶基本信息
     *
     * @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 主键
     * @return
     */
    @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() {
		Boolean flag = cylinderInfoServiceImpl.getCylinderInfo();
		return ResponseHelper.buildResponse(flag);
	}

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



//	// 数据完整性计算 气瓶企业信息 气瓶基本信息 标签 检验 充装 充装审核
//	/**
//	 * 数据完整性计算
//	 *
//	 * @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() {
		Boolean flag = cylinderInfoServiceImpl.addIntegrityData();
		return ResponseHelper.buildResponse(flag);
	}

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

		return ResponseHelper.buildResponse(flag);
	}



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

		return ResponseHelper.buildResponse(flag);
	}

	/**
	 * 列表分页查询
	 *
	 * @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<CylinderFillingRecordDto>();
		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";
		}
		cylinderFillingRecordDto.setAppId("9B150BB7D0C21A7A62BD6837E14A44BF");
		Page<CylinderFillingRecordDto> pageBean = cylinderFillingRecordServiceImpl.queryListByQueryDto(page,cylinderFillingRecordDto, sortParam, sortRule);
		Page<CylinderFillingRecordDto> result = new Page<CylinderFillingRecordDto>(pageNum,pageSize);
		long totle = pageBean.getTotal();
		result.setRecords(pageBean.getRecords());
		result.setTotal(totle);
		return ResponseHelper.buildResponse(result);
	}



}
