package org.springblade.modules.nh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.common.collect.Sets;
import lombok.AllArgsConstructor;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.cache.DictCache;
import org.springblade.common.enums.DictEnum;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.*;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.modules.nh.excel.StationStaticsExcel;
import org.springblade.modules.nh.pojo.entity.*;
import org.springblade.modules.nh.pojo.vo.PowerStationInefficientVO;
import org.springblade.modules.nh.excel.PowerStationInefficientExcel;
import org.springblade.modules.nh.mapper.PowerStationInefficientMapper;
import org.springblade.modules.nh.pojo.vo.StaticsMonthVO;
import org.springblade.modules.nh.pojo.vo.StationStaticsVO;
import org.springblade.modules.nh.service.*;
import org.springblade.modules.nh.wrapper.PowerStationWrapper;
import org.springblade.modules.operation.mapper.OperationSiteEmployeeMapper;
import org.springblade.modules.operation.pojo.entity.OperationSiteEntity;
import org.springblade.modules.operation.pojo.vo.EmpAuthVo;
import org.springblade.modules.operation.service.impl.OperationSiteServiceImpl;
import org.springblade.modules.operation.service.impl.PlatformEmployeeServiceImpl;
import org.springblade.modules.order.constant.OrderConstants;
import org.springblade.modules.order.pojo.entity.OperationOrderEntity;
import org.springblade.modules.order.pojo.entity.OperationOrderOperationInfoEntity;
import org.springblade.modules.order.service.impl.OperationOrderOperationInfoServiceImpl;
import org.springblade.modules.order.service.impl.OperationOrderServiceImpl;
import org.springblade.modules.order.utils.PlantformUtils;
import org.springblade.modules.order.utils.Target;
import org.springblade.modules.order.utils.WebPageFunUtils;
import org.springblade.modules.system.pojo.entity.Region;
import org.springblade.modules.system.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 低效电站 服务实现类
 *
 * @author AlexWang
 * @since 2024-06-14
 */
@Service
@AllArgsConstructor
public class PowerStationInefficientServiceImpl extends BaseServiceImpl<PowerStationInefficientMapper, PowerStationInefficientEntity> implements IPowerStationInefficientService {

	private final IMonitorEntryStatService entryStatService;
	private final IMonitorEntryYearStatService yearStatService;
	private final IMonitorEntryMonthStatService monthStatService;
	private final IInefficientSettingService inefficientSettingService;

	private final OperationOrderServiceImpl orderService;

	private final IPowerStationService powerStationService;

	private final IRegionService regionService;

	private final OperationSiteServiceImpl siteService;
	private final OperationSiteEmployeeMapper employeeMapper;

	private final PlatformEmployeeServiceImpl platformEmployeeService;

	private final OperationOrderOperationInfoServiceImpl infoService;
	private final BladeRedis bladeRedis;

	@Override
	public IPage<PowerStationInefficientVO> selectPowerStationInefficientPage(IPage<PowerStationInefficientVO> page, PowerStationInefficientVO powerStationInefficient) {


		return page.setRecords(baseMapper.selectPowerStationInefficientPage(page, powerStationInefficient));
	}

