package com.siwei.rsmonitoring.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.siwei.common.core.exception.ServiceException;
import com.siwei.common.core.utils.DateUtils;
import com.siwei.common.core.utils.StringUtils;
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.config.StaticConfig;
import com.siwei.rsmonitoring.domain.*;
import com.siwei.rsmonitoring.service.ITDkFieldworkLogService;
import com.siwei.rsmonitoring.service.ITDkjbxxService;
import com.siwei.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.siwei.rsmonitoring.mapper.TDkFieldworkMapper;
import com.siwei.rsmonitoring.service.ITDkFieldworkService;
import com.siwei.rsmonitoring.service.ITDkAuditflowRecordService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 地块外业分配Service业务层处理
 *
 * @author siwei
 * @date 2025-01-21
 */
@Service
public class TDkFieldworkServiceImpl implements ITDkFieldworkService {
    @Autowired
    private TDkFieldworkMapper tDkFieldworkMapper;
    @Autowired
    private ITDkAuditflowRecordService dkAuditflowRecordService;
    @Autowired
    private ITDkjbxxService dkjbxxService;
    @Autowired
    private ITDkFieldworkLogService itDkFieldworkLogService;

    /**
     * 查询地块外业分配
     *
     * @param id 地块外业分配主键
     * @return 地块外业分配
     */
    @Override
    public TDkFieldwork selectTDkFieldworkById(String id) {
        return tDkFieldworkMapper.selectTDkFieldworkById(id);
    }

    @Override
    public Map<String, Object> hcCount(String userId) {
        return tDkFieldworkMapper.hcCount(userId);
    }

    /**
     * 查询地块外业分配列表
     *
     * @param tDkFieldwork 地块外业分配
     * @return 地块外业分配
     */
    @Override
    public List<TDkFieldwork> selectTDkFieldworkList(TDkFieldwork tDkFieldwork) {
        return tDkFieldworkMapper.selectTDkFieldworkList(tDkFieldwork);
    }

