package com.zg.project.wisdom.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zg.common.exception.ServiceException;
import com.zg.common.utils.DateUtils;
import com.zg.common.utils.SecurityUtils;
import com.zg.common.utils.StringUtils;
import com.zg.common.utils.http.OkHttpUtils;
import com.zg.project.information.mapper.MtdMapper;
import com.zg.project.wisdom.domain.AgvTaskResult;
import com.zg.project.wisdom.domain.AgyWcs;
import com.zg.project.wisdom.domain.DdTask;
import com.zg.project.wisdom.domain.WcsTaskResult;
import com.zg.project.wisdom.domain.dto.TaskExecuteDTO;
import com.zg.project.wisdom.domain.vo.TaskExecuteResultVO;
import com.zg.project.wisdom.mapper.AgvTaskResultMapper;
import com.zg.project.wisdom.mapper.AgvWcsMapper;
import com.zg.project.wisdom.mapper.DdTaskMapper;
import com.zg.project.wisdom.mapper.WcsTaskResultMapper;
import com.zg.project.wisdom.service.IDdTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.zg.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 * 调度任务 Service 实现类
 *
 * @author zg
 */
@Service
public class DdTaskServiceImpl implements IDdTaskService {

    @Autowired
    private DdTaskMapper ddTaskMapper;

    @Autowired
    private WcsTaskResultMapper wcsTaskResultMapper;

    @Autowired
    private AgvTaskResultMapper agvTaskResultMapper;

    @Autowired
    private MtdMapper mtdMapper;

    @Autowired
    private AgvWcsMapper agyWcsMapper;
//
    @Value("${agv.job.create-url}")
    private String agvJobCreateUrl;

    @Value("${wcs.job.create-url}")
    private String wcsJobCreateUrl;

    @Value("${wcs.job.chuku-url}")
    private String wcsJobChukuUrl;

//    @Value("${mock.agv-job-create-url}")
//    private String agvJobCreateUrl;
//
//    @Value("${mock.wcs-job-create-url}")
//    private String wcsJobCreateUrl;

    @Override
    public List<DdTask> selectDdTaskList(DdTask ddTask) {
        return ddTaskMapper.selectDdTaskList(ddTask);
    }

    @Override
    public DdTask selectDdTaskById(Long id) {
        return ddTaskMapper.selectDdTaskById(id);
    }

    @Override
    public int insertDdTask(DdTask ddTask) {
        // 1. 生成任务编号（如 DD20250701143059001）
        String taskNo = "DD" + DateUtils.dateTimeNow("yyyyMMddHHmmssSSS");
        ddTask.setTaskNo(taskNo);

        // 2. 判断 mid 是否为空，设置 midStatus（0空托盘，1有货）
        if (ddTask.getMid() == null || ddTask.getMid().trim().isEmpty()) {
            ddTask.setMidStatus(0);
        } else {
            ddTask.setMidStatus(1);
        }

        // 3. 设置任务初始状态为待建（0）
        ddTask.setTaskStatus(0);

        // 4. 设置操作员和审核员（从当前登录用户上下文中获取）
        Long userId = SecurityUtils.getUserId();
        ddTask.setOperator(userId.toString());
        ddTask.setApprover(userId.toString());

        // 5. 设置接收时间 rcptim 和初始化字段
        ddTask.setRcptim(DateUtils.getNowDate());
        ddTask.setRid("");
        ddTask.setDoCount(0);

        // 6. 设置通用字段
        ddTask.setCreateBy(userId.toString());
        ddTask.setCreateTime(DateUtils.getNowDate());
        ddTask.setUpdateBy(userId.toString());
        ddTask.setUpdateTime(DateUtils.getNowDate());
        ddTask.setIsDelete("0");

        return ddTaskMapper.insertDdTask(ddTask);
    }

    @Override
    public int updateDdTask(DdTask ddTask) {
        return ddTaskMapper.updateDdTask(ddTask);
    }

    @Override
    public int deleteDdTaskByIds(Long[] ids) {
        return ddTaskMapper.deleteDdTaskByIds(ids);
    }

    @Override
    public int deleteDdTaskById(Long id) {
        return ddTaskMapper.deleteDdTaskById(id);
    }