	@Override
	public IPage<PowerStationInefficientEntity> selectAllPage(Map<String, Object> powerStationInefficient, Query query) {

		BladeUser user = AuthUtil.getUser();
		if ("3".equals(user.getDeptId())) {  //服务商
			OperationSiteEntity site = siteService.findSiteByUserId(user.getUserId());
			powerStationInefficient.put("omProviderId",site.getId());

		} else if ("5".equals(user.getDeptId())) {  //服务商人员
			EmpAuthVo authVo=employeeMapper.findEmpAuthByUserId(user.getUserId());
			powerStationInefficient.put("omProviderId",authVo.getId());
		}else if("4".equals(user.getDeptId())) { //
			EmpAuthVo authVoP = platformEmployeeService.findPlatEmpAuthByUserId(user.getUserId());
			if (authVoP != null) {
				powerStationInefficient.put("omProviderId", authVoP.getId());
				powerStationInefficient.put("capitalName", authVoP.getPartnerName());

			}
		}
		QueryWrapper<PowerStationInefficientEntity> wrapper = Condition.getQueryWrapper(powerStationInefficient, PowerStationInefficientEntity.class);
		if("0".equals(powerStationInefficient.get("status_equal")) && "1".equals(powerStationInefficient.get("isConfirm"))){
			wrapper.and(
				wrappera -> wrappera.lambda().ge(PowerStationInefficientEntity::getStart, LocalDate.now().minusDays(7))
					.or().inSql(PowerStationInefficientEntity::getOrderNumber,"select number from sf_operation_order o where o.number = order_number and o.status in('1','2','3')")
			);

		}else if("1".equals(powerStationInefficient.get("isConfirm"))){
			wrapper.lambda().lt(PowerStationInefficientEntity::getStart, LocalDate.now().minusDays(7));
		}
		wrapper.lambda().gt(PowerStationInefficientEntity::getMgHour,0);
		return this.page(Condition.getPage(query), wrapper);
	}

	@Override
	public void fillStaticsVO(StationStaticsVO vo) {
		if(vo == null){return;}

		if(StringUtil.isNotBlank(vo.getOutStationId())){
			vo.setEntryStat(entryStatService.getEntryStatInCache(vo.getOutStationId()));

			InefficientSettingEntity setting = inefficientSettingService.getSettingByStation(vo);

			Calendar calendar = Calendar.getInstance();
			int currentMonth = calendar.get(Calendar.MONTH) + 1;
			int currentYear = calendar.get(Calendar.YEAR);
			if(setting!=null){
				Double currentGuardHour= (Double) CommonUtil.reflectGetField(setting,"guardHourM"+currentMonth);
				vo.setCurrentGuardEnergy(CommonUtil.round(currentGuardHour*vo.getActualCapacity().doubleValue(),3));
				if(vo.getEntryStat()!=null && vo.getEntryStat().getEtm()!=null){
					vo.setCurrentGuardRate(CommonUtil.round(vo.getEntryStat().getEtm()/vo.getCurrentGuardEnergy(),3));
				}
			}

			List<StaticsMonthVO> monthList = Lists.newArrayList();

			List<MonitorEntryYearStatEntity> monthDataList = yearStatService.listYearByEntry(vo.getOutStationId(),vo.getYear());

			Map<Integer, MonitorEntryYearStatEntity> monthMap = monthDataList.stream().collect(Collectors.toMap(MonitorEntryYearStatEntity::getMonth, o -> o));
			for(int i=1;i<=12;i++){
				MonitorEntryYearStatEntity monthData = monthMap.get(i);
				if(monthData==null){
					monthData = new MonitorEntryYearStatEntity();
					monthData.setYear(vo.getYear());
					monthData.setMonth(i);
					monthData.setEnergy(0D);
				}

				StaticsMonthVO monthVO = new StaticsMonthVO();
				monthVO.setYear(vo.getYear());
				if(monthData.getEnergy()>50000){
					monthData.setEnergy(monthData.getEnergy()/1000);
				}
				monthVO.setMonth(monthData.getMonth()+"");
				monthVO.setEnergy(CommonUtil.round(monthData.getEnergy(),3));
				if(vo.getEntryStat()!=null
					&& currentYear == vo.getYear()
					&& i==currentMonth
					&& vo.getEntryStat().getEtm()!=null){
					monthVO.setEnergy(vo.getEntryStat().getEtm());
				}
				if(setting!=null){
					Double guardHour= (Double) CommonUtil.reflectGetField(setting,"guardHourM"+monthData.getMonth());
					monthVO.setGuardEnergy(CommonUtil.round(guardHour*vo.getActualCapacity().doubleValue(),3));
					Double guardRate = CommonUtil.setScale(monthVO.getEnergy()/monthVO.getGuardEnergy()*100,0);
					monthVO.setGuardRate(guardRate+"%");
				}
				monthList.add(monthVO);
			}

			vo.setMonthList(monthList);

			vo.setYesterdayEnergy(monthStatService.getYesterdayEnergy(vo.getOutStationId()));
		}
	}

