package com.siwei.rsmonitoring.service.impl;

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

import com.alibaba.fastjson2.JSON;
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.ITDkAuditflowRecordService;
import com.siwei.rsmonitoring.service.ITDkFieldworkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.siwei.rsmonitoring.mapper.TFieldworkTjMapper;
import com.siwei.rsmonitoring.service.ITFieldworkTjService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 地块外业提交Service业务层处理
 *
 * @author siwei
 * @date 2025-03-05
 */
@Service
public class TFieldworkTjServiceImpl implements ITFieldworkTjService {
    @Autowired
    private TFieldworkTjMapper tFieldworkTjMapper;
    @Autowired
    private ITDkAuditflowRecordService dkAuditflowRecordService;
    @Autowired
    private ITDkFieldworkService itDkFieldworkService;

    /**
     * 查询地块外业提交
     *
     * @param id 地块外业提交主键
     * @return 地块外业提交
     */
    @Override
    public TFieldworkTj selectTFieldworkTjById(String id) {
        return tFieldworkTjMapper.selectTFieldworkTjById(id);
    }

    /**
     * 查询地块外业提交列表
     *
     * @param tFieldworkTj 地块外业提交
     * @return 地块外业提交
     */
    @Override
    public List<TFieldworkTj> selectTFieldworkTjList(TFieldworkTj tFieldworkTj) {
        return tFieldworkTjMapper.selectTFieldworkTjList(tFieldworkTj);
    }

    /**
     * 新增地块外业提交
     *
     * @param tFieldworkTj 地块外业提交
     * @return 结果
     */
    @Override
    public int insertTFieldworkTj(TFieldworkTj tFieldworkTj) {
        tFieldworkTj.setCreateTime(DateUtils.getNowDate());
        return tFieldworkTjMapper.insertTFieldworkTj(tFieldworkTj);
    }

    /**
     * 修改地块外业提交
     *
     * @param tFieldworkTj 地块外业提交
     * @return 结果
     */
    @Override
    public int updateTFieldworkTj(TFieldworkTj tFieldworkTj) {
        return tFieldworkTjMapper.updateTFieldworkTj(tFieldworkTj);
    }

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

    /**
     * 删除地块外业提交信息
     *
     * @param id 地块外业提交主键
     * @return 结果
     */
    @Override
    public int deleteTFieldworkTjById(String id) {
        return tFieldworkTjMapper.deleteTFieldworkTjById(id);
    }

    @Override
    public TFieldworkTj selectTFieldworkTjInfo(String fieldworkId, String dkid, String auditflowStep, String auditflowId) {
        if (StringUtils.isNotEmpty(fieldworkId) && StringUtils.isNotEmpty(dkid)) {
            return null;
        }
        if (StringUtils.isEmpty(auditflowStep)) {
            return null;
        }
        TDkFieldwork queryTDkFieldwork = new TDkFieldwork();
        if (StringUtils.isNotEmpty(fieldworkId)) {
            queryTDkFieldwork.setId(fieldworkId);
        }
        if (StringUtils.isNotEmpty(dkid)) {
            queryTDkFieldwork.setDkjdxxId(dkid);
        }
        List<TDkFieldwork> tDkFieldworks = itDkFieldworkService.selectTDkFieldworkList(queryTDkFieldwork);
        if (tDkFieldworks.isEmpty()) {
            return null;
        }
        TDkFieldwork v1 = tDkFieldworks.get(0);
        if (v1 == null) {
            throw new ServiceException("信息缺失");
        }
        if (!SecurityUtils.getUserId().toString().equals(v1.getFieldworkId())) {
            throw new ServiceException("信息缺失");
        }
        fieldworkId = v1.getId();
        dkid = v1.getDkjdxxId();

        TFieldworkTj tFieldworkTjQuery = new TFieldworkTj();
        tFieldworkTjQuery.setFieldworkId(fieldworkId);
        tFieldworkTjQuery.setDkjbxxId(dkid);
        tFieldworkTjQuery.setAuditflowStep(auditflowStep);
        if (StringUtils.isNotEmpty(auditflowId)) {
            tFieldworkTjQuery.setAuditflowId(auditflowId);
        }
        List<TFieldworkTj> list = tFieldworkTjMapper.selectTFieldworkTjList(tFieldworkTjQuery);
        if (!list.isEmpty()) {
            return list.get(0);
        }

        TDkAuditflowRecord tDkAuditflowRecord = new TDkAuditflowRecord();
        tDkAuditflowRecord.setDkjdxxId(dkid);
        tDkAuditflowRecord.setAuditflowStep(auditflowStep);
        if (StringUtils.isNotEmpty(auditflowId)) {
            tDkAuditflowRecord.setId(auditflowId);
        }
        List<TDkAuditflowRecord> tDkAuditflowRecords = dkAuditflowRecordService.selectTDkAuditflowRecordList(tDkAuditflowRecord);
        if (tDkAuditflowRecords.isEmpty()) {
            return null;
        }
        TDkAuditflowRecord qureyData0 = tDkAuditflowRecords.get(0);
        if ("1".equals(qureyData0.getAuditflowState())) {
            TDkAuditflowRecord tDkAuditflowRecord2 = new TDkAuditflowRecord();
            tDkAuditflowRecord2.setDkjdxxId(dkid);
            tDkAuditflowRecord2.setNextId(qureyData0.getPreviousId());
            List<TDkAuditflowRecord> tDkAuditflowRecords2 = dkAuditflowRecordService.selectTDkAuditflowRecordList(tDkAuditflowRecord2);
            if (tDkAuditflowRecords.isEmpty()) {
                return null;
            }

            AuditFlowCacheUtil auditFlowCacheUtil = AuditFlowCacheUtil.getInstance();
            String decide = "0";
            List<Map<String, String>> notes = new ArrayList<>();
            for (TDkAuditflowRecord obj_v1 : tDkAuditflowRecords2) {
                TDkAuditflowStep dkAuditflowStep = auditFlowCacheUtil.getAuditFlowTypePresentStep(obj_v1.getAuditflowType(), obj_v1.getAuditflowStep());
                if (null == dkAuditflowStep) {
                    return null;
                }
                Map<String, String> data = new HashMap<>();
                data.put("stepValue", dkAuditflowStep.getStepValue());
                data.put("stepCode", dkAuditflowStep.getStepCode());
                if ("1".equals(obj_v1.getSuccessType())) {
                    decide = "1";
                    data.put("notes", "操作执行完成");
                } else {
                    data.put("notes", "操作执行完成");
                }
                notes.add(data);
            }
            TFieldworkTj ret = new TFieldworkTj();
            ret.setDkjbxxId(dkid);
            ret.setDecide(decide);
            ret.setNotes(JSON.toJSONString(notes));
            return ret;
        } else {
            return null;
        }
    }

