package com.ygtx.web.service.impl;

import com.ygtx.common.core.domain.ice.IcePendingTaskRequest;
import com.ygtx.common.core.domain.ice.IcePendingTaskResponse;
import com.ygtx.common.core.domain.ice.IcePendingTaskStatusRequest;
import com.ygtx.common.utils.ice.IcePendingTaskWebServiceUtil;
import com.ygtx.common.utils.StringUtils;
import com.ygtx.web.service.IcePendingTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * ICE待办任务服务实现
 *
 * @author ygt
 */
@Service
public class IcePendingTaskServiceImpl implements IcePendingTaskService
{
    private static final Logger log = LoggerFactory.getLogger(IcePendingTaskServiceImpl.class);

    @Autowired
    private IcePendingTaskWebServiceUtil icePendingTaskWebServiceUtil;

    /**
     * 推送待办消息到ICE
     *
     * @param request 待办消息请求对象
     * @return 响应结果
     */
    @Override
    public IcePendingTaskResponse sendPendingTask(IcePendingTaskRequest request)
    {
        log.info("开始推送待办消息到ICE，标题：{}，用户工号：{}", request.getTitle(), request.getCode());
        
        try
        {
            // 验证必要参数
            validatePendingTaskRequest(request);
            
            // 调用Web Service进行推送
            IcePendingTaskResponse response = icePendingTaskWebServiceUtil.sendPendingTask(request);
            
            if (response.getSuccess())
            {
                log.info("成功推送待办消息到ICE，标题：{}，用户工号：{}，任务ID：{}", 
                        request.getTitle(), request.getCode(), request.getTaskId());
            }
            else
            {
                log.error("推送待办消息到ICE失败，标题：{}，用户工号：{}，错误信息：{}", 
                        request.getTitle(), request.getCode(), response.getMsg());
            }
            
            return response;
        }
        catch (Exception e)
        {
            log.error("推送待办消息到ICE异常，标题：{}，用户工号：{}", request.getTitle(), request.getCode(), e);
            // 返回错误响应
            IcePendingTaskResponse errorResponse = new IcePendingTaskResponse();
            errorResponse.setRet(-1);
            errorResponse.setMsg(e.getMessage());
            errorResponse.setSuccess(false);
            return errorResponse;
        }
    }

    /**
     * 批量推送待办消息到ICE
     *
     * @param requestList 待办消息请求对象列表
     * @return 成功推送的数量
     */
    @Override
    public int batchSendPendingTask(List<IcePendingTaskRequest> requestList)
    {
        if (requestList == null || requestList.isEmpty())
        {
            log.warn("批量推送待办消息列表为空");
            return 0;
        }
        
        log.info("开始批量推送待办消息到ICE，总数：{}", requestList.size());
        
        int successCount = 0;
        for (int i = 0; i < requestList.size(); i++)
        {
            IcePendingTaskRequest request = requestList.get(i);
            try
            {
                IcePendingTaskResponse response = sendPendingTask(request);
                if (response.getSuccess())
                {
                    successCount++;
                }
                else
                {
                    log.error("第{}个待办消息推送失败：{}", i + 1, response.getMsg());
                }
            }
            catch (Exception e)
            {
                log.error("第{}个待办消息推送异常：{}", i + 1, e.getMessage());
            }
        }
        
        log.info("批量推送待办消息完成，成功：{}，失败：{}", successCount, requestList.size() - successCount);
        return successCount;
    }

