/**
 * BladeX Commercial License Agreement
 * Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
 * <p>
 * Use of this software is governed by the Commercial License Agreement
 * obtained after purchasing a license from BladeX.
 * <p>
 * 1. This software is for development use only under a valid license
 * from BladeX.
 * <p>
 * 2. Redistribution of this software's source code to any third party
 * without a commercial license is strictly prohibited.
 * <p>
 * 3. Licensees may copyright their own code but cannot use segments
 * from this software for such purposes. Copyright of this software
 * remains with BladeX.
 * <p>
 * Using this software signifies agreement to this License, and the software
 * must not be used for illegal purposes.
 * <p>
 * THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
 * not liable for any claims arising from secondary or illegal development.
 * <p>
 * Author: Chill Zhuang (bladejava@qq.com)
 */
package org.springblade.modules.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.nh.mapper.AlarmInfoMapper;
import org.springblade.modules.nh.pojo.entity.PowerStationEntity;
import org.springblade.modules.nh.service.impl.PowerStationServiceImpl;
import org.springblade.modules.operation.mapper.OperationSiteEmployeeMapper;
import org.springblade.modules.operation.pojo.entity.OperationServiceMeasuresEntity;
import org.springblade.modules.operation.pojo.entity.OperationServiceTypeEntity;
import org.springblade.modules.operation.pojo.entity.OperationSiteEmployeeEntity;
import org.springblade.modules.operation.pojo.entity.OperationSiteEntity;
import org.springblade.modules.operation.pojo.vo.EmpAuthVo;
import org.springblade.modules.operation.service.impl.OperationServiceMeasuresServiceImpl;
import org.springblade.modules.operation.service.impl.OperationServiceTypeServiceImpl;
import org.springblade.modules.operation.service.impl.OperationSiteServiceImpl;
import org.springblade.modules.order.constant.OrderConstants;
import org.springblade.modules.order.mapper.OperationOrderLetterMapper;
import org.springblade.modules.order.mapper.OperationOrderSettleMapper;
import org.springblade.modules.order.pojo.dto.OperationOrderSettleDTO;
import org.springblade.modules.order.pojo.entity.OperationOrderEntity;
import org.springblade.modules.order.pojo.entity.OperationOrderFeedbackEntity;
import org.springblade.modules.order.pojo.entity.OperationOrderOperationInfoEntity;
import org.springblade.modules.order.pojo.vo.*;
import org.springblade.modules.order.excel.OperationOrderExcel;
import org.springblade.modules.order.mapper.OperationOrderMapper;
import org.springblade.modules.order.service.IOperationOrderService;
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.order.wrapper.OperationOrderWrapper;
import org.springblade.modules.system.pojo.entity.Region;
import org.springblade.modules.system.service.IRegionService;
import org.springblade.modules.system.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 工单基础信息表 服务实现类
 *
 * @author lzp
 * @since 2024-06-18
 */
@Service
public class OperationOrderServiceImpl extends ServiceImpl<OperationOrderMapper, OperationOrderEntity> implements IOperationOrderService {
	@Autowired
	UserServiceImpl userService;
	@Autowired
	OperationSiteServiceImpl siteService;
	@Autowired
	OperationSiteEmployeeMapper employeeMapper;
	@Autowired
	OperationOrderOperationInfoServiceImpl infoService;

	@Autowired
	PowerStationServiceImpl powerStationService;

	@Autowired
	IRegionService regionService;

	@Autowired
	OperationServiceTypeServiceImpl serviceTypeService;
	@Autowired
	OperationServiceMeasuresServiceImpl serviceMeasuresService;

	@Autowired
	private OperationOrderSettleMapper orderSettleMapper;

	@Autowired
	private AlarmInfoMapper alarmInfoMapper;

	@Autowired
	private OperationOrderLetterMapper orderLetterMapper;