    /**
     * 新增地块外业分配
     *
     * @param tDkFieldwork 地块外业分配
     * @return 结果
     */
    @Override
    public int insertTDkFieldwork(TDkFieldwork tDkFieldwork) {
        tDkFieldwork.setCreateTime(DateUtils.getNowDate());
        return tDkFieldworkMapper.insertTDkFieldwork(tDkFieldwork);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addSTDkFieldwork(TDkFieldwork tDkFieldwork) {
        if (null == tDkFieldwork) {
            return 0;
        }
        List<String> dkIds = tDkFieldwork.getDkjdxxIds();
        if (dkIds == null || dkIds.isEmpty()) {
            return 0;
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            return 0;
        }

        List<TDkFieldwork> tDkFieldworkInsert = new ArrayList<>();
        TDkFieldwork newTDkFieldwork;
        for (String dkId : dkIds) {
            //验证图斑是否存在
            TDkjbxx dkjbxx = dkjbxxService.selectTDkjbxxById(dkId);
            if (dkjbxx == null) {
                break;
            }

            TDkFieldwork query_data0 = new TDkFieldwork();
            query_data0.setDkjdxxId(dkId);
            List<TDkFieldwork> query_data0_list = tDkFieldworkMapper.selectTDkFieldworkList(query_data0);
            if (!query_data0_list.isEmpty()) {
                TDkFieldwork obj = query_data0_list.get(0);
                if (!"-1".equals(obj.getStepState())) {
                    break;
                }
            }

            //判断用户权限，是否可进行此操作 。暂时忽略 ，后期加上
            if (!dkAuditflowRecordService.isCheckUserTDkAuditflowRecord(dkId, dkjbxx.getAuditflow(), tDkFieldwork.getAuditflowStep(), StaticConfig.AUDIT_FLOW_STEP_OPERATION_TYPE_004)) {
                break;
            }

            newTDkFieldwork = tDkFieldwork;
            newTDkFieldwork.setId(IdUtils.fastSimpleUUID());
            newTDkFieldwork.setDkjdxxId(dkId);
            newTDkFieldwork.setCreateBy(SecurityUtils.getUsername());
            newTDkFieldwork.setCreateTime(DateUtils.getNowDate());
            newTDkFieldwork.setStepState("0");
            newTDkFieldwork.setDkbh(dkjbxx.getDkbh());
            newTDkFieldwork.setDkmj(dkjbxx.getDkmj());
            newTDkFieldwork.setGeom(dkjbxx.getGeom());
            newTDkFieldwork.setAuditflow(dkjbxx.getAuditflow());
            tDkFieldworkMapper.insertTDkFieldwork(newTDkFieldwork);
            tDkFieldworkInsert.add(newTDkFieldwork);

            // 进行审核流程更新
            TDkAuditflowRecord dkAuditFlowRecord_Data = new TDkAuditflowRecord();
            dkAuditFlowRecord_Data.setDkjdxxId(dkId);
            dkAuditFlowRecord_Data.setAuditflowType(dkjbxx.getAuditflow());
            dkAuditFlowRecord_Data.setCreateBy(SecurityUtils.getUsername());
            dkAuditFlowRecord_Data.setAuditflowStep(tDkFieldwork.getAuditflowStep());
            dkAuditFlowRecord_Data.setSuccessType("0");
            Map<String, String> recordData = dkAuditflowRecordService.refreshTDkAuditflowRecord(dkAuditFlowRecord_Data);
            if (recordData.isEmpty()) {
                break;
            }

            String currentId = recordData.get("current");
            TDkFieldworkLog tDkFieldworkLog = new TDkFieldworkLog();
            tDkFieldworkLog.setId(IdUtils.fastSimpleUUID());
            tDkFieldworkLog.setFieldworId(newTDkFieldwork.getId());
            tDkFieldworkLog.setCreateBy(SecurityUtils.getUsername());
            tDkFieldworkLog.setCreateTime(DateUtils.getNowDate());
            tDkFieldworkLog.setStepState(newTDkFieldwork.getStepState());
            tDkFieldworkLog.setAuditflowId(currentId);
            itDkFieldworkLogService.insertTDkFieldworkLog(tDkFieldworkLog);
        }
        return tDkFieldworkInsert.size();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeSTDkFieldwork(TDkFieldwork tDkFieldwork) {
        if (null == tDkFieldwork) {
            return 0;
        }
        List<String> dkIds = tDkFieldwork.getDkjdxxIds();
        if (dkIds == null || dkIds.isEmpty()) {
            return 0;
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            return 0;
        }

        List<TDkFieldwork> tDkFieldworkInsert = new ArrayList<>();
        TDkFieldwork newTDkFieldwork;
        for (String dkId : dkIds) {
            //验证图斑是否存在
            TDkjbxx dkjbxx = dkjbxxService.selectTDkjbxxById(dkId);
            if (dkjbxx == null) {
                break;
            }

            TDkFieldwork query_data0 = new TDkFieldwork();
            query_data0.setDkjdxxId(dkId);
            List<TDkFieldwork> query_data0_list = tDkFieldworkMapper.selectTDkFieldworkList(query_data0);
            if (query_data0_list.isEmpty()) {
                break;
            }
            TDkFieldwork obj = query_data0_list.get(0);
            if (!"0".equals(obj.getStepState())) {
                break;
            }

            //判断用户权限，是否可进行此操作 。暂时忽略 ，后期加上
            if (!dkAuditflowRecordService.isCheckUserTDkAuditflowRecord(dkId, dkjbxx.getAuditflow(), tDkFieldwork.getAuditflowStep(), StaticConfig.AUDIT_FLOW_STEP_OPERATION_TYPE_005)) {
                break;
            }

            // 进行审核流程更新
            TDkAuditflowRecord dkAuditFlowRecord_Data = new TDkAuditflowRecord();
            dkAuditFlowRecord_Data.setDkjdxxId(dkId);
            dkAuditFlowRecord_Data.setAuditflowType(dkjbxx.getAuditflow());
            dkAuditFlowRecord_Data.setCreateBy(SecurityUtils.getUsername());
            dkAuditFlowRecord_Data.setAuditflowStep(tDkFieldwork.getAuditflowStep());
            dkAuditFlowRecord_Data.setSuccessType("1");
            Map<String, String> recordData = dkAuditflowRecordService.refreshTDkAuditflowRecord(dkAuditFlowRecord_Data);
            if (recordData.isEmpty()) {
                break;
            }
            String currentId = recordData.get("current");

            newTDkFieldwork = new TDkFieldwork();
            newTDkFieldwork.setId(obj.getId());
            newTDkFieldwork.setUpdateBy(SecurityUtils.getUsername());
            newTDkFieldwork.setUpdateTime(DateUtils.getNowDate());
            newTDkFieldwork.setStepState("-1");
            newTDkFieldwork.setConfirmState("3");
            tDkFieldworkMapper.updateTDkFieldwork(newTDkFieldwork);

            TDkFieldworkLog tDkFieldworkLog = new TDkFieldworkLog();
            tDkFieldworkLog.setId(IdUtils.fastSimpleUUID());
            tDkFieldworkLog.setFieldworId(obj.getId());
            tDkFieldworkLog.setCreateBy(SecurityUtils.getUsername());
            tDkFieldworkLog.setCreateTime(DateUtils.getNowDate());
            tDkFieldworkLog.setStepState(newTDkFieldwork.getStepState());
            tDkFieldworkLog.setAuditflowId(currentId);
            itDkFieldworkLogService.insertTDkFieldworkLog(tDkFieldworkLog);

            tDkFieldworkInsert.add(newTDkFieldwork);

        }
        return tDkFieldworkInsert.size();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int confirmTDkFieldwork(TDkFieldwork tDkFieldwork) {
        if (null == tDkFieldwork) {
            return 0;
        }
        if (StringUtils.isEmpty(tDkFieldwork.getId())) {
            return 0;
        }
        if (StringUtils.isEmpty(tDkFieldwork.getConfirmState())) {
            return 0;
        }
        String stepStateV0 = null;
        if ("1".equals(tDkFieldwork.getConfirmState())) {
            if (StringUtils.isEmpty(tDkFieldwork.getConfirmType())) {
                return 0;
            }
            stepStateV0 = "-1";
        } else if ("0".equals(tDkFieldwork.getConfirmState())) {
            stepStateV0 = "1";
        } else {
            return 0;
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            return 0;
        }
        //验证ID
        TDkFieldwork v1 = tDkFieldworkMapper.selectTDkFieldworkById(tDkFieldwork.getId());
        if (v1 == null) {
            throw new ServiceException("信息缺失");
        }
        if (!SecurityUtils.getUserId().toString().equals(v1.getFieldworkId())) {
            throw new ServiceException("信息缺失");
        }
        if (!"0".equals(v1.getStepState())) {
            throw new ServiceException("已执行过");
        }

        //判断用户权限，是否可进行此操作 。暂时忽略 ，后期加上
        if (!dkAuditflowRecordService.isCheckUserTDkAuditflowRecord(v1.getDkjdxxId(), v1.getAuditflow(), tDkFieldwork.getAuditflowStep(), StaticConfig.AUDIT_FLOW_STEP_OPERATION_TYPE_005)) {
            throw new ServiceException("无权限操作");
        }

        TDkFieldwork newTDkFieldwork = new TDkFieldwork();
        newTDkFieldwork.setId(tDkFieldwork.getId());
        newTDkFieldwork.setConfirmState(tDkFieldwork.getConfirmState());
        newTDkFieldwork.setConfirmType(tDkFieldwork.getConfirmType());
        newTDkFieldwork.setConfirmNotse(tDkFieldwork.getConfirmNotse());
        newTDkFieldwork.setConfirmTime(DateUtils.getNowDate());
        newTDkFieldwork.setStepState(stepStateV0);
        tDkFieldworkMapper.updateTDkFieldwork(newTDkFieldwork);

        // 进行审核流程更新
        TDkAuditflowRecord dkAuditFlowRecord_Data = new TDkAuditflowRecord();
        dkAuditFlowRecord_Data.setDkjdxxId(v1.getDkjdxxId());
        dkAuditFlowRecord_Data.setAuditflowType(v1.getAuditflow());
        dkAuditFlowRecord_Data.setCreateBy(SecurityUtils.getUsername());
        dkAuditFlowRecord_Data.setAuditflowStep(tDkFieldwork.getAuditflowStep());
        dkAuditFlowRecord_Data.setSuccessType(tDkFieldwork.getConfirmState());
        Map<String, String> recordData = dkAuditflowRecordService.refreshTDkAuditflowRecord(dkAuditFlowRecord_Data);
        if (recordData.isEmpty()) {
            throw new ServiceException("核查流程失败");
        }

        String currentId = recordData.get("current");
        TDkFieldworkLog tDkFieldworkLog = new TDkFieldworkLog();
        tDkFieldworkLog.setId(IdUtils.fastSimpleUUID());
        tDkFieldworkLog.setFieldworId(newTDkFieldwork.getId());
        tDkFieldworkLog.setCreateBy(SecurityUtils.getUsername());
        tDkFieldworkLog.setCreateTime(DateUtils.getNowDate());
        tDkFieldworkLog.setStepState(newTDkFieldwork.getStepState());
        tDkFieldworkLog.setAuditflowId(currentId);
        itDkFieldworkLogService.insertTDkFieldworkLog(tDkFieldworkLog);
        return 1;
    }

    /**
     * 修改地块外业分配
     *
     * @param tDkFieldwork 地块外业分配
     * @return 结果
     */
    @Override
    public int updateTDkFieldwork(TDkFieldwork tDkFieldwork) {
        return tDkFieldworkMapper.updateTDkFieldwork(tDkFieldwork);
    }

    /**
     * 批量删除地块外业分配
     *
     * @param ids 需要删除的地块外业分配主键
     * @return 结果
     */
    @Override
    public int deleteTDkFieldworkByIds(String[] ids) {
        return tDkFieldworkMapper.deleteTDkFieldworkByIds(ids);
    }

    /**
     * 删除地块外业分配信息
     *
     * @param id 地块外业分配主键
     * @return 结果
     */
    @Override
    public int deleteTDkFieldworkById(String id) {
        return tDkFieldworkMapper.deleteTDkFieldworkById(id);
    }
}
