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

import java.util.Date;
import java.util.Map;

import com.sw.mes.core.utils.BeanUtil;
import com.sw.mes.redis.server.RedisUtils;
import com.sw.mes.yb.pad.controller.PadDeviceCheckController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.enumvalue.EnumValuesAgv;
import com.sw.mes.base.factory.init.entity.Equipment;
import com.sw.mes.base.factory.init.service.EquipmentService;
import com.sw.mes.yb.agv.dto.AgvCallDto;
import com.sw.mes.yb.agv.dto.AgvLockDto;
import com.sw.mes.yb.agv.service.AgvDispatchService;
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.EquipmentWorkHoursLog;
import com.sw.mes.yb.production.service.EquipmentWorkHoursLogService;

/**
 * AGV操作 点击处理
 *
 * @author 李儒
 *
 */
@Service
@Transactional
public class AgvOperationClickServiceImpl implements IBaseButtonHandler {

	@Autowired
	private EquipmentWorkHoursLogService equipmentWorkHoursLogService;
	@Autowired
	private RedisUtils redisUtils;
	@Autowired
	private EquipmentService equipmentService;

	@Autowired
    AgvDispatchService agvDispatchService;

	@Override
	public Object execute(ButtonClickDto dto) throws Exception {
		if (dto.getButtonName().equals("库位解锁")) {
			if(StringUtils.isBlank(dto.getEquipmentCode())) {
				throw new RuntimeException("缺少当前炉台号");
			}

			try {
        		AgvLockDto agvLock = new AgvLockDto();
        		agvLock.setKeyword(EnumValuesAgv.AGVKeyword.库位解锁.getValue());//关键字 根据配置中的信息固定写入  : 圆棒送验
        		agvLock.setPosCode(dto.getEquipmentCode());
        		agvLock.setLocked(0);
                //其他信息可根据配置信息自动填充
                agvDispatchService.storeLock(agvLock);
                redisUtils.set(dto.getEquipmentCode()+"-store-lock", false);
            } catch (Exception e) {
            	throw new RuntimeException(e.getMessage());
            }
			return "操作:库位解锁";
		} else if (dto.getButtonName().equals("库位锁定")) {
			if(StringUtils.isBlank(dto.getEquipmentCode())) {
				throw new RuntimeException("缺少当前炉台号");
			}

			try {
        		AgvLockDto agvLock = new AgvLockDto();
        		agvLock.setKeyword(EnumValuesAgv.AGVKeyword.库位解锁.getValue());//关键字 根据配置中的信息固定写入  : 圆棒送验
        		agvLock.setPosCode(dto.getEquipmentCode());
        		agvLock.setLocked(1);
                //其他信息可根据配置信息自动填充
                agvDispatchService.storeLock(agvLock);
                redisUtils.set(dto.getEquipmentCode()+"-store-lock", true);
            } catch (Exception e) {
            	throw new RuntimeException(e.getMessage());
            }
			return "操作:库位锁定";
		} else if (dto.getButtonName().equals("吊料空车")) {
			if(StringUtils.isBlank(dto.getEquipmentCode())) {
				throw new RuntimeException("缺少当前炉台号");
			}

			try {
				Equipment equipment = equipmentService.findByCode(dto.getEquipmentCode());
				String targetPoint = EnumValuesAgv.EquipmentAreaBLHCK.getText(equipment.getArea());

        		AgvCallDto agvCall = new AgvCallDto();
                agvCall.setKeyword(EnumValuesAgv.AGVKeyword.吊料空车.getValue());//关键字 根据配置中的信息固定写入  : 圆棒送验
                agvCall.setStartPoint(dto.getEquipmentCode()); //开始工作位  - 当前传入机台号
                agvCall.setTargetPoint(targetPoint);//结束工作位
                //其他信息可根据配置信息自动填充
                String taskCode = agvDispatchService.callAgv(agvCall);
            } catch (Exception e) {
            	throw new RuntimeException(e.getMessage());
            }
            return "操作:吊料空车,呼叫AGV";
			//新增按钮“送验车呼叫”20220728
		} else if (dto.getButtonName().equals("送验车呼叫")){
			if(StringUtils.isBlank(dto.getEquipmentCode())) {
				throw new RuntimeException("缺少当前炉台号");
			}
			try {
				Equipment equipment = equipmentService.findByCode(dto.getEquipmentCode());
				String targetPoint = EnumValuesAgv.EquipmentAreaBLHCK.getText(equipment.getArea());

				AgvCallDto agvCall = new AgvCallDto();
				agvCall.setKeyword(EnumValuesAgv.AGVKeyword.送验车呼叫.getValue());//关键字 根据配置中的信息固定写入  : 圆棒送验
				agvCall.setStartPoint(dto.getEquipmentCode()); //开始工作位  - 当前传入机台号
				agvCall.setTargetPoint(targetPoint);//结束工作位
				//其他信息可根据配置信息自动填充
				String taskCode = agvDispatchService.callAgv(agvCall);
			} catch (Exception e) {
				throw new RuntimeException(e.getMessage());
			}
			return "操作:送验车呼叫,呼叫AGV";
		} else if (dto.getButtonName().equals("复投空车")) {
			if(StringUtils.isBlank(dto.getEquipmentCode())) {
				throw new RuntimeException("缺少当前炉台号");
			}

            try {
            	Equipment equipment = equipmentService.findByCode(dto.getEquipmentCode());
				String targetPoint = EnumValuesAgv.EquipmentAreaBLHCK.getText(equipment.getArea());

        		AgvCallDto agvCall = new AgvCallDto();
                agvCall.setKeyword(EnumValuesAgv.AGVKeyword.复投空车.getValue());//关键字 根据配置中的信息固定写入  : 圆棒送验
                agvCall.setStartPoint(dto.getEquipmentCode()); //起始位置编号  - 当前传入机台号
                agvCall.setTargetPoint(targetPoint);//结束工作位
                //其他信息可根据配置信息自动填充
                String taskCode = agvDispatchService.callAgv(agvCall);
            } catch (Exception e) {
            	throw new RuntimeException(e.getMessage());
            }
            return "操作:复投空车,呼叫AGV";
		} else if (dto.getButtonName().equals("拆清车")) {
			if(StringUtils.isBlank(dto.getEquipmentCode())) {
				throw new RuntimeException("缺少当前炉台号");
			}

            Map<String, Object> params = dto.getParams();
            Integer delayTime = Integer.valueOf(params.get("delayTime").toString());
            Integer carNum = Integer.valueOf(params.get("carNum").toString());

            Equipment equipment = equipmentService.findByCode(dto.getEquipmentCode());
			String targetPoint = EnumValuesAgv.EquipmentAreaDMJK.getText(equipment.getArea());

            int successNum = 0;
            for (int i = 0; i < carNum; i++) {
	            try {
            		AgvCallDto agvCall = new AgvCallDto();
                    agvCall.setKeyword(EnumValuesAgv.AGVKeyword.拆清车.getValue());//关键字 根据配置中的信息固定写入  : 圆棒送验
                    agvCall.setStartPoint(dto.getEquipmentCode()); //起始位置编号  - 当前传入机台号
                    agvCall.setTargetPoint(targetPoint);//结束工作位
                    agvCall.setBufferTime(delayTime * 60 * 60);//延时时间 小时转成秒
                    //其他信息可根据配置信息自动填充
                    String taskCode = agvDispatchService.callAgv(agvCall);
                    successNum++;
	            } catch (Exception e) {
	            	throw new RuntimeException(e.getMessage());
	            }
            }

            //拆清点检按钮
            redisUtils.set(PadDeviceCheckController.DEVICE_CHECK_BUTTON_PREFIX+dto.getEquipmentCode(), 1);

            if(carNum<=1)
            	return "操作:拆清车,呼叫AGV";
            else {
            	return "操作:拆清车,呼叫"+carNum+"辆AGV,成功"+successNum+"辆";
            }

		} else if (dto.getButtonName().equals("复拉提头运输")) {
			if(StringUtils.isBlank(dto.getEquipmentCode())) {
				throw new RuntimeException("缺少当前炉台号");
			}

            try {
                AgvCallDto agvCall = new AgvCallDto();
                agvCall.setKeyword(EnumValuesAgv.AGVKeyword.复拉提头运输.getValue());//关键字 根据配置中的信息固定写入  : 圆棒送验
                agvCall.setStartPoint(dto.getEquipmentCode()); //起始位置编号  - 当前传入机台号
                //其他信息可根据配置信息自动填充
                String taskCode = agvDispatchService.callAgv(agvCall);
            } catch (Exception e) {
            	throw new RuntimeException(e.getMessage());
            }

			return "操作:复拉提头运输";
		}
		else if (dto.getButtonName().equals("送验车呼叫")) {

            //toDO 参数不确定
//            AgvCallDto agvCallDto = new AgvCallDto();
//            String taskCode = callAgv(agvCallDto);
			return "操作:送验车呼叫";

		}

		return "未知操作:"+dto.getButtonName();
	}