	@Override
	public List<StationStaticsExcel> exportStationStatics(Map<String, Object> powerStation) {
		Integer year = 2025;
		if(powerStation.containsKey("year")){
			year = Integer.valueOf(powerStation.get("year").toString());
			powerStation.remove("year");
		}
		Set<String> delKeys = Sets.newHashSet();
		for(String key :powerStation.keySet()){
			if(key.contains("$")){
				delKeys.add(key);
			}
		}
		delKeys.forEach(key->{
			powerStation.remove(key);
		});



		QueryWrapper<PowerStationEntity> queryWrapper =Condition.getQueryWrapper(powerStation, PowerStationEntity.class);
		//queryWrapper.lambda().gt(PowerStationEntity::getEto,0);
		queryWrapper.lambda().eq(PowerStationEntity::getApplyStatus,1);
		List<PowerStationEntity> list =powerStationService.list(queryWrapper);
		List<StationStaticsVO> stationStaticsList = PowerStationWrapper.build().staticsListVO(list);
		List<StationStaticsExcel> result = Lists.newArrayList();
		for(StationStaticsVO vo : stationStaticsList){
			vo.setYear(year);
			fillStaticsVO(vo);

			StationStaticsExcel excel = new StationStaticsExcel();
			BeanUtil.copyProperties(vo,excel);
			excel.setActualCapacityStr(vo.getActualCapacity() != null?vo.getActualCapacity().doubleValue():0);
			excel.setCurrentGuardEnergyStr(vo.getCurrentGuardEnergy());
			if(vo.getCurrentGuardRate() != null){
				excel.setCurrentGuardRateStr(CommonUtil.setScale(vo.getCurrentGuardRate()*100,0)+"%");
			}

			MonitorEntryStatEntity entryStat = vo.getEntryStat();
			if(entryStat!=null){
				excel.setEtdStr(entryStat.getEtd());
				excel.setEtmStr(entryStat.getEtm());
				if(entryStat.getFisGenerateTime()!=null){
					excel.setFisGenerateTimeStr(DateUtil.format(entryStat.getFisGenerateTime(),"yyyy-MM-dd"));
				}
				for(int i=0;i<12;i++){
					StaticsMonthVO monthVO = vo.getMonthList().get(i);
					CommonUtil.reflectSetField(excel,"energy_"+monthVO.getMonth(),monthVO.getEnergy());
					CommonUtil.reflectSetField(excel,"guardEnergy_"+monthVO.getMonth(),monthVO.getGuardEnergy());
					CommonUtil.reflectSetField(excel,"guardRate_"+monthVO.getMonth(),monthVO.getGuardRate());
				}
			}
			result.add(excel);
		}
		return result;
	}

	@Override
	public boolean updateSiteName(String entryIds, OperationSiteEntity site) {
		LambdaUpdateWrapper<PowerStationInefficientEntity> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.set(PowerStationInefficientEntity::getOmProviderId,site.getId()).set(PowerStationInefficientEntity::getOmProviderName,site.getName())
			.in(PowerStationInefficientEntity::getStationId, Func.toLongList(entryIds));
		return this.update(updateWrapper);
	}

	@Override
	public boolean deleteSiteName(String entryIds) {
		LambdaUpdateWrapper<PowerStationInefficientEntity> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.set(PowerStationInefficientEntity::getOmProviderId,"").set(PowerStationInefficientEntity::getOmProviderName,"")
			.in(PowerStationInefficientEntity::getStationId, Func.toLongList(entryIds));
		return this.update(updateWrapper);
	}