    /**
     * 更新待办任务状态
     *
     * @param request 状态变更请求对象
     * @return 响应结果
     */
    @Override
    public IcePendingTaskResponse updatePendingTaskStatus(IcePendingTaskStatusRequest request)
    {
        log.info("开始更新待办任务状态，任务ID：{}，系统ID：{}，目标状态：{}", 
                request.getTaskId(), request.getSystemId(), request.getIsCompleted());
        
        try
        {
            // 验证必要参数
            validatePendingTaskStatusRequest(request);
            
            // 调用Web Service更新状态
            IcePendingTaskResponse response = icePendingTaskWebServiceUtil.updatePendingTaskStatus(request);
            
            if (response.getSuccess())
            {
                log.info("成功更新待办任务状态，任务ID：{}，系统ID：{}，新状态：{}", 
                        request.getTaskId(), request.getSystemId(), request.getIsCompleted());
            }
            else
            {
                log.error("更新待办任务状态失败，任务ID：{}，系统ID：{}，错误信息：{}", 
                        request.getTaskId(), request.getSystemId(), response.getMsg());
            }
            
            return response;
        }
        catch (Exception e)
        {
            log.error("更新待办任务状态异常，任务ID：{}，系统ID：{}", request.getTaskId(), request.getSystemId(), e);
            // 返回错误响应
            IcePendingTaskResponse errorResponse = new IcePendingTaskResponse();
            errorResponse.setRet(-1);
            errorResponse.setMsg(e.getMessage());
            errorResponse.setSuccess(false);
            return errorResponse;
        }
    }

    /**
     * 根据任务ID取消待办任务
     *
     * @param taskId 任务ID
     * @param systemId 系统ID
     * @return 响应结果
     */
    @Override
    public IcePendingTaskResponse cancelPendingTask(String taskId, String systemId)
    {
        log.info("开始取消待办任务，任务ID：{}，系统ID：{}", taskId, systemId);
        
        if (StringUtils.isEmpty(taskId))
        {
            log.error("任务ID不能为空");
            IcePendingTaskResponse errorResponse = new IcePendingTaskResponse();
            errorResponse.setRet(-1);
            errorResponse.setMsg("任务ID不能为空");
            errorResponse.setSuccess(false);
            return errorResponse;
        }
        
        // 创建状态变更请求，设置为已办状态（2）
        IcePendingTaskStatusRequest request = new IcePendingTaskStatusRequest();
        request.setTaskId(taskId);
        request.setIsCompleted("2"); // 已办状态
        request.setSystemId(systemId);
        
        return updatePendingTaskStatus(request);
    }

    /**
     * 验证待办任务请求参数
     *
     * @param request 请求对象
     */
    private void validatePendingTaskRequest(IcePendingTaskRequest request)
    {
        if (request == null)
        {
            throw new IllegalArgumentException("待办任务请求对象不能为空");
        }

        if (StringUtils.isEmpty(request.getTitle()))
        {
            throw new IllegalArgumentException("待办任务标题不能为空");
        }

        if (StringUtils.isEmpty(request.getCode()))
        {
            throw new IllegalArgumentException("用户工号不能为空");
        }

        if (request.getType() == null)
        {
            throw new IllegalArgumentException("任务类型不能为空，应为2");
        }

        if (request.getType() != 2)
        {
            log.warn("任务类型建议为2，当前值：{}", request.getType());
        }

        if (StringUtils.isEmpty(request.getUrl()))
        {
            throw new IllegalArgumentException("跳转URL不能为空");
        }
    }

    /**
     * 验证待办任务状态变更请求参数
     *
     * @param request 请求对象
     */
    private void validatePendingTaskStatusRequest(IcePendingTaskStatusRequest request)
    {
        if (request == null)
        {
            throw new IllegalArgumentException("待办任务状态变更请求对象不能为空");
        }

        if (StringUtils.isEmpty(request.getTaskId()))
        {
            throw new IllegalArgumentException("任务ID不能为空");
        }

        if (StringUtils.isEmpty(request.getIsCompleted()))
        {
            throw new IllegalArgumentException("完成状态不能为空，应为1（待办）或2（已办）");
        }

        if (!"1".equals(request.getIsCompleted()) && !"2".equals(request.getIsCompleted()))
        {
            throw new IllegalArgumentException("完成状态应为1（待办）或2（已办）");
        }

        if (StringUtils.isEmpty(request.getSystemId()))
        {
            throw new IllegalArgumentException("系统ID不能为空");
        }
    }
}