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.HttpUtils;
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.AgvDTO;
import com.zg.project.wisdom.domain.dto.OutGoodsDTO;
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.IAgvTaskResultService;
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.Date;
import java.util.List;
import java.util.Objects;

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

@Service
public class AgvTaskResultServiceImpl implements IAgvTaskResultService {

    @Autowired
    private AgvTaskResultMapper agvTaskResultMapper;

    @Autowired
    private WcsTaskResultMapper wcsTaskResultMapper;

    @Autowired
    private DdTaskMapper ddTaskMapper;

    @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("${mock.agv-job-create-url}")
//    private String agvJobCreateUrl;
//
//    @Value("${mock.wcs-job-create-url}")
//    private String wcsJobCreateUrl;


    @Override
    public AgvTaskResult selectAgvTaskResultById(Long id) {
        return agvTaskResultMapper.selectAgvTaskResultById(id);
    }

    @Override
    public List<AgvTaskResult> selectAgvTaskResultList(AgvTaskResult agvTaskResult) {
        return agvTaskResultMapper.selectAgvTaskResultList(agvTaskResult);
    }

    @Override
    public int insertAgvTaskResult(AgvTaskResult agvTaskResult) {
        agvTaskResult.setCreateBy(SecurityUtils.getUserId().toString());
        return agvTaskResultMapper.insertAgvTaskResult(agvTaskResult);
    }

    @Override
    public int updateAgvTaskResult(AgvTaskResult agvTaskResult) {
        agvTaskResult.setUpdateBy(SecurityUtils.getUserId().toString());
        return agvTaskResultMapper.updateAgvTaskResult(agvTaskResult);
    }

    @Override
    public int deleteAgvTaskResultById(Long id) {
        return agvTaskResultMapper.deleteAgvTaskResultById(id);
    }