	@Override
	public OperationOrderVO findOrderDetail(String orderId) {
		OperationOrderEntity order = baseMapper.getOrderDetail(orderId);
		OperationOrderVO vo = OperationOrderWrapper.build().entityVO(order);
		OperationOrderOperationInfoEntity info = infoService.findInfoByOrderId(orderId);
		if (info != null) {
			List<Target> list = WebPageFunUtils.getOrderProcess(info.getProcessDetail());
			vo.setGuochengList(list);
		}
		OperationOrderFeedbackEntity feedbackEntity=baseMapper.getLatestByOrderId(orderId);
		if(feedbackEntity==null){
			feedbackEntity=new OperationOrderFeedbackEntity();
		}
		vo.setFeedbackEntity(feedbackEntity);
		List<String> feedImgs = baseMapper.findOrderFeedImgs(orderId);
		vo.setFeedImgs(feedImgs);
		//费用结算信息
		OperationOrderSettleDTO orderSettleDTO=orderSettleMapper.getByOrderId(orderId);
		if(orderSettleDTO==null){
			orderSettleDTO=new OperationOrderSettleDTO();
			//如果有上传公函，获取公函里面的扣款金额
			BigDecimal totalDedutionAumount=orderLetterMapper.getTotalDeductionAmount(order.getId());
			orderSettleDTO.setDeductionAmount(totalDedutionAumount);
		}
		vo.setOrderSettleDTO(orderSettleDTO);
		//获取告警名称
		if(order.getAlarmId()!=null){
           String alarmName=alarmInfoMapper.getAlarmName(order.getAlarmId());
           vo.setAlarmName(alarmName);
		}
		return vo;
	}