	@Override
	public List<PowerStationInefficientExcel> exportPowerStationInefficient(Map<String, Object> powerStationMap) {

		BladeUser user = AuthUtil.getUser();
		if ("3".equals(user.getDeptId())) {  //服务商
			OperationSiteEntity site = siteService.findSiteByUserId(user.getUserId());
			powerStationMap.put("omProviderId",site.getId());

		} else if ("5".equals(user.getDeptId())) {  //服务商人员
			EmpAuthVo authVo=employeeMapper.findEmpAuthByUserId(user.getUserId());
			powerStationMap.put("omProviderId",authVo.getId());
		}else if("4".equals(user.getDeptId())) { //
			EmpAuthVo authVoP = platformEmployeeService.findPlatEmpAuthByUserId(user.getUserId());
			if (authVoP != null) {
				powerStationMap.put("omProviderId", authVoP.getId());
				powerStationMap.put("capitalName", authVoP.getPartnerName());

			}
		}
		QueryWrapper<PowerStationInefficientEntity> wrapper = Condition.getQueryWrapper(powerStationMap, PowerStationInefficientEntity.class);
		if("0".equals(powerStationMap.get("status_equal")) && "1".equals(powerStationMap.get("isConfirm"))){
			wrapper.and(
				wrappera -> wrappera.lambda().ge(PowerStationInefficientEntity::getStart, LocalDate.now().minusDays(7))
					.or().inSql(PowerStationInefficientEntity::getOrderNumber,"select number from sf_operation_order o where o.number = order_number and o.status in('1','2','3')")
			);
		}else if("1".equals(powerStationMap.get("isConfirm"))){
			wrapper.lambda().lt(PowerStationInefficientEntity::getStart, LocalDate.now().minusDays(7));
		}

		List<PowerStationInefficientEntity> powerStationInefficientList = this.list(wrapper);
		List<PowerStationInefficientExcel> result = Lists.newArrayList();

		powerStationInefficientList.forEach(powerStationInefficient -> {
			PowerStationInefficientExcel excel = new PowerStationInefficientExcel();
			BeanUtil.copyProperties(powerStationInefficient,excel);
			String startStr = DateUtil.format(powerStationInefficient.getStart(), "yyyy-MM-dd");
			String endStr = DateUtil.format(powerStationInefficient.getEnd(), "yyyy-MM-dd");
			excel.setStart_and(startStr+"-"+endStr);
			result.add(excel);
//			powerStationInefficient.setTypeName(DictCache.getValue(DictEnum.YES_NO, PowerStationInefficient.getType()));
		});
		return result;
	}

