package com.shkj.wms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shkj.common.core.domain.Result;
import com.shkj.common.enums.HttpStatus;
import com.shkj.common.utils.DateUtils;
import com.shkj.common.utils.SecurityUtils;
import com.shkj.common.utils.StringUtils;
import com.shkj.system.service.ISysParameterService;
import com.shkj.wms.bo.BasePointDeviceQueryBo;
import com.shkj.wms.domain.*;
import com.shkj.wms.enums.TaskStatusEnum;
import com.shkj.wms.enums.TaskTypeEnum;
import com.shkj.wms.mapper.*;
import com.shkj.wms.service.*;
import com.shkj.wms.bo.BusinContainerUpkeepAddBo;
import com.shkj.wms.bo.BusinContainerUpkeepQueryBo;
import com.shkj.wms.constants.ParameterConstants;
import com.shkj.wms.third.rcs.RCSUtil;
import com.shkj.wms.third.rcs.dto.RcsCreateTaskDto;
import com.shkj.wms.third.rcs.dto.RcsIdList;
import com.shkj.wms.third.rcs.enums.RCSTaskTypeEnum;
import com.shkj.wms.utils.JsonUtil;
import com.shkj.wms.vo.BaseDevicePlcVo;
import com.shkj.wms.vo.BaseLocationVo;
import com.shkj.wms.vo.BasePointDeviceVo;
import com.shkj.wms.vo.BusinContainerUpkeepVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zjx
 */
@Slf4j
@Service
public class IBusinContainerUpkeepServiceImpl extends ServiceImpl<BusinContainerUpkeepMapper, BusinContainerUpkeep> implements IBusinContainerUpkeepService {

    @Autowired
    private ISysParameterService sysParameterService;

    @Autowired
    IBasePointService iBasePointService;

    @Resource
    private BasePointDeviceMapper basePointDeviceMapper;

    @Resource
    private IBusinEnptyContainerServiceImpl iBusinEnptyContainerServiceImpl;

    @Resource
    private BaseLocationPlcMapper baseLocationPlcMapper;

    @Resource
    IBusinDataTaskService iBusinDataTaskService;

    @Resource
    RCSUtil rcsUtil;

    @Resource
    IBasePointService basePointService;

    @Resource
    BaseLocationMapper baseLocationMapper;

    @Resource
    BaseContainerMapper baseContainerMapper;

    @Override
    public List<BusinContainerUpkeepVo> getContainerUpkeepDate(BusinContainerUpkeepQueryBo bo) {
        //治具保养周期
        bo.setBranchId(SecurityUtils.getCurrentBranchId());
        return this.baseMapper.getContainerUpkeepDate(bo);
    }

