package com.siwei.rsmonitoring.service.impl;

import com.siwei.common.core.utils.DateUtils;
import com.siwei.common.core.utils.StringUtils;
import com.siwei.common.core.utils.bean.BeanReflectionUtils;
import com.siwei.common.core.utils.uuid.IdUtils;
import com.siwei.common.security.utils.SecurityUtils;
import com.siwei.rsmonitoring.cache.AuditFlowCacheUtil;
import com.siwei.rsmonitoring.domain.TDkAuditflowRecord;
import com.siwei.rsmonitoring.domain.TDkAuditflowStep;
import com.siwei.rsmonitoring.domain.TDkjbxxState;
import com.siwei.rsmonitoring.mapper.TDkAuditflowRecordMapper;
import com.siwei.rsmonitoring.mapper.TDkjbxxStateMapper;
import com.siwei.rsmonitoring.service.ITDkAuditflowRecordService;
import com.siwei.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 地块核查流程Service业务层处理
 *
 * @author siwei
 * @date 2025-01-21
 */
@Service
public class TDkAuditflowRecordServiceImpl1 implements ITDkAuditflowRecordService {
    @Autowired
    private TDkAuditflowRecordMapper tDkAuditflowRecordMapper;
    @Autowired
    private TDkjbxxStateMapper tDkjbxxStateMapper;

    /**
     * 查询地块核查流程
     *
     * @param id 地块核查流程主键
     * @return 地块核查流程
     */
    @Override
    public TDkAuditflowRecord selectTDkAuditflowRecordById(String id) {
        return tDkAuditflowRecordMapper.selectTDkAuditflowRecordById(id);
    }

    /**
     * 查询地块核查流程列表
     *
     * @param tDkAuditflowRecord 地块核查流程
     * @return 地块核查流程
     */
    @Override
    public List<TDkAuditflowRecord> selectTDkAuditflowRecordList(TDkAuditflowRecord tDkAuditflowRecord) {
        return tDkAuditflowRecordMapper.selectTDkAuditflowRecordList(tDkAuditflowRecord);
    }

    @Override
    public int insertTDkAuditflowRecord(TDkAuditflowRecord tDkAuditflowRecord) {
        return tDkAuditflowRecordMapper.insertTDkAuditflowRecord(tDkAuditflowRecord);
    }

    @Override
    public Map<String, String> initDkAuditflowRecord(TDkAuditflowRecord tDkAuditflowRecord) {
        Map<String, String> retMap = new HashMap<>();
        //判断条件，是否满足相应的条件
        if (tDkAuditflowRecord == null) {
            return retMap;
        }
        tDkAuditflowRecord.setCreateBy(SecurityUtils.getUsername());
        if (StringUtils.isEmpty(tDkAuditflowRecord.getCreateBy())) {
            return retMap;
        }
        if (StringUtils.isEmpty(tDkAuditflowRecord.getDkjdxxId())) {
            return retMap;
        }
        if (StringUtils.isEmpty(tDkAuditflowRecord.getAuditflowType())) {
            return retMap;
        }

        AuditFlowCacheUtil auditFlowCacheUtil = AuditFlowCacheUtil.getInstance();
        List<TDkAuditflowStep> stepList = auditFlowCacheUtil.getCodeCacheData(tDkAuditflowRecord.getAuditflowType());
        if (stepList == null || stepList.isEmpty() || stepList.size() < 2) {
            return retMap;
        }

        //数据下发
        Long xyjAuditflowOrder = 0L;
        //验证当前的数据是否可进行操作
        TDkAuditflowStep stepNewObj = null;
        TDkAuditflowRecord newDkAuditFlowRecord = tDkAuditflowRecord;
        for (TDkAuditflowStep obj : stepList) {
            stepNewObj = obj;
            newDkAuditFlowRecord.setId(IdUtils.fastSimpleUUID());
            newDkAuditFlowRecord.setAuditflowStep(stepNewObj.getStepCode());
            newDkAuditFlowRecord.setAuditflowOrder(xyjAuditflowOrder);
            newDkAuditFlowRecord.setAuditflowOperateType("0");
            newDkAuditFlowRecord.setCreateTime(DateUtils.getNowDate());
            newDkAuditFlowRecord.setSuccessType("0");
            tDkAuditflowRecordMapper.insertTDkAuditflowRecord(newDkAuditFlowRecord);
            if ("WYFF".equals(stepNewObj.getNextSuccess())) {
                break;
            }
            xyjAuditflowOrder++;
        }

        retMap.put("current", newDkAuditFlowRecord.getId());
        xyjAuditflowOrder++;
        TDkAuditflowRecord nestDkAuditFlowRecord = tDkAuditflowRecord;
        nestDkAuditFlowRecord.setId(IdUtils.fastSimpleUUID());
        nestDkAuditFlowRecord.setAuditflowStep(stepNewObj.getNextSuccess());
        nestDkAuditFlowRecord.setAuditflowOrder(xyjAuditflowOrder);
        nestDkAuditFlowRecord.setAuditflowOperateType("1");
        nestDkAuditFlowRecord.setCreateTime(DateUtils.getNowDate());
        tDkAuditflowRecordMapper.insertTDkAuditflowRecord(nestDkAuditFlowRecord);
        retMap.put("next", nestDkAuditFlowRecord.getId());

        TDkjbxxState tDkjbxxState = new TDkjbxxState();
        tDkjbxxState.setId(newDkAuditFlowRecord.getDkjdxxId());
        tDkjbxxState.setAuditflow(newDkAuditFlowRecord.getAuditflowType());
        tDkjbxxState.setStepCode(newDkAuditFlowRecord.getAuditflowStep());
        tDkjbxxState.setOperationBy(SecurityUtils.getUsername());
        tDkjbxxState.setOperationTime(DateUtils.getNowDate());
        tDkjbxxState.setOperationId(SecurityUtils.getUserId().toString());
        tDkjbxxState.setSuccessType("0");
        tDkjbxxStateMapper.insertTDkjbxxState(tDkjbxxState);
        return retMap;
    }