    /**
     * 执行任务
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public TaskExecuteResultVO executeTask(TaskExecuteDTO dto) {
        Long id = dto.getId();
        String targetName = dto.getTargetName();
        Integer materialStatus = dto.getMaterialStatus();

        if (StringUtils.isBlank(targetName)) {
            throw new ServiceException("targetName 不能为空");
        }

        DdTask task = ddTaskMapper.selectDdTaskById(id);
        if (task == null) {
            throw new ServiceException("任务不存在，ID = " + id);
        }
        if (!Objects.equals(task.getTaskStatus(), 0)) {
            throw new ServiceException("任务状态不是待执行，当前状态为：" + task.getTaskStatus());
        }

        String taskNo = task.getTaskNo();
        String taskType = task.getTaskType();
        String requestId = null;
        String taskIdParam = null;
        String response;
        String msg;
        int code = 200;
        String userId = SecurityUtils.getUserId().toString();
        Date now = DateUtils.getNowDate();

        if ("1".equals(taskType)) {
            // 出库任务：先调 WCS
            taskIdParam = taskNo + "22";
            JSONObject wcsParam = new JSONObject();
            wcsParam.put("TaskID", taskIdParam);
            wcsParam.put("TaskType", 1);
            wcsParam.put("Mlocation", task.getSourceName());
            wcsParam.put("TrayNo", "");
            wcsParam.put("Materialstatus", materialStatus);
            wcsParam.put("outBack", 1);

            if (materialStatus == 0) {
                wcsParam.put("MaterialCode", "");
                wcsParam.put("Specification", "");
                wcsParam.put("Quantity", "");
            } else {
                String materialCode = task.getMid();
//                String quantity = task.getNum().toString();
                String specification = mtdMapper.selectWlmsByWlbh(materialCode);
                wcsParam.put("MaterialCode", materialCode);
//                wcsParam.put("Quantity", quantity);
                wcsParam.put("Specification", specification == null ? "" : specification);
            }

            log.info("[任务执行] 出库 → 调用WCS，taskId={}, param={}", taskIdParam, wcsParam);
            response = OkHttpUtils.postJson(wcsJobChukuUrl, wcsParam.toJSONString());

            if (StringUtils.isBlank(response)) {
                throw new ServiceException("WCS 无响应或返回为空");
            }

            JSONObject respJson;
            try {
                respJson = JSON.parseObject(response);
                String result = respJson.getString("result");
                msg = respJson.getString("errorMessage");
                if (!"success".equalsIgnoreCase(result)) {
                    throw new ServiceException("WCS任务执行失败: " + msg);
                }
            } catch (Exception e) {
                throw new ServiceException("WCS响应解析失败: " + response);
            }

            WcsTaskResult wcs = new WcsTaskResult();
            wcs.setTaskId(taskIdParam);
            wcs.setTaskStatus("1");
            wcs.setMsg(msg);
            wcs.setOwner("wms");
            wcs.setType(taskType);
            wcs.setPriority("1");
            wcs.setSourceName(task.getSourceName());
            wcs.setTargetName(targetName);
            wcs.setIsDelete("0");
            wcs.setCreateBy(userId);
            wcs.setCreateTime(now);
            wcs.setUpdateTime(now);
            wcsTaskResultMapper.insertWcsTaskResult(wcs);

            // 调用 AGV（使用 OkHttpUtils）
            requestId = taskNo + "12";
            JSONObject agvParam = new JSONObject();
            agvParam.put("owner", "wms");
            agvParam.put("type", "1");
            agvParam.put("priority", 1);
            agvParam.put("sourceName", "v01-010101");
            agvParam.put("targetName", targetName);
            agvParam.put("taskNo", taskNo);
            agvParam.put("requestId", requestId);

            log.info("[任务执行] 出库 → 调用AGV，requestId={}, param={}", requestId, agvParam);
            response = OkHttpUtils.postJson(agvJobCreateUrl, agvParam.toJSONString());

            try {
                respJson = JSON.parseObject(response);
                code = respJson.getInteger("code");
                msg = respJson.getString("msg");
            } catch (Exception e) {
                throw new ServiceException("AGV响应解析失败: " + response);
            }

            if (code != 200) {
                throw new ServiceException("AGV任务执行失败: " + msg);
            }

            AgvTaskResult agv = new AgvTaskResult();
            agv.setRequestId(requestId);
            agv.setTaskNo(taskNo);
            agv.setStatus("CREATED");
            agv.setMsg(msg);
            agv.setOwner("wms");
            agv.setType(taskType);
            agv.setPriority("1");
            agv.setSourceName(task.getSourceName());
            agv.setTargetName(targetName);
            agv.setIsDelete("0");
            agv.setCreateBy(userId);
            agv.setCreateTime(now);
            agv.setUpdateTime(now);
            agvTaskResultMapper.insertAgvTaskResult(agv);

            AgyWcs mapping = new AgyWcs();
            mapping.setRequestId(requestId);
            mapping.setTaskId(taskIdParam);
            agyWcsMapper.insertAgvWcs(mapping);

        } else {
            // 入库/移库任务 → 调用 AGV（使用 OkHttpUtils）
            requestId = taskNo + ("0".equals(taskType) ? "11" : "12");
            JSONObject param = new JSONObject();
            param.put("owner", "wms");
            param.put("type", taskType);
            param.put("priority", 1);
            param.put("sourceName", task.getSourceName());
            param.put("targetName", targetName);
            param.put("taskNo", taskNo);
            param.put("requestId", requestId);

            log.info("[任务执行] 类型={}（AGV），requestId={}, param={}", taskType, requestId, param);
            response = OkHttpUtils.postJson(agvJobCreateUrl, param.toJSONString());

            JSONObject respJson;
            try {
                respJson = JSON.parseObject(response);
                code = respJson.getInteger("code");
                msg = respJson.getString("msg");
            } catch (Exception e) {
                throw new ServiceException("AGV响应解析失败: " + response);
            }

            if (code != 200) {
                throw new ServiceException("任务执行失败: " + msg);
            }

            AgvTaskResult agv = new AgvTaskResult();
            agv.setRequestId(requestId);
            agv.setTaskNo(taskNo);
            agv.setStatus("CREATED");
            agv.setMsg(msg);
            agv.setOwner("wms");
            agv.setType(taskType);
            agv.setPriority("1");
            agv.setSourceName(task.getSourceName());
            agv.setTargetName(targetName);
            agv.setIsDelete("0");
            agv.setCreateBy(userId);
            agv.setCreateTime(now);
            agv.setUpdateTime(now);
            agvTaskResultMapper.insertAgvTaskResult(agv);
        }

        task.setTaskStatus(1);
        task.setDoCount(Optional.ofNullable(task.getDoCount()).orElse(0) + 1);
        task.setUpdateBy(userId);
        task.setUpdateTime(now);
        ddTaskMapper.updateDdTask(task);

        TaskExecuteResultVO vo = new TaskExecuteResultVO();
        vo.setRequestId(requestId);
        vo.setCode(code);
        vo.setMsg(msg);
        return vo;
    }

    }