    /**
     *  App治具入库-确认入库(保养完成)
     * @param bo bo
     * @return
     */
    @Override
    public Result<Boolean> saveBusintContainerUpkeepEnd(BusinContainerUpkeepAddBo bo) {

        //更新保养的记录，新增
        BusinContainerUpkeep businContainerUpkeep = this.baseMapper.selectById(bo.getId());
        if(businContainerUpkeep != null){
            businContainerUpkeep.setIsUpkeep("1");
            this.baseMapper.updateById(businContainerUpkeep);
        }else {
            businContainerUpkeep = new BusinContainerUpkeep();
        }

        BaseContainer baseContainer = baseContainerMapper.selectOne(new LambdaQueryWrapper<BaseContainer>()
                .eq(BaseContainer::getContainerCode,bo.getContainerCode()).last("limit 1"));

        if(ObjectUtils.isNotEmpty(bo.getContainerId())){
            businContainerUpkeep.setContainerId(bo.getContainerId());
        }else{
            businContainerUpkeep.setContainerId(baseContainer.getId());
        }

        businContainerUpkeep.setIsUpkeep("0");

        businContainerUpkeep.setUpkeepTime(DateUtils.getNowDate());

        String upkeepDay = sysParameterService.selectConfigByKey(ParameterConstants.ParameterSystem.upkeep_day);
        businContainerUpkeep.setNextUpkeep(DateUtils.addDateDay(Integer.valueOf(upkeepDay)));
        businContainerUpkeep.setUpkeepDay(Integer.valueOf(upkeepDay));

        this.baseMapper.insert(businContainerUpkeep);

        //更新点位状态信息，
        //把占用的点位改为已占用
        // TODO 临时注释   用于某一点位入库空治具
//        String tepairGroup = sysParameterService.selectConfigByKey(ParameterConstants.ParameterSystem.Upkeep_piont);
//        BasePointDeviceQueryBo pointQueryBo1 = new BasePointDeviceQueryBo();
//        pointQueryBo1.setGroupNo(tepairGroup);
//        BasePointDeviceVo pointDevice = basePointDeviceMapper.selectBasePointByGroupno(pointQueryBo1);
//
//        BasePoint basePoint = new BasePoint();
//        basePoint.setPointNo(pointDevice.getPointNo());
//        basePoint = iBasePointService.selectBasePoint(basePoint);
//        basePoint.setIsOccupy("1");
//        iBasePointService.updateById(basePoint);
        //TODO 呼叫AGV，判断任务是否有需要空治具的任务，如果有，则送达


        Map map = iBusinEnptyContainerServiceImpl.checkWareForEmptycon();
        if(ObjectUtils.isEmpty(map)){
            return Result.err().msg("暂无空治具存放区域");
        }
        BasePointDeviceVo pointDeviceVo = BeanUtil.toBean(map.get("basePointDeviceVo"),BasePointDeviceVo.class);
        BaseLocationVo locationVo = BeanUtil.toBean(map.get("locationVo"), BaseLocationVo.class);
        String agvType= String.valueOf(RCSTaskTypeEnum.A_TO_B_HAND_PUT.getValue());
        String toPpoint = pointDeviceVo.getPointNo();
        Long dspPlcId =Long.valueOf(sysParameterService.selectConfigByKey(ParameterConstants.ParameterSystem.LK_plc_id));

        //获取巷道对应的堆垛机信息
        BasePointDeviceQueryBo pointQueryBo = new BasePointDeviceQueryBo();
        pointQueryBo.setDevType("1");
        pointQueryBo.setTunnel(pointDeviceVo.getTunnel());
        BaseDevicePlcVo baseDevicePlcVo = baseLocationPlcMapper.selectBaseDevicePlc(pointQueryBo);
        Long stkPlcId = baseDevicePlcVo.getPlcId();
        String tunnelId = baseDevicePlcVo.getTunnel();


        //创建任务
        BusinDataTask businDataTask = new BusinDataTask();
        businDataTask.setTaskPath(toPpoint);
        String taskstatus= TaskStatusEnum.wait_put.getValue();
        businDataTask.setTaskStatus(taskstatus);
        String Type= TaskTypeEnum.emptyCon.getValue();
        businDataTask.setTaskType(Type);
        businDataTask.setIsDown(agvType);
        if(ObjectUtils.isNotEmpty(bo.getContainerId())){
            businDataTask.setContainerId(bo.getContainerId());
        }else{
            businDataTask.setContainerId(baseContainer.getId());
        }

        businDataTask.setDpsNoOne(dspPlcId);
        businDataTask.setDpsNoTwo(stkPlcId);
        businDataTask.setTunnel(tunnelId);
        businDataTask.setBatch(DateUtils.getDate());

        if (locationVo!=null){
            businDataTask.setToColumn(locationVo.getLocationColumn());
            businDataTask.setToLayer(locationVo.getLayer());
            businDataTask.setToRow(locationVo.getLocationRow());
            businDataTask.setLocationId(locationVo.getId());

        }

        int  agvTaskType = Integer.valueOf(agvType);
        RcsCreateTaskDto dto = new RcsCreateTaskDto();
        Map<String,String> snPointMap = new HashMap<>();
        List<RcsIdList> idList = new ArrayList<>();

        dto.setMapId(1);
        dto.setTaskType(agvTaskType);

        RcsIdList startId = new RcsIdList();
        RcsIdList lyId = new RcsIdList();
        RcsIdList endId = new RcsIdList();
// TODO 临时注释  用于某一点位入库空治具
//        startId.setId(pointDevice.getPointNo());
//        snPointMap.put("1",pointDevice.getPointNo());
        startId.setId(bo.getPointNo());
        snPointMap.put("1",bo.getPointNo());
        idList.add(startId);
        snPointMap.put("2",pointDeviceVo.getHandshakePoint());
        lyId.setId(pointDeviceVo.getHandshakePoint());
        idList.add(lyId);
        snPointMap.put("3",toPpoint);
        endId.setId(toPpoint);
        idList.add(endId);
        dto.setTargets(idList);

        businDataTask.setPoints(JsonUtil.toJSONString(snPointMap));

        //创建任务
        iBusinDataTaskService.insertBusinTask(businDataTask);
        Long taskId = businDataTask.getId();
        dto.setTaskId(taskId.toString());
        //呼叫AGV
        Result<Boolean> booleanResult =  rcsUtil.rcsCreateTask(dto);

        if (booleanResult.getCode()== HttpStatus.SUCCESS.getCode()){

            businDataTask.setTaskStatus(TaskStatusEnum.wait_callback.getValue());
            iBusinDataTaskService.updateById(businDataTask);
            //更改点位状态为空闲
            // TODO 临时注释  用于某一点位入库空治具
//            BasePoint basePoint1 = basePointService.selectBasePointByPointNo(pointDevice.getPointNo());
//            basePoint1.setIsOccupy("0");
//            basePointService.updateById(basePoint1);

        BasePoint basePoint = new BasePoint();
        basePoint.setPointNo(bo.getPointNo());
        basePoint = iBasePointService.selectBasePoint(basePoint);
        basePoint.setIsOccupy("0");
        iBasePointService.updateById(basePoint);
        //更新货位状态为已分配
        if (locationVo!=null){
            BaseLocation baseLocation = BeanUtil.toBean(locationVo,BaseLocation.class);
            baseLocation.setLocationStatus("4");
            baseLocationMapper.updateById(baseLocation);
        }
        //有呼叫空治具的任务时添加任务后更改原任务状态
        }

        return Result.ok();
    }

    /**
     * App治具保养-确认取出（去保养）
     *
     * @param bo bo
     * @return 结果
     */
    @Override
    public Result<Boolean> saveBusintContainerUpkeepStart(BusinContainerUpkeepAddBo bo) {

        //获取需要保养治具的点位信息；
        String pointNo = bo.getPointNo();
        BasePoint basePoint = new BasePoint();
        basePoint.setPointNo(pointNo);
        basePoint = iBasePointService.selectBasePoint(basePoint);
        basePoint.setIsOccupy("0");
        iBasePointService.updateById(basePoint);
        return Result.ok();
    }
}