    /**
     * 刷新地块核查流程
     *
     * @param tDkAuditflowRecord 地块核查流程
     * @return 结果
     */
    @Override
    public Map<String, String> refreshTDkAuditflowRecord(TDkAuditflowRecord tDkAuditflowRecord) {
        Map<String, String> retMap = new HashMap<>();
        //判断条件，是否满足相应的条件
        if (tDkAuditflowRecord == null) {
            return retMap;
        }
        if (StringUtils.isEmpty(tDkAuditflowRecord.getDkjdxxId())) {
            return retMap;
        }
        if (StringUtils.isEmpty(tDkAuditflowRecord.getSuccessType())) {
            return retMap;
        }
        if (StringUtils.isEmpty(tDkAuditflowRecord.getAuditflowType())) {
            return retMap;
        }
        if (StringUtils.isEmpty(tDkAuditflowRecord.getAuditflowStep())) {
            return retMap;
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            return retMap;
        }
        tDkAuditflowRecord.setCreateBy(SecurityUtils.getUsername());

        //验证当前的数据是否可进行操作
        TDkAuditflowRecord dkAuditFlowRecordQuery = new TDkAuditflowRecord();
        dkAuditFlowRecordQuery.setDkjdxxId(tDkAuditflowRecord.getDkjdxxId());
        dkAuditFlowRecordQuery.setAuditflowOperateType("1");
        dkAuditFlowRecordQuery.setAuditflowType(tDkAuditflowRecord.getAuditflowType());
        List<TDkAuditflowRecord> tDkAuditFlowRecords = tDkAuditflowRecordMapper.selectTDkAuditflowRecordList(dkAuditFlowRecordQuery);
        if (tDkAuditFlowRecords == null || tDkAuditFlowRecords.isEmpty()) {
            return retMap;
        }
        Long xyjAuditflowOrder = 0L;
        TDkAuditflowRecord dkAuditFlowRecord_Data = null;
        List<TDkAuditflowRecord> tDkAuditFlowRecordsFull = new ArrayList<>();
        for (TDkAuditflowRecord recordObj : tDkAuditFlowRecords) {
            xyjAuditflowOrder = recordObj.getAuditflowOrder();
            if (tDkAuditflowRecord.getAuditflowStep().equals(recordObj.getAuditflowStep())) {
                dkAuditFlowRecord_Data = recordObj;
            } else {
                tDkAuditFlowRecordsFull.add(recordObj);
            }
        }

        if (null == dkAuditFlowRecord_Data) {
            return retMap;
        }

        if (dkAuditFlowRecord_Data.getAuditflowStep().equals("-9999")) {
            return retMap;
        }
        //验证
        AuditFlowCacheUtil auditFlowCacheUtil = AuditFlowCacheUtil.getInstance();
        TDkAuditflowStep presentStep = auditFlowCacheUtil.getAuditFlowTypePresentStep(dkAuditFlowRecord_Data.getAuditflowType(), dkAuditFlowRecord_Data.getAuditflowStep());
        if (presentStep == null) {
            return retMap;
        }

        //校验用户是否可以进行操作,校验分为两种，一种是角色校验，另外一种是方法校验
        //判断用户权限，是否可进行此操作 。暂时忽略 ，后期加上
        if (!loginUser.getSysUser().isAdmin()) {
            Set<String> auditFlows = loginUser.getAuditFlows();
            String auditFlowHandle = dkAuditFlowRecord_Data.getAuditflowType() + ":" + dkAuditFlowRecord_Data.getAuditflowStep();
            if (!auditFlows.contains(auditFlowHandle)) {
                return retMap;
            }
        }

        //方法校验 做二次扩展 true为校验成功
        String checkBean = presentStep.getCheckBean();
        String checkMethod = presentStep.getCheckMethod();
        if (StringUtils.isNotEmpty(checkBean)) {
            try {
                String userid = loginUser.getUserid().toString();
                List<Object> invokeMethodData = new ArrayList<>();
                invokeMethodData.add(dkAuditFlowRecord_Data.getDkjdxxId());
                invokeMethodData.add(userid);
                invokeMethodData.add(dkAuditFlowRecord_Data.getAuditflowType());
                Object resultBean = BeanReflectionUtils.invokeMethodV1(checkBean, checkMethod, invokeMethodData);
                if (resultBean instanceof Boolean) {
                    boolean boolResult = (Boolean) resultBean;
                    if (!boolResult) {
                        //校验失败，
                        return retMap;
                    }
                } else {
                    return retMap;
                }
            } catch (Exception e) {
                return retMap;
            }
        }

        dkAuditFlowRecord_Data.setAuditflowOperateType("0");
        dkAuditFlowRecord_Data.setAuditflowOperateData(tDkAuditflowRecord.getAuditflowOperateData());
        dkAuditFlowRecord_Data.setCreateBy(tDkAuditflowRecord.getCreateBy());
        dkAuditFlowRecord_Data.setCreateTime(DateUtils.getNowDate());
        dkAuditFlowRecord_Data.setSuccessType(tDkAuditflowRecord.getSuccessType());


        TDkjbxxState tDkjbxxState = new TDkjbxxState();
        tDkjbxxState.setId(dkAuditFlowRecord_Data.getDkjdxxId());
        tDkjbxxState.setAuditflow(dkAuditFlowRecord_Data.getAuditflowType());
        tDkjbxxState.setStepCode(dkAuditFlowRecord_Data.getAuditflowStep());
        tDkjbxxState.setOperationBy(SecurityUtils.getUsername());
        tDkjbxxState.setOperationTime(DateUtils.getNowDate());
        tDkjbxxState.setOperationId(SecurityUtils.getUserId().toString());
        tDkjbxxState.setSuccessType(tDkAuditflowRecord.getSuccessType());


        //0 成功 1失败
        //TODO 修改流程
//        下一级判断
        xyjAuditflowOrder++;
        TDkAuditflowRecord dkAuditFlowRecord_Data_Next = new TDkAuditflowRecord();
        dkAuditFlowRecord_Data_Next.setId(IdUtils.fastSimpleUUID());
        dkAuditFlowRecord_Data_Next.setDkjdxxId(dkAuditFlowRecord_Data.getDkjdxxId());
        dkAuditFlowRecord_Data_Next.setAuditflowType(dkAuditFlowRecord_Data.getAuditflowType());
        dkAuditFlowRecord_Data_Next.setAuditflowOrder(xyjAuditflowOrder);
        dkAuditFlowRecord_Data_Next.setAuditflowOperateType("1");

        if ("0".equals(tDkAuditflowRecord.getSuccessType())) {
            if (tDkAuditFlowRecordsFull.isEmpty()) {
                if (StringUtils.isEmpty(presentStep.getNextSuccess())) {
                    dkAuditFlowRecord_Data_Next.setAuditflowStep("-999");
                    tDkjbxxState.setStepCode("-999");
                    tDkAuditflowRecordMapper.insertTDkAuditflowRecord(dkAuditFlowRecord_Data_Next);
                } else {
                    String[] nextSuccess = presentStep.getNextSuccess().split(",");
                    for (String s : nextSuccess) {
                        if (!StringUtils.isEmpty(s)) {
                            dkAuditFlowRecord_Data_Next.setAuditflowOrder(xyjAuditflowOrder);
                            dkAuditFlowRecord_Data_Next.setAuditflowStep(s);
                            tDkAuditflowRecordMapper.insertTDkAuditflowRecord(dkAuditFlowRecord_Data_Next);
                            xyjAuditflowOrder++;
                        }
                    }
                }
            }
        } else {
            if (StringUtils.isEmpty(presentStep.getNextFull())) {
                tDkjbxxState.setStepCode("-999");
                dkAuditFlowRecord_Data_Next.setAuditflowStep("-999");
            } else {
                dkAuditFlowRecord_Data_Next.setAuditflowStep(presentStep.getNextFull());
            }
            tDkAuditflowRecordMapper.insertTDkAuditflowRecord(dkAuditFlowRecord_Data_Next);

            if (!tDkAuditFlowRecordsFull.isEmpty()) {
                for (TDkAuditflowRecord record : tDkAuditFlowRecordsFull) {
                    record.setSuccessType(tDkAuditflowRecord.getSuccessType());
                    record.setAuditflowOperateType("3");
                    tDkAuditflowRecordMapper.updateTDkAuditflowRecord(record);
                }
            }
        }
        tDkAuditflowRecordMapper.updateTDkAuditflowRecord(dkAuditFlowRecord_Data);
        tDkjbxxStateMapper.updateTDkjbxxState(tDkjbxxState);
        retMap.put("current", dkAuditFlowRecord_Data.getId());
//        retMap.put("next", dkAuditFlowRecord_Data_Next.getId());
        return retMap;
    }

