package com.sw.mes.yb.ipc.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sw.mes.core.utils.BeanUtil;
import com.sw.mes.enumvalue.EnumValuesServer;
import com.sw.mes.yb.ipc.dto.IpcStandbyInfoDto;
import com.sw.mes.yb.plan.entity.ProductionSchedule;
import com.sw.mes.yb.plan.service.ProductionScheduleService;
import com.sw.mes.yb.report.entity.CrystalPullingInfo;
import com.sw.mes.yb.report.service.CrystalPullingInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import com.sw.mes.base.factory.init.entity.Equipment;
import com.sw.mes.base.factory.init.service.EquipmentService;
import com.sw.mes.yb.ipc.dto.ButtonClickDto;
import com.sw.mes.yb.ipc.mapping.ButtonType;
import com.sw.mes.yb.ipc.service.IBaseButtonHandler;
import com.sw.mes.yb.production.entity.EquipmentExtendState;
import com.sw.mes.yb.production.entity.EquipmentWorkHoursLog;
import com.sw.mes.yb.production.service.EquipmentExtendStateService;
import com.sw.mes.yb.production.service.EquipmentWorkHoursLogService;

/**
 * 开始待机/结束待机 点击处理
 *
 * @author 李儒
 *
 */
@Service
@Transactional
public class EquipmentStateUpdateClickServiceImpl implements IBaseButtonHandler {

	@Autowired
	private EquipmentService equipmentService;
	@Autowired
	private EquipmentExtendStateService equipmentExtendStateService;
	@Autowired
	private EquipmentWorkHoursLogService equipmentWorkHoursLogService;

	@Autowired
	private CrystalPullingInfoService crystalPullingInfoService;

	@Autowired
	private ProductionScheduleService scheduleService;

