package com.ruoyi.approvalFlow.service.impl;

import com.ruoyi.approvalFlow.domain.AuditItems;
import com.ruoyi.approvalFlow.mapper.AuditItemsDoMapper;
import com.ruoyi.approvalFlow.mapper.AuditItemsMapper;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

/**
 * 审批流相关的操作方法，可以根据自己需求添加方法，避免在多个接口中出现重复的方法定义
 */
@Component
public class AuditItemsAbout {
    @Autowired
    private AuditItemsMapper auditItemsMapperOld;
    private static AuditItemsMapper auditItemsMapper;
    @Autowired
    private AuditItemsDoMapper auditItemsDoMapperOld;
    private static AuditItemsDoMapper auditItemsDoMapper;
    @Autowired
    private SysConfigMapper sysConfigMapperOld;
    private static SysConfigMapper sysConfigMapper;

    @PostConstruct
    public void init() {
        auditItemsMapper = this.auditItemsMapperOld;
        auditItemsDoMapper = this.auditItemsDoMapperOld;
        sysConfigMapper = this.sysConfigMapperOld;
    }

    /**
     * 查看系统参数是否启用
     * @param key 参数键名
     * @return true or false
     */
    public static boolean sysConfigKeyTrue(String key){
        boolean ok = false;
        // 获取 sysConfig 配置
        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique(key);
        if ("0".equals(sysConfig.getConfigValue())) { // 是否开启系统参数
            ok = true;
        }
        return ok;
    }

    /**
     * 根据业务 id 连带删除审批流任务明细数据 + 审批流任务明细从表数据
     * @param billId 业务 id
     */
    public static void deleteAuditItemsData(Long billId) {
        // 发起撤销后 根据 feeId 获取到对应的审批流数据
        List<AuditItems> auditItems = auditItemsMapper.selectAuditItemsByBillId(billId);
        // 如果有数据
        if (auditItems.size()!=0) {
            for (AuditItems result : auditItems) {
                // 根据 id 删除对应 审批流数据
                auditItemsMapper.deleteAuditItemsById(result.getId());
                // 根据活动号业务 id 删除对应从表数据
                revokeDeleteAID(result.getActId(),result.getBillId());
            }
        }
    }

    /**
     * 撤销审批时连带删除审批流任务明细从表对应数据
     * @param actId 活动号
     * @param billId 业务id
     */
    public static void revokeDeleteAID(Long actId,Long billId) {
        // 根据审批流任务明细活动号 + 业务id 获取审批流任务明细从表数据
        List<Map<String,Object>> itemsDos = auditItemsDoMapper.selectByActIdAndBillId(actId,billId);
        for (Map<String,Object> map : itemsDos) {
            // 删除审批流任务明细从表
            auditItemsDoMapper.deleteById(Long.valueOf(map.get("fId").toString()));
        }
    }
}