    /**
     * 修改地块核查流程
     *
     * @param tDkAuditflowRecord 地块核查流程
     * @return 结果
     */
    @Override
    public int updateTDkAuditflowRecord(TDkAuditflowRecord tDkAuditflowRecord) {
        return tDkAuditflowRecordMapper.updateTDkAuditflowRecord(tDkAuditflowRecord);
    }

    /**
     * 批量删除地块核查流程
     *
     * @param ids 需要删除的地块核查流程主键
     * @return 结果
     */
    @Override
    public int deleteTDkAuditflowRecordByIds(String[] ids) {
        return tDkAuditflowRecordMapper.deleteTDkAuditflowRecordByIds(ids);
    }

    /**
     * 删除地块核查流程信息
     *
     * @param id 地块核查流程主键
     * @return 结果
     */
    @Override
    public int deleteTDkAuditflowRecordById(String id) {
        return tDkAuditflowRecordMapper.deleteTDkAuditflowRecordById(id);
    }


    /**
     * 校驗用戶是否有權限操作，并返回当前操作
     *
     * @param auditflow
     * @return
     */
    @Override
    public boolean isCheckUserTDkAuditflowRecord(String dkid, String auditflow, String auditflowStep, String operationType) {
        if (StringUtils.isEmpty(dkid) || StringUtils.isEmpty(auditflow) || StringUtils.isEmpty(auditflowStep)) {
            return false;
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            return false;
        }

        //验证当前的数据列席是否可进行下发
        TDkAuditflowRecord dkAuditFlowRecordQuery = new TDkAuditflowRecord();
        dkAuditFlowRecordQuery.setDkjdxxId(dkid);
        dkAuditFlowRecordQuery.setAuditflowType(auditflow);
        dkAuditFlowRecordQuery.setAuditflowOperateType("1");
        List<TDkAuditflowRecord> tDkAuditFlowRecords = selectTDkAuditflowRecordList(dkAuditFlowRecordQuery);
        if (tDkAuditFlowRecords == null || tDkAuditFlowRecords.isEmpty()) {
            return false;
        }
        TDkAuditflowRecord dkAuditFlowRecord_Data = null;
        List<TDkAuditflowRecord> tDkAuditFlowRecordsFull = new ArrayList<>();
        for (TDkAuditflowRecord recordObj : tDkAuditFlowRecords) {
            if (auditflowStep.equals(recordObj.getAuditflowStep())) {
                dkAuditFlowRecord_Data = recordObj;
            }
        }

        if (dkAuditFlowRecord_Data == null) {
            return false;
        }

        //判断用户权限，是否可进行此操作 。暂时忽略 ，后期加上
        if (!loginUser.getSysUser().isAdmin()) {
            Set<String> auditFlows = loginUser.getAuditFlows();
            String auditFlowHandle = dkAuditFlowRecord_Data.getAuditflowType() + ":" + dkAuditFlowRecord_Data.getAuditflowStep();
            if (!auditFlows.contains(auditFlowHandle)) {
                return false;
            }
        }

        AuditFlowCacheUtil auditFlowCacheUtil = AuditFlowCacheUtil.getInstance();
        TDkAuditflowStep presentStep = auditFlowCacheUtil.getAuditFlowTypePresentStep(dkAuditFlowRecord_Data.getAuditflowType(), dkAuditFlowRecord_Data.getAuditflowStep());
        if (presentStep == null) {
            return false;
        }

        if (StringUtils.isNotEmpty(presentStep.getOperationType()) && StringUtils.isEmpty(operationType)) {
            return false;
        }

        if (StringUtils.isEmpty(presentStep.getOperationType()) && StringUtils.isNotEmpty(operationType)) {
            return false;
        }

        if (StringUtils.isNotEmpty(presentStep.getOperationType()) && StringUtils.isNotEmpty(operationType)) {
            if (!operationType.equals(presentStep.getOperationType())) {
                return false;
            }
        }

        return true;
    }