	@Override
	public IPage<OperationOrderVO> selectOperationOrderPage(IPage<OperationOrderVO> page, OrderListConditionVo conditionVo) {
		BladeUser user = AuthUtil.getUser();
		//	User dquser = userService.getById(user.getUserId());
        //3.服务商 4.平台员工 5.服务商人员
		if ("3".equals(user.getDeptId())) {  //服务商
			OperationSiteEntity site = siteService.findSiteByUserId(user.getUserId());
			conditionVo.setSiteId(site.getId());
		} else if ("5".equals(user.getDeptId())|| "6".equals(user.getDeptId())) {  //服务商人员
			EmpAuthVo authVo=employeeMapper.findEmpAuthByUserId(user.getUserId());
			if(authVo!=null){
				conditionVo.setSiteId(authVo.getSiteId());
				conditionVo.setProvinces(authVo.getProvinces());
				conditionVo.setCity(authVo.getCity());
				conditionVo.setArea(authVo.getArea());
				if(authVo.getRole()==1){
					conditionVo.setEmployeId(authVo.getId());
				}
			}
		}else if("4".equals(user.getDeptId())){ //平台员工
			EmpAuthVo authVoP=baseMapper.findPlatEmpAuthByUserId(user.getUserId());
			if(authVoP!= null){
				conditionVo.setSiteIds(authVoP.getSiteId());

				conditionVo.setProvinces(authVoP.getProvinces());
				conditionVo.setCity(authVoP.getCity());
				conditionVo.setArea(authVoP.getArea());
				conditionVo.setEntryIds(authVoP.getEntryId());
				//conditionVo.setCapitalName(authVoP.getPartnerName());
				if(StringUtil.isBlank(conditionVo.getCapitalName())){
					conditionVo.setCapitalName(authVoP.getPartnerName());
				}
			}

		}
		List<OperationOrderVO> list = baseMapper.selectOperationOrderPage(page, conditionVo);
			for(OperationOrderVO order : list ){
				if(order.getProcessTime()!= null && order.getEndTime() != null){
					String hour= PlantformUtils.pastHour(order.getEndTime(),order.getProcessTime());
					order.setDisEndTime(hour);
				}else if(order.getProcessTime()!= null && !OrderConstants.ORDER_STATUS_INVALID.equals(order.getStatus())){
					String hour= PlantformUtils.pastHour(new Date(),order.getProcessTime());
					order.setDisEndTime(hour);
				}
				order.setCustomerAddress(order.getCustomerAddress().replace(order.getProvince(),"").replace(order.getCity(),""));
			}
		return page.setRecords(list);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R saveOrder(OperationOrderEntity order) {
		BladeUser user = AuthUtil.getUser();

		Date time = new Date();
		if("3".equals(user.getDeptId())){        //服务商
			OperationSiteEntity site = siteService.findSiteByUserId(user.getUserId());
			order.setSiteId(site.getId());
			order.setSiteName(site.getName());
			order.setStatus(OrderConstants.ORDER_STATUS_SERVICE);
			order.setSiteStatus(OrderConstants.SITE_STATUS_DIS);
			order.setDispatchTime(time);
		}else if("5".equals(user.getDeptId())){  //服务商员工
			OperationSiteEmployeeEntity emp = employeeMapper.findByuserId(user.getUserId());
			OperationSiteEntity site = siteService.getById(emp.getSiteId());
			order.setSiteId(emp.getSiteId());
			order.setSiteName(site.getName());
			order.setStatus(OrderConstants.ORDER_STATUS_SERVICE);
			order.setSiteStatus(OrderConstants.SITE_STATUS_DIS);
			order.setDispatchTime(time);
		}
		/*if(StringUtil.isBlank(order.getServiceType())){
			throw new ServiceException("服务类型为空，请先维护服务类型");
		}*/
		String number = PlantformUtils.getOrderNumber();
		order.setCreateBy(user.getUserId().toString());
		order.setCreateName(user.getNickName());
		order.setCreateTime(time);
		order.setNumber(number);
		order.setOrderType("1");
		order.setLatestProcess(user.getNickName() + "报修");
		order.setLatestProcessTime(time);
		order.setSiteCost(BigDecimal.ZERO);
		order.setServiceCost(BigDecimal.ZERO);
		order.setFittingCost(BigDecimal.ZERO);
		order.setMileage(BigDecimal.ZERO);
		order.setMileCost(BigDecimal.ZERO);
		order.setAccountsReceivable(BigDecimal.ZERO);
		order.setTotalCollections(BigDecimal.ZERO);
		if (StringUtil.isNotBlank(order.getPowerStationCode())) {
			//获取电站信息
			PowerStationEntity entity = powerStationService.getStationDetailByPowCode(order.getPowerStationCode());
			if (entity == null) {
				R.fail(201,"当前电站编码不存在");
			}
			Long count = findRetunCountByOrderId(entity.getInnerStationId());
			if(count>0){
				throw  new ServiceException("该电站已经转运维，不可重复操作");
			}
			order.setCapitalCode(entity.getCapitalCode());
			order.setCapitalName(entity.getCapitalName());
			order.setEntryId(entity.getInnerStationId());
			order.setAgentId(entity.getAgentId());
			order.setAgentName(entity.getAgentName());
			order.setPaymentTime(entity.getPaymentTime());
			order.setWarrantyExpiresTime(entity.getWarrantyExpiresTime());
			if(entity.getStartGenDate()!= null){
				String shtime = getFirstDayofNextMonth(entity.getStartGenDate(),"yyyy-MM-dd");
				order.setApplianceBuyTime(DateUtil.parse(shtime,"yyyy-MM-dd"));
				order.setPutIntoTime(DateUtil.parse(shtime,"yyyy-MM-dd"));
			}
			//order.setApplianceBuyTime(DateUtil.plusMonths(entity.getStartGenDate(),1));
		}

		Target ta = new Target();
		ta.setD(DateUtil.formatDateTime(time));
		ta.setP(user.getNickName());
		ta.setC(user.getNickName() + "接入");
		ta.setT(Target.NEW_ORDER);
		if (!save(order)) {
			return R.fail(201,"保存失败，请刷新在试");
		}
		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());
		}
		if(!infoService.save(info)){
			return R.fail(201,"保存失败，请刷新在试");
		}
		return R.status(true);
	}

	//修改工单
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateOrder(OperationOrderEntity operationOrder){
		BladeUser user = AuthUtil.getUser();
		Date time=new Date();
		Target ta = new Target();
		ta.setD(DateUtil.formatDateTime(time));
		ta.setP(user.getNickName());
		ta.setC(user.getNickName() + "修改工单");
        operationOrder.setLatestProcess(user.getNickName()+"修改工单");
        operationOrder.setLatestProcessTime(time);
		if (!updateById(operationOrder)) {
			return false;
		}
		OperationOrderOperationInfoEntity info = infoService.findInfoByOrderId(operationOrder.getId());
		ta.setT(2);
		String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
		info.setProcessDetail(str);
		return infoService.updateById(info);
	}


	@Override
	public boolean turnMainOrder(String id) {
		BladeUser user = AuthUtil.getUser();
		Date time = new Date();
		PowerStationEntity customerEntry =  powerStationService.getById(id);
		if(StringUtil.isBlank(customerEntry.getOmProviderId())){
			throw  new ServiceException("该电站未绑定运维商，不可转运维");
		}

		Long count = findRetunCountByOrderId(customerEntry.getInnerStationId());
		if(count>0){
			throw  new ServiceException("该电站已经转运维，不可重复操作");
		}
		BigDecimal bd = BigDecimal.ZERO;
		String number = PlantformUtils.getOrderNumber();
		OperationOrderEntity order = new OperationOrderEntity();
		order.setNumber(number);
		order.setOrderType("2");//监控转运维
		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(customerEntry.getProvince());
		region.setRegionLevel(1);
		Region detail = regionService.getOne(Condition.getQueryWrapper(region));
		if(detail!= null){
			order.setProvinceCode(detail.getProvinceCode());
		}
		order.setProvince(customerEntry.getProvince());
		region.setCityName(customerEntry.getCity());
		region.setRegionLevel(2);
		Region citys = regionService.getOne(Condition.getQueryWrapper(region));
		if(citys!= null){
			order.setCityCode(citys.getCityCode());
		}
		order.setCity(customerEntry.getCity());
		region.setDistrictName(customerEntry.getDistrict());
		region.setRegionLevel(3);
		Region distr = regionService.getOne(Condition.getQueryWrapper(region));
		if(distr!= null){
			order.setAreaCode(distr.getDistrictCode());
		}
		order.setArea(customerEntry.getDistrict());

		order.setCustomerAddress(customerEntry.getAddress());

		order.setCustomerMobile(customerEntry.getOwnerPhone());
		order.setPowerStationName(customerEntry.getStationCode());
		order.setEntryId(customerEntry.getInnerStationId());
		order.setApplianceBrand(DictCache.getValue(DictEnum.DEVICE_BRAND, customerEntry.getBrand()));
		if(customerEntry.getStartGenDate()!= null){
			String shtime = getFirstDayofNextMonth(customerEntry.getStartGenDate(),"yyyy-MM-dd");
			order.setApplianceBuyTime(DateUtil.parse(shtime,"yyyy-MM-dd"));
			order.setPutIntoTime(DateUtil.parse(shtime,"yyyy-MM-dd"));
		}
		order.setApplianceBarcode(customerEntry.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.setAgentId(customerEntry.getAgentId());
		order.setAgentName(customerEntry.getAgentName());
		//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");
        order.setPaymentTime(customerEntry.getPaymentTime());
        order.setWarrantyExpiresTime(customerEntry.getWarrantyExpiresTime());
		Target ta = new Target();
		ta.setD(DateUtil.formatDateTime(time));
		ta.setP(user.getNickName());
		ta.setC(user.getNickName() + "转运维接入");
		ta.setT(Target.NEW_ORDER);
		if (!save(order)) {
			throw  new ServiceException("该电站转运维失败");
		}
		customerEntry.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(customerEntry);
		return infoService.save(info);
	}

	public static String getFirstDayofNextMonth(Date date , String format){
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		try {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime (date);
			calendar.set(Calendar.DAY_OF_MONTH,1);
			calendar.add(Calendar.MONTH, 1);
			return sdf.format(calendar.getTime());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	@Override
	public boolean toExamineOrder(ExamineOrderVo exc ) {
		 String callbackResult = exc.getCallbackResult();
		 String memoNote = exc.getMemoNote();
		OperationOrderEntity order = getById(exc.getId());
		BladeUser user = AuthUtil.getUser();
		Date time = new Date();
		String cName = "审核";
		if (!OrderConstants.ORDER_STATUS_SETTLE.equals(order.getStatus())) {
			throw new ServiceException("工单状态发生改变，不满足审核条件");
		}
		//工单服务商操作状态:0尚未指派给服务商 1待服务商接单 2服务商已拒单 3待服务商派工 4待工程师接单 5待上门 6服务中 7已完工 8派工取消 9无效工单
		//工单平台操作状态：1.待派工 2.服务中 3.待回访 4.待结算 5.已完成 6.无效工单 7.取消工单，默认1
		if(OrderConstants.CASLLBACK_RESULT_TWO.equals(callbackResult)){
			//任需上门
			order.setStatus(OrderConstants.ORDER_STATUS_SERVICE);
			order.setSiteStatus(OrderConstants.SITE_STATUS_SERVICE);
			order.setEndTime(null);
			cName = cName+"，驳回；";
		}else{
			//已完成
			//判断是否有审核中的物料申请
			long count=baseMapper.coutNoFinishFittingApply(order.getNumber());
			if(count>0){
				throw new ServiceException("该工单有未完成的物料申请，不能完工！");
			}
			order.setStatus(OrderConstants.ORDER_STATUS_FINISH);
			cName = cName+"，通过；";
			order.setSettleTime(new Date());
			//查询电站
			PowerStationEntity station = powerStationService.getStationDetailByPowCode(order.getPowerStationCode());
			if(station != null){
				station.setOrderNumber("");
				powerStationService.updateById(station);
			}

			//去除电站的工单编号
		}
		cName = cName+memoNote;
		order.setCallbackResult(callbackResult);
		order.setMemoNote(memoNote);
		Target ta = new Target();
		ta.setD(DateUtil.formatDateTime(time));
		ta.setP(user.getNickName());
		ta.setC(user.getNickName() + cName);
		//判断是否需要结算--根据电站运维商和代理商是否为同一个，工单是否在质保期内；两者有一个不满足，则工单判断为需要结算；
		if(!order.getSiteName().equals(order.getAgentName()) || (order.getWarrantyExpiresTime()!=null && (order.getWarrantyExpiresTime().compareTo(new Date()))<0)){
			order.setIfSettle("1");
		}else{
			order.setIfSettle("0");
		}
//return t);
		if (!this.update(order, Wrappers.<OperationOrderEntity>update().lambda().eq(OperationOrderEntity::getId, order.getId()))) {
			return false;
		}
		ta.setC(user.getNickName() + "操作" + cName);
		OperationOrderOperationInfoEntity info = infoService.findInfoByOrderId(order.getId());
		ta.setT(2);
		String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
		info.setProcessDetail(str);
		return infoService.updateById(info);
	}

	@Override
	public List<OperationOrderExcel> exportOperationOrder(Map<String, Object> operationOrder) {
		BladeUser user = AuthUtil.getUser();
		//User dquser = userService.getById(user.getUserId());
		if ("3".equals(user.getDeptId())) {  //服务商
			OperationSiteEntity site = siteService.findSiteByUserId(user.getUserId());
			operationOrder.put("siteId", site.getId());
		} else if ("5".equals(user.getDeptId())) {  //服务商人员
			EmpAuthVo authVo=employeeMapper.findEmpAuthByUserId(user.getUserId());
			operationOrder.put("siteId", authVo.getSiteId());
			operationOrder.put("provinces",authVo.getProvinces());
			operationOrder.put("city",authVo.getCity());
			operationOrder.put("area",authVo.getArea());
		}else if("4".equals(user.getDeptId())){ //平台员工
            EmpAuthVo authVoP=baseMapper.findPlatEmpAuthByUserId(user.getUserId());
			if(authVoP!= null){
				operationOrder.put("siteIds", authVoP.getSiteId());
				operationOrder.put("provinces",authVoP.getProvinces());
				operationOrder.put("city",authVoP.getCity());
				operationOrder.put("area",authVoP.getArea());
				operationOrder.put("entryIds",authVoP.getEntryId());
				operationOrder.put("capitalName",authVoP.getPartnerName());
			}
		}
		//
		List<OperationServiceTypeEntity> listType = serviceTypeService.list(new QueryWrapper<OperationServiceTypeEntity>().lambda().eq(OperationServiceTypeEntity::getStatus,"0"));
		Map<Long,String> maps =listType.stream().collect(Collectors.toMap(OperationServiceTypeEntity::getId, OperationServiceTypeEntity::getName));
		List<OperationServiceMeasuresEntity> listMea = serviceMeasuresService.list(new QueryWrapper<OperationServiceMeasuresEntity>().lambda().eq(OperationServiceMeasuresEntity::getIsDeleted,"0"));
		Map<Long,String> mapsmea =listMea.stream().collect(Collectors.toMap(OperationServiceMeasuresEntity::getId, OperationServiceMeasuresEntity::getServiceMeasures));
		List<OperationOrderExcel> operationOrderList = baseMapper.exportOperationOrder(operationOrder);
		for(OperationOrderExcel order : operationOrderList ){
			if(order.getProcessTime()!= null && order.getEndTime() != null){
				String hour= PlantformUtils.pastHour(order.getEndTime(),order.getProcessTime());
				order.setDisEndTime(hour);
			}else if(order.getProcessTime()!= null&& !OrderConstants.ORDER_STATUS_INVALID.equals(order.getStatus())){
				String hour= PlantformUtils.pastHour(new Date(),order.getProcessTime());
				order.setDisEndTime(hour);
			}
			order.setStatus(DictCache.getValue(DictEnum.ORDER_STATUS, order.getStatus()));
			order.setOrderType(DictCache.getValue(DictEnum.ORDER_TYPE, order.getOrderType()));
			if(StringUtil.isNotBlank(order.getServiceType())){
				order.setServiceType(maps.get(Long.valueOf(order.getServiceType())));
			}
			if(StringUtil.isNotBlank(order.getServiceMeasures())){
				order.setServiceMeasures(mapsmea.get(Long.valueOf(order.getServiceMeasures())));
			}
			if(StringUtil.isNotBlank(order.getIfOverDue())){
				if("1".equals(order.getIfOverDue())){
					order.setIfOverDue("是");
				}else{
					order.setIfOverDue("否");
				}
			}
			if(StringUtil.isNotBlank(order.getIfSettle())){
				if("1".equals(order.getIfSettle())){
					order.setIfSettle("是");
				}else{
					order.setIfSettle("否");
				}
			}
			//order.setServiceMeasures(DictCache.getValue(DictEnum.ORDER_TYPE, order.getServiceMeasures()));
		}
		return operationOrderList;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean deleteLogic(String id, String status, String disableResource) {
		BladeUser user = AuthUtil.getUser();
		Date time = new Date();
		String cName = "无效";
		OperationOrderEntity order = getById(id);
		if (OrderConstants.ORDER_STATUS_FINISH.equals(order.getStatus())) {
			throw new ServiceException("已完成的工单不可操作");
		}
		if (OrderConstants.ORDER_STATUS_INVALID.equals(status)) {  //无效工单
			if (StringUtil.isBlank(disableResource)) {
				throw new ServiceException("请输入无效原因!");
			}
			order.setSiteStatus(OrderConstants.SITE_STATUS_INVALID);  //无效工单
			//修改派工单表的状态
			baseMapper.changeDispatchOrderStatus(order.getId(), user.getNickName(), time);
			baseMapper.changeSiteDispatchOrderStatus(order.getId(), user.getNickName(), time);
		}
		if ("7".equals(status)) {
			if (!OrderConstants.ORDER_STATUS_INVALID.equals(order.getStatus())) {
				throw new ServiceException("只有无效工单才可操作删除");
			}
			cName = "删除";
		}
		//查询电站
		PowerStationEntity station = powerStationService.getStationDetailByPowCode(order.getPowerStationCode());
		if(station != null){
			station.setOrderNumber("");
			powerStationService.updateById(station);
		}

		order.setStatus(status);
		order.setDisableResource(disableResource);
		Target ta = new Target();
		ta.setD(DateUtil.formatDateTime(time));
		ta.setP(user.getNickName());
		ta.setC(user.getNickName() + cName);

		if (!updateById(order)) {
			return false;
		}
		ta.setC(user.getNickName() + "操作" + cName);
		OperationOrderOperationInfoEntity info = infoService.findInfoByOrderId(order.getId());
		ta.setT(2);
		String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
		info.setProcessDetail(str);
		return infoService.updateById(info);
	}

	@Override
	public OrderHomeVo orderHomeIndex() {
		BladeUser user = AuthUtil.getUser();
		if (!"6".equals(user.getDeptId())) {
			return new OrderHomeVo();
		}
		OperationSiteEmployeeEntity emp = employeeMapper.findByuserId(user.getUserId());

		return baseMapper.orderHomeIndex(emp.getSiteId(), emp.getId().toString());
	}

	public IPage<OrderVo> findOrderList(IPage<OrderVo> page){
		List<OrderVo> list = baseMapper.findOrderList(page);
		return page.setRecords(list);
	}

	public Long findRetunCountByOrderId(String entryId){
		return baseMapper.findRetunCountByOrderId(entryId);
	}


	@Override
	public OrderStaticVo homeOrderStatic() {
		OrderListConditionVo conditionVo=new OrderListConditionVo();
		BladeUser user = AuthUtil.getUser();
		//	User dquser = userService.getById(user.getUserId());
		//3.服务商 4.平台员工 5.服务商人员
		if ("3".equals(user.getDeptId())) {  //服务商
			OperationSiteEntity site = siteService.findSiteByUserId(user.getUserId());
			conditionVo.setSiteId(site.getId());
		} else if ("5".equals(user.getDeptId())|| "6".equals(user.getDeptId())) {  //服务商人员
			EmpAuthVo authVo=employeeMapper.findEmpAuthByUserId(user.getUserId());
			if(authVo!=null){
				conditionVo.setSiteId(authVo.getSiteId());
				conditionVo.setProvinces(authVo.getProvinces());
				conditionVo.setCity(authVo.getCity());
				conditionVo.setArea(authVo.getArea());
				if(authVo.getRole()==1){
					conditionVo.setEmployeId(authVo.getId());
				}
			}
		}else if("4".equals(user.getDeptId())){ //平台员工
			EmpAuthVo authVoP=baseMapper.findPlatEmpAuthByUserId(user.getUserId());
			if(authVoP!= null){
				conditionVo.setSiteIds(authVoP.getSiteId());
				conditionVo.setProvinces(authVoP.getProvinces());
				conditionVo.setCity(authVoP.getCity());
				conditionVo.setArea(authVoP.getArea());
				conditionVo.setEntryIds(authVoP.getEntryId());
				conditionVo.setCapitalName(authVoP.getPartnerName());
			}
		}
		return baseMapper.homeOrderStatic(conditionVo);
	}

	@Override
	public OrderHomeVo pcOrderHomeIndex(){
		OrderListConditionVo conditionVo=new OrderListConditionVo();
		BladeUser user = AuthUtil.getUser();
		//	User dquser = userService.getById(user.getUserId());
		//3.服务商 4.平台员工 5.服务商人员
		if ("3".equals(user.getDeptId())) {  //服务商
			OperationSiteEntity site = siteService.findSiteByUserId(user.getUserId());
			conditionVo.setSiteId(site.getId());
		} else if ("5".equals(user.getDeptId())|| "6".equals(user.getDeptId())) {  //服务商人员
			EmpAuthVo authVo=employeeMapper.findEmpAuthByUserId(user.getUserId());
			if(authVo!=null){
				conditionVo.setSiteId(authVo.getSiteId());
				conditionVo.setProvinces(authVo.getProvinces());
				conditionVo.setCity(authVo.getCity());
				conditionVo.setArea(authVo.getArea());
				if(authVo.getRole()==1){
					conditionVo.setEmployeId(authVo.getId());
				}
			}
		}else if("4".equals(user.getDeptId())){ //平台员工
			EmpAuthVo authVoP=baseMapper.findPlatEmpAuthByUserId(user.getUserId());
			if(authVoP!= null){
				conditionVo.setSiteIds(authVoP.getSiteId());
				conditionVo.setProvinces(authVoP.getProvinces());
				conditionVo.setCity(authVoP.getCity());
				conditionVo.setArea(authVoP.getArea());
				conditionVo.setEntryIds(authVoP.getEntryId());
				conditionVo.setCapitalName(authVoP.getPartnerName());
			}
		}
		return baseMapper.pcOrderHomeIndex(conditionVo);
	}

	@Override
	public List<OperationOrderEntity> findOrderListBySiteId(String station_code) {
		List<OperationOrderEntity> list = this.list(new QueryWrapper<OperationOrderEntity>().lambda().eq(OperationOrderEntity::getPowerStationCode,station_code).notIn(OperationOrderEntity::getStatus,"5","6","7"));
		return list;
	}


}