    /**
     * 新增地块基本信息提交
     *
     * @param tFieldworkTj 地块基本信息提交
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addTFieldworkTj(TFieldworkTj tFieldworkTj) {
        if (null == tFieldworkTj) {
            return 0;
        }
        if (StringUtils.isEmpty(tFieldworkTj.getFieldworkId()) || StringUtils.isEmpty(tFieldworkTj.getAuditflowStep()) || StringUtils.isEmpty(tFieldworkTj.getDecide())) {
            return 0;
        }
        String fieldworkId = tFieldworkTj.getFieldworkId();
        String auditflowStep = tFieldworkTj.getAuditflowStep();
        //验证ID
        TDkFieldwork v1 = itDkFieldworkService.selectTDkFieldworkById(fieldworkId);
        if (v1 == null) {
            throw new ServiceException("信息缺失");
        }
        if (!SecurityUtils.getUserId().toString().equals(v1.getFieldworkId())) {
            throw new ServiceException("信息缺失");
        }

        if (!"2".equals(v1.getStepState())) {
            throw new ServiceException("无权限执行");
        }
        String dkid = v1.getDkjdxxId();
        if (StringUtils.isEmpty(dkid)) {
            return 0;
        }
        if (!dkAuditflowRecordService.isCheckUserTDkAuditflowRecord(v1.getDkjdxxId(), v1.getAuditflow(), auditflowStep, null)) {
            return 0;
        }
        tFieldworkTj.setDkjbxxId(dkid);
        tFieldworkTj.setCreateBy(SecurityUtils.getUsername());
        tFieldworkTj.setId(IdUtils.fastSimpleUUID());
        tFieldworkTj.setCreateTime(DateUtils.getNowDate());
        tFieldworkTjMapper.insertTFieldworkTj(tFieldworkTj);

        //更新流程
        TDkAuditflowRecord tDkAuditflowRecord = new TDkAuditflowRecord();
        tDkAuditflowRecord.setDkjdxxId(dkid);
        tDkAuditflowRecord.setAuditflowType(v1.getAuditflow());
        tDkAuditflowRecord.setCreateBy(SecurityUtils.getUsername());
        tDkAuditflowRecord.setAuditflowStep(auditflowStep);
        tDkAuditflowRecord.setSuccessType("0");
        Map<String, String> recordData = dkAuditflowRecordService.refreshTDkAuditflowRecord(tDkAuditflowRecord);
        if (recordData.isEmpty()) {
            throw new ServiceException("流程失败");
        }

        TDkFieldwork v1Update = new TDkFieldwork();
        v1Update.setId(v1.getId());
        v1Update.setStepState("3");
        itDkFieldworkService.updateTDkFieldwork(v1Update);

        String currentId = recordData.get("current");
        deleteAuditflowId(currentId);
        TFieldworkTj tTjUpdate = new TFieldworkTj();
        tTjUpdate.setId(tFieldworkTj.getId());
        tTjUpdate.setAuditflowId(currentId);
        tFieldworkTjMapper.updateTFieldworkTj(tTjUpdate);
        return 1;
    }

    private void deleteAuditflowId(String auditflowId) {
        TFieldworkTj query = new TFieldworkTj();
        query.setAuditflowId(auditflowId);
        List<TFieldworkTj> removerList = tFieldworkTjMapper.selectTFieldworkTjList(query);
        for (TFieldworkTj hgx : removerList) {
            tFieldworkTjMapper.deleteTFieldworkTjById(hgx.getId());
        }
    }
}