    @Override
    public int deleteAgvTaskResultByIds(Long[] ids) {
        return agvTaskResultMapper.deleteAgvTaskResultByIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleAgvCallback(AgvDTO dto) {
        String requestId = dto.getRequestId();
        if (StringUtils.isBlank(requestId)) {
            throw new ServiceException("requestId不能为空");
        }

        // 截取 taskNo（去除 -AGV 等后缀）
        String taskNo = requestId.substring(0, requestId.length() - 2);

        // 写入 AGV 回调状态记录（每个状态都一条，不覆盖）
        AgvTaskResult result = new AgvTaskResult();
        result.setRequestId(requestId);
        result.setTaskNo(taskNo);
        result.setJobId(dto.getJobId());
        result.setOwner(dto.getOwner());
        result.setType(dto.getType());
        result.setPriority(dto.getPriority());
        result.setSourceName(dto.getSourceName());
        result.setTargetName(dto.getTargetName());
        result.setStatus(dto.getStatus());
        result.setMsg(dto.getMsg());
        result.setCreateBy("agv");
        result.setCreateTime(DateUtils.getNowDate());
        result.setUpdateTime(DateUtils.getNowDate());
        result.setIsDelete("0");

        agvTaskResultMapper.insertAgvTaskResult(result);

        // 如果状态为 TAKE_DOWN_COMPLETED，则将 dd_task 中状态置为 2（已完成）
        if ("TAKE_DOWN_COMPLETED".equalsIgnoreCase(dto.getStatus())) {
            ddTaskMapper.updateTaskStatusByTaskNo(taskNo, 2);
        }

    }

    /**
     * 货物上架
     * @param
     */
    @Override
    public String handleUpGoods(String taskNo, Integer materialStatus) {
        Date now = DateUtils.getNowDate();

        // 1. 查询调度任务
        DdTask ddTask = ddTaskMapper.selectByTaskNo(taskNo);
        if (ddTask == null) {
            throw new ServiceException("未找到调度任务，taskNo = " + taskNo);
        }

        // 2. 构造 WCS 请求参数
        String taskId = taskNo + "21"; // 上架任务编号（WCS）

        JSONObject wcsParam = new JSONObject();
        wcsParam.put("TaskID", taskId);
        wcsParam.put("TrayNo", "");
        wcsParam.put("Materialstatus", materialStatus);

        if (materialStatus != null && materialStatus == 1) {
            String materialCode = ddTask.getMid();
            String specification = mtdMapper.selectWlmsByWlbh(materialCode);
            wcsParam.put("MaterialCode", materialCode);
            wcsParam.put("Specification", specification != null ? specification : "");
            wcsParam.put("Quantity", ddTask.getNum() != null ? ddTask.getNum() : "");
        } else {
            wcsParam.put("MaterialCode", "");
            wcsParam.put("Specification", "");
            wcsParam.put("Quantity", "");
        }

        wcsParam.put("Mlocation", ddTask.getTargetName());
        wcsParam.put("Tlocation", ddTask.getSourceName());

        log.info("[上架] 调用 WCS 接口参数: {}", wcsParam.toJSONString());

        // 3. 发起调用
        String wcsResp = OkHttpUtils.postJson(wcsJobCreateUrl, wcsParam.toJSONString());

        if (StringUtils.isBlank(wcsResp)) {
            throw new ServiceException("WCS 接口无响应");
        }

        JSONObject json = JSON.parseObject(wcsResp);

        if (!json.containsKey("result")) {
            throw new ServiceException("WCS 返回格式异常：" + wcsResp);
        }

        String result = json.getString("result");
        if (!"success".equalsIgnoreCase(result)) {
            throw new ServiceException("WCS 上架失败：" + json.getString("errorMessage"));
        }

        // 4. 插入执行记录
        WcsTaskResult wcs = new WcsTaskResult();
        wcs.setTaskId(taskId);
        wcs.setTaskStatus("0"); // 成功
        wcs.setMsg(json.getString("errorMessage"));
        wcs.setOwner("wms");
        wcs.setType("1");
        wcs.setPriority("1");
        wcs.setSourceName(ddTask.getSourceName());
        wcs.setTargetName(ddTask.getTargetName());
        wcs.setIsDelete("0");
        wcs.setCreateTime(now);
        wcs.setUpdateTime(now);
        wcsTaskResultMapper.insertWcsTaskResult(wcs);

        log.info("[上架] 执行成功，任务 {} 状态已更新为已完成", taskNo);

        // ✅ 返回 taskId
        return taskId;
    }

    /**
     * 货物下架
     * @param
     */
    @Override
    public void handleOutGoods(OutGoodsDTO dto) {
        String taskNo = dto.getTaskNo();
        Integer materialStatus = dto.getMaterialStatus(); // ✅ 关键判断字段
        String userId = SecurityUtils.getUserId().toString();
        Date now = DateUtils.getNowDate();

        // 1. 查询 AGV 原任务记录
        AgvTaskResult task = agvTaskResultMapper.selectByTaskNo(taskNo);
        if (task == null) {
            throw new ServiceException("未找到任务：" + taskNo);
        }

        // 2. 调用 WCS 下架接口
        String wcsTaskId = taskNo + "22";
        JSONObject wcsParam = new JSONObject();
        wcsParam.put("TaskID", wcsTaskId);
        wcsParam.put("TrayNo", "");
        wcsParam.put("Materialstatus", materialStatus);

        if (Objects.equals(materialStatus, 1)) {
            wcsParam.put("MaterialCode", task.getMid());
            wcsParam.put("Quantity", task.getNum());
            String spec = mtdMapper.selectWlmsByWlbh(task.getMid());
            wcsParam.put("Specification", spec != null ? spec : "");
        } else {
            wcsParam.put("MaterialCode", "");
            wcsParam.put("Quantity", "");
            wcsParam.put("Specification", "");
        }

        wcsParam.put("Mlocation", task.getSourceName()); // 来源库位
        wcsParam.put("Tlocation", task.getTargetName()); // 目标库位
        wcsParam.put("outBack", 1); // 固定值

        log.info("[下架] 调用 WCS 接口: {}", wcsParam.toJSONString());
        String wcsResp = HttpUtils.sendPost(wcsJobCreateUrl, wcsParam.toJSONString());
        if (StringUtils.isBlank(wcsResp)) {
            throw new ServiceException("WCS接口无响应");
        }

        JSONObject wcsJson = JSON.parseObject(wcsResp);
        if (!Objects.equals(wcsJson.getInteger("code"), 0)) {
            throw new ServiceException("WCS下架失败：" + wcsJson.getString("msg"));
        }

        // 3. 记录 WCS 任务
        WcsTaskResult wcs = new WcsTaskResult();
        wcs.setTaskId(wcsTaskId);
        wcs.setTaskStatus("3"); // 等待下架
        wcs.setMsg(wcsJson.getString("msg"));
        wcs.setOwner("wms");
        wcs.setType("2");
        wcs.setPriority("1");
        wcs.setSourceName(task.getSourceName());
        wcs.setTargetName(task.getTargetName());
        wcs.setIsDelete("0");
        wcs.setCreateBy(userId);
        wcs.setCreateTime(now);
        wcs.setUpdateTime(now);
        wcsTaskResultMapper.insertWcsTaskResult(wcs);

        // 4. 调用 AGV 出库搬运（下架点 → 出口）
        String agvRequestId = taskNo + "12";
        JSONObject agvParam = new JSONObject();
        agvParam.put("requestId", agvRequestId);
        agvParam.put("taskNo", taskNo);
        agvParam.put("owner", "wms");
        agvParam.put("type", 2); // 下架搬运
        agvParam.put("priority", "1");
        agvParam.put("sourceName", task.getTargetName());
        agvParam.put("targetName", "出口口A");

        log.info("[下架] 调用 AGV 接口: {}", agvParam.toJSONString());
        String agvResp = HttpUtils.sendPost(agvJobCreateUrl, agvParam.toJSONString());
        if (StringUtils.isBlank(agvResp)) {
            throw new ServiceException("AGV接口无响应");
        }

        JSONObject agvJson = JSON.parseObject(agvResp);
        if (!Objects.equals(agvJson.getInteger("code"), 0)) {
            throw new ServiceException("AGV搬运失败：" + agvJson.getString("msg"));
        }

        // 5. 保存 AGV 出库搬运记录
        AgvTaskResult agv = new AgvTaskResult();
        agv.setRequestId(agvRequestId);
        agv.setStatus("CREATED");
        agv.setMsg(agvJson.getString("msg"));
        agv.setOwner("wms");
        agv.setType("2");
        agv.setPriority("1");
        agv.setTaskNo(taskNo);
        agv.setSourceName(task.getTargetName());
        agv.setTargetName("出口口A");
        agv.setIsDelete("0");
        agv.setCreateBy(userId);
        agv.setCreateTime(now);
        agv.setUpdateTime(now);
        agvTaskResultMapper.insertAgvTaskResult(agv);

        // 6. 保存 AGV/WCS 对应关系
        AgyWcs mapping = new AgyWcs();
        mapping.setRequestId(agvRequestId);
        mapping.setTaskId(wcsTaskId);
        agyWcsMapper.insertAgvWcs(mapping);

        log.info("[下架] AGV 搬运任务提交成功");
    }


    @Override
    public boolean existsByRequestIdAndStatus(String requestId, String status) {
        return agvTaskResultMapper.countByRequestIdAndStatus(requestId, status) > 0;
    }

}