	@Override
	public boolean turnMainOrder(String id) {
		BladeUser user = AuthUtil.getUser();
		Date time = new Date();
		PowerStationInefficientEntity customerEntry =  getById(id);
		PowerStationEntity entity = powerStationService.getStationDetailByPowCode(customerEntry.getStationCode());
		if(entity == null){
			throw  new ServiceException("该电站已不存在");
		}
		if(StringUtil.isBlank(customerEntry.getOmProviderId())){
			if(StringUtil.isBlank(entity.getOmProviderId())){
				throw  new ServiceException("该电站未绑定运维商，不可转运维");
			}
			customerEntry.setOmProviderId(entity.getOmProviderId());
			customerEntry.setOmProviderName(entity.getOmProviderName());
		}
		Long count = orderService.findRetunCountByOrderId(entity.getInnerStationId());
		if(count>0){
			throw  new ServiceException("该电站已经转运维，不可重复操作");
		}
		BigDecimal bd = BigDecimal.ZERO;
		String number = PlantformUtils.getOrderNumber();
		OperationOrderEntity order = new OperationOrderEntity();
		order.setNumber(number);
		order.setOrderType("5");//监控转运维
		order.setCreateTime(time);
		order.setRepairTime(time);
		order.setCreateBy(user.getUserId().toString());

		order.setCustomerName(customerEntry.getOwnerName());
		order.setPowerStationCode(customerEntry.getStationCode());
		order.setCapitalName(customerEntry.getCapitalName());
		order.setCapitalCode(customerEntry.getCapitalCode());
		Region region = new Region();
		region.setProvinceName(entity.getProvince());
		region.setRegionLevel(1);
		Region detail = regionService.getOne(Condition.getQueryWrapper(region));
		if(detail!= null){
			order.setProvinceCode(detail.getProvinceCode());
		}
		order.setProvince(entity.getProvince());
		region.setCityName(entity.getCity());
		region.setRegionLevel(2);
		Region citys = regionService.getOne(Condition.getQueryWrapper(region));
		if(citys!= null){
			order.setCityCode(citys.getCityCode());
		}
		order.setCity(entity.getCity());
		region.setDistrictName(entity.getDistrict());
		region.setRegionLevel(3);
		Region distr = regionService.getOne(Condition.getQueryWrapper(region));
		if(distr!= null){
			order.setAreaCode(distr.getDistrictCode());
		}
		order.setArea(entity.getDistrict());

		order.setCustomerAddress(entity.getAddress());

		order.setCustomerMobile(customerEntry.getOwnerPhone());
		order.setPowerStationName(customerEntry.getStationCode());
		order.setEntryId(entity.getInnerStationId());
		order.setAgentId(entity.getAgentId());
		order.setAgentName(entity.getAgentName());
		order.setApplianceBrand(DictCache.getValue(DictEnum.DEVICE_BRAND, entity.getBrand()));
		if(entity.getStartGenDate()!= null){
			String shtime = orderService.getFirstDayofNextMonth(entity.getStartGenDate(),"yyyy-MM-dd");
			order.setApplianceBuyTime(DateUtil.parse(shtime,"yyyy-MM-dd"));
			order.setPutIntoTime(DateUtil.parse(shtime,"yyyy-MM-dd"));
		}
		order.setApplianceBarcode(entity.getSn());
		if(StringUtils.isNotBlank(customerEntry.getOmProviderId())){
			order.setSiteId(customerEntry.getOmProviderId());
			order.setSiteName(customerEntry.getOmProviderName());
			order.setStatus(OrderConstants.ORDER_STATUS_SERVICE);
			order.setSiteStatus(OrderConstants.SITE_STATUS_GET);
			order.setDispatchTime(time);
			if(order.getWarningStartDay()==null){
				order.setWarningStartDay(DateUtils.addDays(time,3));
			}
		}

		//order.setRemarks(alarm.getMalfunctionCode()+","+alarm.getAlarmName());//故障码+告警名称(故障信息)
		order.setComplaintCount(0);
		order.setSiteCost(bd);
		order.setAccountsReceivable(bd);
		order.setTotalCollections(bd);
		order.setMileage(bd);
		order.setMileCost(bd);
		order.setServiceCost(bd);
		order.setFittingCost(bd);
		order.setSpecialInstallation("1");

		Target ta = new Target();
		ta.setD(DateUtil.formatDateTime(time));
		ta.setP(user.getNickName());
		ta.setC(user.getNickName() + "转运维接入");
		ta.setT(Target.NEW_ORDER);
		if (!orderService.save(order)) {
			throw  new ServiceException("该电站转运维失败");
		}
		customerEntry.setOrderNumber(order.getNumber());
		entity.setOrderNumber(order.getNumber());
		String str = WebPageFunUtils.appendOrderProcessDetail(ta, "");
		OperationOrderOperationInfoEntity info = new OperationOrderOperationInfoEntity();
		info.setOrderId(order.getId());
		info.setProcessDetail(str);
		if(StringUtil.isNotBlank(order.getSiteId())){
			info.setSiteId(order.getSiteId());
		}
		powerStationService.updateById(entity);
		updateById(customerEntry);
		return infoService.save(info);
	}


}
