package com.bonus.material.approval.strategy.impl;

import com.alibaba.fastjson2.JSON;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.material.approval.domain.ApprovalInstance;
import com.bonus.material.approval.strategy.IApprovalCallback;
import com.bonus.material.back.domain.BackCsDeviceDetails;
import com.bonus.material.back.domain.BackCsDeviceVo;
import com.bonus.material.back.mapper.BackChangeMapper;
import com.bonus.material.back.service.BackChangeService;
import com.bonus.material.devchange.domain.CsDeviceInfo;
import com.bonus.material.devchange.mapper.DevChangeMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 设备退库审批回调
 * 
 * @author syruan
 */
@Component("EQUIPMENT_RETURN")
public class EquipmentReturnCallback implements IApprovalCallback {

    private static final Logger log = LoggerFactory.getLogger(EquipmentReturnCallback.class);

    @Resource
    private BackChangeService backChangeService;

    @Resource
    private BackChangeMapper backChangeMapper;

    @Resource
    private DevChangeMapper devChangeMapper;

    /**
     * 审批通过回调
     * 执行退库业务逻辑：更新台账、修改库存等
     */
    @Override
    public void onApproved(ApprovalInstance instance) {
        try {
            log.info("设备退库审批通过，开始执行退库业务逻辑，业务ID：{}", instance.getBusinessId());
            
            // 1. 从审批实例中获取业务数据
            String businessData = instance.getBusinessData();
            BackCsDeviceVo bean = JSON.parseObject(businessData, BackCsDeviceVo.class);
            
            // 2. 设置任务ID（从businessId获取）
            Long changeId = Long.valueOf(instance.getBusinessId());

            // 3. 从数据库查询退库明细列表（包含ID）
            // 注意：BackChangeMapper.getDevDetailsById 使用的是 #{id} 参数，不是 #{changeId}
            BackCsDeviceDetails queryBean = new BackCsDeviceDetails();
            queryBean.setId(changeId);  // 设置id字段，而不是changeId
            List<BackCsDeviceDetails> detailsList = backChangeMapper.getDevDetailsById(queryBean);
            
            if (detailsList == null || detailsList.isEmpty()) {
                log.error("设备退库审批通过，但未找到退库明细，业务ID：{}", instance.getBusinessId());
                throw new RuntimeException("未找到退库明细");
            }
            
            // 4. 构造审批参数
            BackCsDeviceDetails approveParam = new BackCsDeviceDetails();
            approveParam.setChangeId(changeId);
            approveParam.setId(changeId);
            approveParam.setTaskStatus("2");  // 2-通过
            
            // 5. 调用原有的审批业务逻辑
            AjaxResult result = backChangeService.approve(approveParam);
            
            if (result.get("code").equals(200)) {
                log.info("设备退库审批通过，业务逻辑执行成功，业务ID：{}", instance.getBusinessId());
            } else {
                log.error("设备退库审批通过，但业务逻辑执行失败，业务ID：{}，错误信息：{}", instance.getBusinessId(), result.get("msg"));
                throw new RuntimeException("退库业务逻辑执行失败：" + result.get("msg"));
            }
            
        } catch (Exception e) {
            log.error("设备退库审批通过回调执行失败，业务ID：{}", instance.getBusinessId(), e);
            throw new RuntimeException("审批通过回调执行失败：" + e.getMessage());
        }
    }

    /**
     * 审批驳回回调
     * 更新任务状态为"已驳回"
     */
    @Override
    public void onRejected(ApprovalInstance instance) {
        try {
            log.info("设备报废审批驳回，开始执行报废业务驳回逻辑，业务ID：{}", instance.getBusinessId());

            // 1. 设置任务ID（从businessId获取）及驳回值
            CsDeviceInfo csDeviceInfo = new CsDeviceInfo();
            csDeviceInfo.setId(Long.valueOf(instance.getBusinessId()));
            csDeviceInfo.setTaskStatus("3");  // 3-驳回
            csDeviceInfo.setUpdateBy(String.valueOf(instance.getApplyUserId()));

            // 2. 调用原有的审批业务逻辑
            int rejectCount = devChangeMapper.approve(csDeviceInfo);

            if (rejectCount > 0) {
                log.info("设备报废审批驳回，业务逻辑执行成功，业务ID：{}", instance.getBusinessId());
            } else {
                log.error("设备报废审批驳回，但业务逻辑执行失败，业务ID：{}", instance.getBusinessId());
            }

        } catch (Exception e) {
            log.error("设备退库审批驳回回调执行失败，业务ID：{}", instance.getBusinessId(), e);
            throw new RuntimeException("审批驳回回调执行失败：" + e.getMessage());
        }
    }
}