    @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);
		}
	}

    /**
     * ipc-agv呼叫
     * @param agvCallDto
     * @return
     */
	public String callAgv(AgvCallDto agvCallDto){
        return agvDispatchService.callAgv(agvCallDto);

    }

//    /**
//     * ipc-agv呼叫（延时任务）quartz执行定时任务，暂不能传自定义对象，改为json
//     * @param json
//     */
//    public String callAgvDelay(String json, String uuid){
//        AgvCallDto agvCallDto = JSON.parseObject(json, new TypeReference<AgvCallDto>() {
//        });
//        //TODO
////        String taskCode = agvDispatchService.callAgv(agvCallDto);
//
//        // 删除定时任务
//        List<SysJob> sysJobs = sysJobService.findByJobName("ipcCqcTask:"+uuid);
//        for (SysJob sysJob : sysJobs) {
//            try {
//                sysJobService.deleteJob(sysJob);
//            } catch (SchedulerException e) {
//                e.printStackTrace();
//            }
//        }
//        return "taskCode";
//    }


//    private Calendar getDelayDate(Object delayTime) {
//        Date currentDate = new Date();
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(currentDate);
//        int delayMinute = Integer.parseInt(new BigDecimal(delayTime.toString()).multiply(new BigDecimal("60")).multiply(new BigDecimal("60")).setScale( 0, BigDecimal.ROUND_FLOOR).toString());
//        calendar.add(Calendar.SECOND, delayMinute);
//        return calendar;
//    }
//
//    private String getMillSecond(Object delayTime){
//        return new BigDecimal(delayTime.toString()).multiply(new BigDecimal("60")).multiply(new BigDecimal("60"))
//                .multiply(new BigDecimal("1000")).setScale(0, BigDecimal.ROUND_FLOOR).toString();
//    }

}