    /**
     * 校驗用戶是否有權限操作，并返回当前操作
     *
     * @param auditflow
     * @return
     */
    @Override
    public boolean isCheckDataUpdateTDkAuditflowRecord(String dkid, String auditflow) {
        if (StringUtils.isEmpty(dkid) || StringUtils.isEmpty(auditflow)) {
            return false;
        }

        //验证当前的数据列席是否可进行
        TDkAuditflowRecord dkAuditFlowRecordQuery = new TDkAuditflowRecord();
        dkAuditFlowRecordQuery.setDkjdxxId(dkid);
        dkAuditFlowRecordQuery.setAuditflowType(auditflow);
        dkAuditFlowRecordQuery.setAuditflowOperateType("1");
        dkAuditFlowRecordQuery.setAuditflowStep("LR");
        List<TDkAuditflowRecord> tDkAuditFlowRecords = selectTDkAuditflowRecordList(dkAuditFlowRecordQuery);
        if (!tDkAuditFlowRecords.isEmpty()) {
            return true;
        }

        dkAuditFlowRecordQuery.setDkjdxxId(dkid);
        dkAuditFlowRecordQuery.setAuditflowType(auditflow);
        dkAuditFlowRecordQuery.setAuditflowOperateType("1");
        dkAuditFlowRecordQuery.setAuditflowStep("SJXF");
        tDkAuditFlowRecords = selectTDkAuditflowRecordList(dkAuditFlowRecordQuery);
        if (!tDkAuditFlowRecords.isEmpty()) {
            return true;
        }

        dkAuditFlowRecordQuery.setDkjdxxId(dkid);
        dkAuditFlowRecordQuery.setAuditflowType(auditflow);
        dkAuditFlowRecordQuery.setAuditflowOperateType("1");
        dkAuditFlowRecordQuery.setAuditflowStep("WYFF");
        tDkAuditFlowRecords = selectTDkAuditflowRecordList(dkAuditFlowRecordQuery);
        if (!tDkAuditFlowRecords.isEmpty()) {
            return true;
        }

        return false;
    }

    ;
}
