package org.wcs.serve.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.wcs.factory.AppServeResponseFactory;
import org.wcs.mapper.intf.AppConveyLocationService;
import org.wcs.model.bo.tuple.Tuple2;
import org.wcs.model.dto.serve.convey.AddConveyLocationReq;
import org.wcs.model.dto.serve.convey.QueryConveyLocationReq;
import org.wcs.model.dto.serve.convey.UpdateConveyLocationReq;
import org.wcs.model.po.app.AppConveyLocation;
import org.wcs.model.vo.serve.AppServeDataResponse;
import org.wcs.model.vo.serve.AppServeResponse;
import org.wcs.model.vo.serve.common.PageDataResponse;
import org.wcs.model.vo.serve.convey.ConveyStatusVo;
import org.wcs.model.vo.serve.convey.QueryConveyLocationVo;
import org.wcs.plugin.plc.PlcCommunicationFactory;
import org.wcs.plugin.plc.model.TaskConveyStatus;
import org.wcs.serve.service.intf.IConveyLocationService;
import org.wcs.utils.AppBeanUtils;
import org.wcs.utils.AppStringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class ConveyLocationService implements IConveyLocationService {

    private final AppConveyLocationService conveyLocationService;

    /**
     * 查询输送点位
     * @param request 查询参数
     * @param pageSize 每页数量
     * @param pageIndex 页码
     * @return 查询结果
     */
    @Override
    public AppServeDataResponse<PageDataResponse<QueryConveyLocationVo>> queryConveyLocation(QueryConveyLocationReq request, Integer pageSize, Integer pageIndex) {
        if(pageSize == null || pageSize <= 0 || pageIndex == null || pageIndex <= 0) {
            return AppServeResponseFactory.fail("分页参数错误", null);
        }
        Tuple2<Long, List<AppConveyLocation>> queryResult = conveyLocationService.queryConveyLocation(request, pageSize, pageIndex);
        if(queryResult == null) {
            return AppServeResponseFactory.fail("数据服务异常", null);
        }
        PageDataResponse<QueryConveyLocationVo> response = new PageDataResponse<>();
        response.setPageIndex(pageIndex);
        response.setPageSize(pageSize);
        response.setTotalCount(queryResult.getItem1());
        response.setData(AppBeanUtils.copyListProperties(queryResult.getItem2(), QueryConveyLocationVo::new));
        return AppServeResponseFactory.success("查询成功", response);
    }

    /**
     * 添加点位信息
     * @param request 新增参数
     * @return 参数
     */
    @Override
    public AppServeResponse addConveyLocation(AddConveyLocationReq request) {
        Object userIdObj = StpUtil.getLoginId();
        if(userIdObj == null) {
            return AppServeResponseFactory.unauthorized("用户未登录");
        }
        String operationUserId = userIdObj.toString();
        log.info("用户：{} 想要添加箱式输送线点位数据：{}", operationUserId, AppStringUtils.objectToString(request));
        List<AppConveyLocation> conveyLocations = conveyLocationService.queryByLocationId(request.getLocationId());
        if(conveyLocations == null) {
            return AppServeResponseFactory.fail("数据服务异常");
        }
        if(!conveyLocations.isEmpty()) {
            return AppServeResponseFactory.fail("该位置已存在");
        }
        AppConveyLocation insertConveyLocation = new AppConveyLocation();
        insertConveyLocation.setLocationId(request.getLocationId());
        insertConveyLocation.setBusinessLocationId(request.getBusinessLocationId());
        insertConveyLocation.setLocationName(request.getLocationName());
        insertConveyLocation.setLocationStatus(request.getLocationStatus());
        insertConveyLocation.setLocationType(request.getLocationType());
        insertConveyLocation.setPlcId(request.getPlcId());
        insertConveyLocation.setAreaId(request.getAreaId());
        insertConveyLocation.setLocationRouter(request.getLocationRouter());
        insertConveyLocation.setReadStatusAddress(request.getReadStatusAddress());
        insertConveyLocation.setWriteTaskAddress(request.getWriteTaskAddress());
        insertConveyLocation.setRemark(request.getRemark());
        boolean saveResult = conveyLocationService.insertConveyLocation(insertConveyLocation);
        return saveResult ? AppServeResponseFactory.success() : AppServeResponseFactory.fail("数据服务异常");
    }

    /**
     *  更新点位信息
     * @param request 更新的信息
     * @return 更新结果
     */
    @Override
    public AppServeResponse updateConveyLocation(UpdateConveyLocationReq request) {
        Object userIdObj = StpUtil.getLoginId();
        if(userIdObj == null) {
            return AppServeResponseFactory.unauthorized("用户未登录");
        }
        String operationUserId = userIdObj.toString();
        log.info("用户：{} 想要更新箱式输送线点位数据：{}", operationUserId, AppStringUtils.objectToString(request));
        List<AppConveyLocation> conveyLocations = conveyLocationService.queryByLocationId(request.getLocationId());
        if(conveyLocations == null) {
            return AppServeResponseFactory.fail("数据服务异常");
        }
        if(conveyLocations.isEmpty()) {
            return AppServeResponseFactory.fail("该位置不存在");
        }
        AppConveyLocation insertConveyLocation = new AppConveyLocation();
        insertConveyLocation.setLocationId(request.getLocationId());
        insertConveyLocation.setBusinessLocationId(request.getBusinessLocationId());
        insertConveyLocation.setLocationName(request.getLocationName());
        insertConveyLocation.setLocationStatus(request.getLocationStatus());
        insertConveyLocation.setLocationType(request.getLocationType());
        insertConveyLocation.setPlcId(request.getPlcId());
        insertConveyLocation.setAreaId(request.getAreaId());
        insertConveyLocation.setLocationRouter(request.getLocationRouter());
        insertConveyLocation.setReadStatusAddress(request.getReadStatusAddress());
        insertConveyLocation.setWriteTaskAddress(request.getWriteTaskAddress());
        insertConveyLocation.setRemark(request.getRemark());
        boolean updated = conveyLocationService.updateConveyLocationByLocationId(insertConveyLocation);
        return updated ? AppServeResponseFactory.success() : AppServeResponseFactory.fail("数据服务异常");
    }

    /**
     * 查询输送点位状态
     * @param conveyId 输送点位ID
     * @return 结果
     */
    @Override
    public AppServeDataResponse<ConveyStatusVo> queryTrayConveyStatus(String conveyId) {
        List<AppConveyLocation> conveyLocations = conveyLocationService.queryByLocationId(conveyId);
        if(conveyLocations == null || conveyLocations.isEmpty()) {
            return AppServeResponseFactory.fail("数据服务异常或者点位不存在", null);
        }
        AppConveyLocation conveyLocation = conveyLocations.getFirst();
        Tuple2<String, TaskConveyStatus> taskConveyStatusTuple2 = PlcCommunicationFactory.getPlcCommunicationByPlcId(conveyLocation.getPlcId()).readTaskConveyStatus(conveyId);
        if(AppStringUtils.isNotEmpty(taskConveyStatusTuple2.item1)) {
            return AppServeResponseFactory.fail(taskConveyStatusTuple2.item1, null);
        }
        if(taskConveyStatusTuple2.item2 == null) {
            return AppServeResponseFactory.fail("查询失败", null);
        }
        ConveyStatusVo conveyStatusVo = new ConveyStatusVo();
        AppBeanUtils.copyProperties(taskConveyStatusTuple2.item2, conveyStatusVo);
        return AppServeResponseFactory.success("查询成功", conveyStatusVo);
    }
}