	@Override
	public Object execute(ButtonClickDto dto) throws Exception {

		if (dto.getButtonName().equals("开始待机")) {
			Equipment equipment = equipmentService.findByCode(dto.getEquipmentCode());


			//状态卡控，判断能否开始待机
			if(null != equipment && equipment.getStatus() == 2){
				throw new RuntimeException("设备："+dto.getEquipmentCode()+"已经处于待机状态请勿重复开始待机！");
			}

			// 判断排程情况
			List<Integer> statusList = Arrays.asList(
					EnumValuesServer.ProductionScheduleStatus.未开始.getKey(),
					EnumValuesServer.ProductionScheduleStatus.待备料.getKey(),
					EnumValuesServer.ProductionScheduleStatus.已备料.getKey(),
					EnumValuesServer.ProductionScheduleStatus.进行中.getKey()
			);
			ProductionSchedule schedule = scheduleService.findByDeviceAndStatusList(equipment.getId(), statusList);
			if (schedule != null){
				// 未开始状态则修改状态，其他状态则不允许待机
				if (schedule.getStatus() == EnumValuesServer.ProductionScheduleStatus.未开始.getKey()){
					schedule.setStatus(EnumValuesServer.ProductionScheduleStatus.已取消.getKey());
					schedule.setStatusInfo("设备待机，解绑排程任务");
					scheduleService.saveOrUpdate(schedule);
				}else {
					throw new RuntimeException("设备："+dto.getEquipmentCode() +
							" 已有 "+ EnumValuesServer.ProductionScheduleStatus.getText(schedule.getStatus()) +" 状态排程任务正在执行，不能待机！");
				}
			}

			//获取开始待机原因
			String operationCause = (String) dto.getParams().get("reason");
			if (StringUtils.isBlank(operationCause)) {
				throw new RuntimeException("请选择待机原因");
			}
			equipment.setReason(operationCause);
			equipment.setEnableState(true);
			equipment.setStatus(2);


			//开始待机，写入待机开始时间  0810
			equipment.setStartOrEndWaitTime(new Date());
			equipmentService.saveOrUpdate(equipment);


//			//信息写入拉晶情况表
//			CrystalPullingInfo crystalPullingInfo = crystalPullingInfoService.getCrystalPullingInfoByLotNo(dto.getLotNo());
//			if (null != crystalPullingInfo){
//				List<IpcStandbyInfoDto> ipcStandbyInfoDtoList = new ArrayList<>();
//				IpcStandbyInfoDto ipcStandbyInfoDto = new IpcStandbyInfoDto();
//				ipcStandbyInfoDto.setReason(operationCause);
//				ipcStandbyInfoDto.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//
//				if (null != crystalPullingInfo.getAbnormalStandbyInfo() && !crystalPullingInfo.getAbnormalStandbyInfo().isEmpty()){
//					List<IpcStandbyInfoDto> ipcStandbyInfoDtoListOld = JSON.parseArray(crystalPullingInfo.getAbnormalStandbyInfo(), IpcStandbyInfoDto.class);
//					if (null != ipcStandbyInfoDtoListOld && ipcStandbyInfoDtoListOld.size()>0){
//						ipcStandbyInfoDtoList = ipcStandbyInfoDtoListOld;
//						ipcStandbyInfoDtoList.add(ipcStandbyInfoDto);
//					}
//				}else {
//					ipcStandbyInfoDtoList.add(ipcStandbyInfoDto);
//				}
//
////				ipcStandbyInfoDtoList.add(ipcStandbyInfoDto);
//				crystalPullingInfo.setAbnormalStandbyInfo(JSONObject.toJSONString(ipcStandbyInfoDtoList));
//				crystalPullingInfoService.saveOrUpdate(crystalPullingInfo);
//			}



			EquipmentExtendState equipmentExtendState = equipmentExtendStateService.getByCode(dto.getEquipmentCode());
			if (equipmentExtendState != null) {
				equipmentExtendState.setEquipmentState(2);
				equipmentExtendStateService.saveOrUpdate(equipmentExtendState);
			}

			return "修改状态设备状态为:待机";
		} else if (dto.getButtonName().equals("异常停炉")) {
			return "修改状态设备状态为:异常停炉";
		}  else if (dto.getButtonName().equals("异常停炉结束")) {
			return "修改状态设备状态为:异常停炉结束";
		} else if (dto.getButtonName().equals("开始煅烧")) {

			Equipment equipment = equipmentService.findByCode(dto.getEquipmentCode());
			/*String operationCause = (String) dto.getParams().get("reason");
			if (StringUtils.isBlank(operationCause)) {
				throw new RuntimeException("请选择开始煅烧原因");
			}
			equipment.setReason(operationCause);*/
			equipment.setEnableState(true);
			equipment.setStatus(4);
			equipmentService.saveOrUpdate(equipment);
			EquipmentExtendState equipmentExtendState = equipmentExtendStateService.getByCode(dto.getEquipmentCode());
			if (equipmentExtendState != null) {
				equipmentExtendState.setEquipmentState(4);
				equipmentExtendStateService.saveOrUpdate(equipmentExtendState);
			}
			return "修改状态设备状态为:煅烧";
		} else if (dto.getButtonName().equals("结束煅烧") || dto.getButtonName().equals("结束待机")) {
			Equipment equipment = equipmentService.findByCode(dto.getEquipmentCode());

			//状态卡控，判断能否结束待机
			if(null != equipment && equipment.getStatus() == 1){
				throw new RuntimeException("设备："+dto.getEquipmentCode()+"已经处于结束待机状态请勿重复结束待机！");
			}

			equipment.setEnableState(true);
			equipment.setStatus(1);

			//结束待机 记录待机时长，待机相关信息
//			CrystalPullingInfo crystalPullingInfo = crystalPullingInfoService.getCrystalPullingInfoByLotNo(dto.getLotNo());
//			if (null != crystalPullingInfo){
//				//获取本次待机时长
//				Date startOrEndWaitTime = equipment.getStartOrEndWaitTime();
//				if (null != startOrEndWaitTime){
//					long standbyTime = new Date().getTime() - startOrEndWaitTime.getTime();
//					double standbyTime1 = standbyTime / 1000 / 60 / 60d;
//					BigDecimal standbyTimeForPullingInfo = new BigDecimal(standbyTime1).setScale(2, BigDecimal.ROUND_HALF_DOWN);
//					//待机时长
//					if (null == crystalPullingInfo.getStandbyTime()){
//						crystalPullingInfo.setStandbyTime(standbyTimeForPullingInfo);
//					}else {
//						crystalPullingInfo.setStandbyTime(crystalPullingInfo.getStandbyTime().add(standbyTimeForPullingInfo));
//					}
//				}
//				//待机信息
//				List<IpcStandbyInfoDto> ipcStandbyInfoDtoList = new ArrayList<>();
//				IpcStandbyInfoDto ipcStandbyInfoDto = new IpcStandbyInfoDto();
//
//				ipcStandbyInfoDto.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//				if (null != crystalPullingInfo.getAbnormalStandbyInfo() && !crystalPullingInfo.getAbnormalStandbyInfo().isEmpty()){
//					List<IpcStandbyInfoDto> ipcStandbyInfoDtoListOld = JSON.parseArray(crystalPullingInfo.getAbnormalStandbyInfo(), IpcStandbyInfoDto.class);
//					if (null != ipcStandbyInfoDtoListOld && ipcStandbyInfoDtoListOld.size()>0){
//						ipcStandbyInfoDtoList = ipcStandbyInfoDtoListOld;
//						ipcStandbyInfoDtoList.add(ipcStandbyInfoDto);
//					}
//				}else {
//					ipcStandbyInfoDtoList.add(ipcStandbyInfoDto);
//				}
//				crystalPullingInfo.setAbnormalStandbyInfo(JSONObject.toJSONString(ipcStandbyInfoDtoList));
//				crystalPullingInfoService.saveOrUpdate(crystalPullingInfo);
//			}else {
//				throw new RuntimeException("拉晶实实时况为空，请先开炉！");
//			}

			//结束待机，写入结束待机时间
			equipment.setStartOrEndWaitTime(new Date());



			equipmentService.saveOrUpdate(equipment);

			EquipmentExtendState equipmentExtendState = equipmentExtendStateService.getByCode(dto.getEquipmentCode());
			if (equipmentExtendState != null) {
				equipmentExtendState.setEquipmentState(1);
				equipmentExtendStateService.saveOrUpdate(equipmentExtendState);
			}
			return "修改状态设备状态为:运行";
		}
		return "未修改状态设备";
	}

	@Override
	public void writeWorkHours(ButtonClickDto dto) {
		if(ButtonType.isCalculationWorkHours(dto.getButtonName())) {
			EquipmentWorkHoursLog log = new EquipmentWorkHoursLog();
			BeanUtil.copyProperties(dto, log);


			String changePath = "";

			//获取上次操作
			EquipmentWorkHoursLog preLog = equipmentWorkHoursLogService.getByEquipmentCodeLastOperation(dto.getEquipmentCode());
			if(preLog!=null) {
				changePath = preLog.getButtonName();
				log.setStartTime(preLog.getEndTime());
				log.setWorkStep(ButtonType.getType(preLog.getButtonName()));
			}

			changePath = changePath + "->" + dto.getButtonName();

			log.setChangePath(changePath);
			log.setEndTime(new Date());

			if(log.getStartTime()!=null && log.getEndTime()!=null) {
				log.setTimeLong(log.getEndTime().getTime() - log.getStartTime().getTime());
			}else {
				log.setTimeLong(0L);
			}

			equipmentWorkHoursLogService.saveOrUpdate(log);
		}
	}

}
