package org.wcs.serve.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.wcs.business.stacker.StackerStatusMonitor;
import org.wcs.constant.enums.plc.StackerControllerModelEnum;
import org.wcs.constant.enums.plc.StackerDeviceStatusEnum;
import org.wcs.factory.AppServeResponseFactory;
import org.wcs.mapper.intf.AppStackerInfoService;
import org.wcs.mapper.intf.AppStackerStandService;
import org.wcs.model.bo.stacker.StackerStatusData;
import org.wcs.model.dto.serve.stacker.AddOrUpdateStackerStandReq;
import org.wcs.model.dto.serve.stacker.AddStackerReq;
import org.wcs.model.dto.serve.stacker.UpdateStackerInfoReq;
import org.wcs.model.po.app.AppStackerInfo;
import org.wcs.model.po.app.AppStackerStand;
import org.wcs.model.vo.serve.AppServeDataResponse;
import org.wcs.model.vo.serve.AppServeResponse;
import org.wcs.model.vo.serve.stacker.QueryStackerInfoVo;
import org.wcs.model.vo.serve.stacker.QueryStackerStandVo;
import org.wcs.model.vo.serve.stacker.StackerStatusVo;
import org.wcs.plugin.plc.model.StackerStatus;
import org.wcs.serve.service.intf.IStackerService;
import org.wcs.utils.AppBeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class StackerService implements IStackerService {

    private final AppStackerInfoService appStackerInfoService;
    private final AppStackerStandService appStackerStandService;
    private final StackerStatusMonitor stackerStatusMonitor; // 堆垛机监控类

    /**
     * 查询堆垛机信息
     * @param stackerName 堆垛机名称
     * @return 查询结果
     */
    @Override
    public AppServeDataResponse<List<QueryStackerInfoVo>> queryStackerInfo(String stackerName) {
        List<AppStackerInfo> appStackerInfos = appStackerInfoService.queryStackerInfoIndistinct(stackerName);
        if(appStackerInfos == null) {
            return AppServeResponseFactory.internalServerError("数据服务异常", null);
        }
        List<QueryStackerInfoVo> queryStackerInfoVos = AppBeanUtils.copyListProperties(appStackerInfos, QueryStackerInfoVo::new);
        return AppServeResponseFactory.success("查询成功", queryStackerInfoVos);
    }

    /**
     * 添加堆垛机信息
     * @param addStackerReq 添加的信息
     * @return 添加结果
     */
    @Override
    public AppServeResponse addStacker(AddStackerReq addStackerReq) {
        List<AppStackerInfo> stackerInfos = appStackerInfoService.queryStackerInfoById(addStackerReq.getStackerId());
        if(stackerInfos == null) {
            return AppServeResponseFactory.internalServerError("数据服务异常");
        }
        if(!stackerInfos.isEmpty()) {
            return AppServeResponseFactory.dataRepeat("该堆垛机ID已经存在");
        }
        AppStackerInfo appStackerInfo = new AppStackerInfo();
        AppBeanUtils.copyProperties(addStackerReq, appStackerInfo);
        int insertCount = appStackerInfoService.insert(appStackerInfo);
        if(insertCount == 0) {
            return AppServeResponseFactory.internalServerError("数据服务异常");
        }
        return AppServeResponseFactory.success(String.format("添加成功，添加了 %d 条记录", insertCount));
    }

    /**
     * 更新堆垛机信息
     * @param updateStackerInfoReq 更新的信息
     * @return 更新结果
     */
    @Override
    public AppServeResponse updateStackerInfo(UpdateStackerInfoReq updateStackerInfoReq) {
        List<AppStackerInfo> stackerInfos = appStackerInfoService.queryStackerInfoById(updateStackerInfoReq.getStackerId());
        if(stackerInfos == null) {
            return AppServeResponseFactory.internalServerError("数据服务异常");
        }
        if(stackerInfos.isEmpty()) {
            return AppServeResponseFactory.dataRepeat("该堆垛机ID不存在");
        }
        AppStackerInfo appStackerInfo = new AppStackerInfo();
        AppBeanUtils.copyProperties(updateStackerInfoReq, appStackerInfo);
        int updateCount = appStackerInfoService.update(appStackerInfo);
        if(updateCount == 0) {
            return AppServeResponseFactory.internalServerError("数据服务异常");
        }
        return AppServeResponseFactory.success(String.format("更新成功，更新了 %d 条记录", updateCount));
    }

    /**
     * 根据堆垛机ID查询堆垛机站台
     * @param stackerId 堆垛机ID
     * @return 查询结果
     */
    @Override
    public AppServeDataResponse<List<QueryStackerStandVo>> queryStackerStand(Integer stackerId) {
        List<AppStackerStand> stackerStands = appStackerStandService.queryStackerStand(stackerId);
        if(stackerStands == null) {
            return AppServeResponseFactory.internalServerError("数据服务异常", null);
        }
        List<QueryStackerStandVo> queryStackerStandVos = AppBeanUtils.copyListProperties(stackerStands, QueryStackerStandVo::new);
        return AppServeResponseFactory.success("查询成功", queryStackerStandVos);
    }

    /**
     *  添加或更新堆垛机站台
     * @param addOrUpdateStackerStandReq 新堆垛机站台参数
     * @return  更新结果
     */
    @Override
    public AppServeResponse addOrUpdateStackerStand(AddOrUpdateStackerStandReq addOrUpdateStackerStandReq) {
        List<AppStackerStand> stackerStands = appStackerStandService.queryStandInfo(addOrUpdateStackerStandReq.getStandId());
        if(stackerStands == null) {
            return AppServeResponseFactory.internalServerError("数据服务异常");
        }
        if(stackerStands.isEmpty()) {
            // 不存在站台，新增一个
            AppStackerStand insertStackerStand = new AppStackerStand();
            AppBeanUtils.copyProperties(addOrUpdateStackerStandReq, insertStackerStand);
            int insertCount = appStackerStandService.insert(insertStackerStand);
            if(insertCount == 0) {
                return AppServeResponseFactory.internalServerError("数据服务异常");
            }
            return AppServeResponseFactory.success(String.format("添加成功，添加了 %d 条记录", insertCount));
        }
        // 更新
        AppStackerStand updateStackerStand = new AppStackerStand();
        AppBeanUtils.copyProperties(addOrUpdateStackerStandReq, updateStackerStand);
        int updateCount = appStackerStandService.update(updateStackerStand);
        if(updateCount < 1) {
            return AppServeResponseFactory.internalServerError("数据服务异常");
        }
        return AppServeResponseFactory.success(String.format("更新成功，更新了 %d 条记录", updateCount));
    }

    /**
     * 删除堆垛机站台信息
     * @param standId 站台号
     * @return 删除结果
     */
    @Override
    public AppServeResponse deleteWithStandId(String standId) {
        int deleteResult = appStackerStandService.delete(standId);
        if(deleteResult < 1) {
            return AppServeResponseFactory.internalServerError("数据服务异常");
        }
        return AppServeResponseFactory.success(String.format("删除成功，删除了 %d 条记录", deleteResult));
    }

    /**
     * 获取堆垛机运行信息
     * @return 堆垛机运行信息
     */
    @Override
    public AppServeDataResponse<List<StackerStatusVo>> getStackerRunningInfo() {
        Map<Integer, StackerStatusData> stackerStatusDataMap = stackerStatusMonitor.getStackerStatusDataMap();
        if(stackerStatusDataMap == null) {
            return AppServeResponseFactory.internalServerError("无数据，必须开启堆垛机任务功能才能监控堆垛机状态", null);
        }
        if(stackerStatusDataMap.isEmpty()) {
            return AppServeResponseFactory.fail("必须开启堆垛机任务功能才能监控堆垛机状态", null);
        }
        List<StackerStatusVo> stackerStatusVos = new ArrayList<>();
        for(Map.Entry<Integer, StackerStatusData> entry : stackerStatusDataMap.entrySet()) {
            StackerStatusData stackerStatusData = entry.getValue();
            StackerStatusVo stackerStatusVo = new StackerStatusVo();
            stackerStatusVo.setStackerId(stackerStatusData.getStackerId());
            StackerStatus stackerStatus = stackerStatusData.getStatus();
            if(stackerStatus == null) {
                stackerStatusVo.setDeviceStatus(StackerDeviceStatusEnum.OFF_LINE.getCode());
                stackerStatusVo.setControlModel(StackerControllerModelEnum.OFF_LINE.getCode());
                stackerStatusVo.setErrCode(0);
                stackerStatusVo.setLocation("");
                stackerStatusVo.setVehicleNo("");
                stackerStatusVo.setPlcTaskId(0);
            } else {
                stackerStatusVo.setDeviceStatus(Integer.valueOf(stackerStatus.getDeviceStatus()));
                stackerStatusVo.setControlModel(Integer.valueOf(stackerStatus.getControlModel()));
                stackerStatusVo.setErrCode(Integer.valueOf(stackerStatus.getErrCode()));
                stackerStatusVo.setLocation(stackerStatus.getLLine() + "列" + stackerStatus.getLLayer() + "层");
                stackerStatusVo.setVehicleNo(stackerStatus.getCode1() + "");
                stackerStatusVo.setPlcTaskId(stackerStatus.getPlcTaskId());
            }
            stackerStatusVos.add(stackerStatusVo);
        }
        return AppServeResponseFactory.success("查询成功", stackerStatusVos);
    }
}
