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.devchange.domain.CsDeviceInfo;
import com.bonus.material.devchange.mapper.DevChangeMapper;
import com.bonus.material.repair.domain.ToBeRepair;
import com.bonus.material.repair.mapper.RepairMapper;
import com.bonus.material.repair.service.RepairService;
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_REPAIR")
public class EquipmentRepairCallback implements IApprovalCallback {

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

    @Resource
    private RepairService repairService;

    @Resource
    private RepairMapper repairMapper;

    @Resource
    private DevChangeMapper devChangeMapper;

    /**
     * 审批通过回调
     * 执行维修业务逻辑：更新台账、添加周期表等
     */
    @Override
    public void onApproved(ApprovalInstance instance) {
        try {
            log.info("设备维修审批通过，开始执行维修业务逻辑，业务ID：{}", instance.getBusinessId());
            
            // 1. 从审批实例中获取业务数据
            String businessData = instance.getBusinessData();
            ToBeRepair bean = JSON.parseObject(businessData, ToBeRepair.class);
            
            // 2. 设置任务ID（从businessId获取）
            bean.setChangeId(Long.valueOf(instance.getBusinessId()));
            
            // 3. 从数据库查询维修明细列表（包含ID）
            ToBeRepair queryBean = new ToBeRepair();
            queryBean.setId(bean.getChangeId());
            List<ToBeRepair> detailsList = repairMapper.getRepairDetailsList(queryBean);
            
            if (detailsList == null || detailsList.isEmpty()) {
                log.error("设备维修审批通过，但未找到维修明细，业务ID：{}", instance.getBusinessId());
                throw new RuntimeException("未找到维修明细");
            }
            
            // 4. 将所有明细的审批状态设置为"通过"
            for (ToBeRepair detail : detailsList) {
                detail.setAuditStatus("2");  // 2-通过
            }
            bean.setToBeRepairList(detailsList);
            
            // 5. 调用原有的审批业务逻辑
            AjaxResult result = repairService.auditData(bean);
            
            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());
        }
    }
}

