package com.fs.provider.service.impl;

import com.fs.audit.chain.AuditResult;
import com.fs.audit.domain.AuditFlow;
import com.fs.audit.dto.AuditRequestDTO;
import com.fs.audit.dto.CreateAuditRequestDTO;
import com.fs.audit.enums.AuditStatus;
import com.fs.audit.enums.AuditTypeEnum;
import com.fs.audit.enums.AuditUserType;
import com.fs.audit.exception.BusinessException;
import com.fs.audit.service.AuditService;
import com.fs.common.BeanCopyUtils;
import com.fs.common.config.LoginContextManager;
import com.fs.common.core.domain.entity.SysUser;
import com.fs.common.core.domain.model.LoginUser;
import com.fs.common.utils.SecurityUtils;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyUserService;
import com.fs.provider.domain.ServiceGenConfig;
import com.fs.provider.enums.ServiceOrderConfigAuditStatusEnum;
import com.fs.provider.mapper.ServiceGenConfigMapper;
import com.fs.provider.service.IServiceGenConfigService;
import com.fs.provider.vo.ServiceGenConfigAuditInfoVO;
import com.fs.provider.vo.ServiceGenConfigAuditReqVO;
import com.fs.provider.vo.ServiceGenConfigVO;
import com.fs.system.service.ISysUserService;
import com.fs.task.vo.audit_Info.AuditFlowVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 任务生成配置Service业务层处理
 *
 * @author fs
 * @date 2026-01-27
 */
@Service
public class ServiceGenConfigServiceImpl implements IServiceGenConfigService {
    @Autowired
    private ServiceGenConfigMapper serviceGenConfigMapper;

    @Autowired
    private AuditService auditService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ICompanyUserService companyUserService;

    /**
     * 查询任务生成配置
     *
     * @param id 任务生成配置主键
     * @return 任务生成配置
     */
    @Override
    public ServiceGenConfig selectServiceGenConfigById(Long id) {
        return serviceGenConfigMapper.selectServiceGenConfigById(id);
    }

    /**
     * 查询任务生成配置列表
     *
     * @param serviceGenConfig 任务生成配置
     * @return 任务生成配置
     */
    @Override
    public List<ServiceGenConfig> selectServiceGenConfigList(ServiceGenConfig serviceGenConfig) {
        return serviceGenConfigMapper.selectServiceGenConfigList(serviceGenConfig);
    }

    /**
     * 新增任务生成配置
     *
     * @param serviceGenConfig 任务生成配置
     * @return 结果
     */
    @Override
    public int insertServiceGenConfig(ServiceGenConfig serviceGenConfig) {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();

        serviceGenConfig.setCreatedAt(new Date());

        if (serviceGenConfig.getNeedAudit() == 0) {
            serviceGenConfig.setAuditStatus( ServiceOrderConfigAuditStatusEnum.NO_NEED_AUDIT.getCode());
            serviceGenConfig.setAuditInstanceId(null);
        } else {
            serviceGenConfig.setAuditStatus(ServiceOrderConfigAuditStatusEnum.WAIT_AUDIT.getCode());
            // auditInstanceId 如果你接工作流，再生成；否则先 null
            serviceGenConfig.setAuditInstanceId(null);

            //创建审核初始化
            handleAuditInit(serviceGenConfig, userId);
        }


        return serviceGenConfigMapper.insertServiceGenConfig(serviceGenConfig);
    }


    @Override
    public int companyInsertServiceGenConfig(ServiceGenConfig serviceGenConfig) {

        Long userId =  LoginContextManager.getCurrentCompanyUserId();

        serviceGenConfig.setCreatedAt(new Date());


        if (serviceGenConfig.getNeedAudit() == 0) {
            serviceGenConfig.setAuditStatus( ServiceOrderConfigAuditStatusEnum.NO_NEED_AUDIT.getCode());
            serviceGenConfig.setAuditInstanceId(null);
        } else {
            serviceGenConfig.setAuditStatus(ServiceOrderConfigAuditStatusEnum.WAIT_AUDIT.getCode());
            // auditInstanceId 如果你接工作流，再生成；否则先 null
            serviceGenConfig.setAuditInstanceId(null);
            //创建审核初始化
            handleAuditInit(serviceGenConfig, userId);
        }


        return serviceGenConfigMapper.insertServiceGenConfig(serviceGenConfig);
    }

    /**
     * 修改任务生成配置
     *
     * @param serviceGenConfig 任务生成配置
     * @return 结果
     */
    @Override
    public int updateServiceGenConfig(ServiceGenConfig serviceGenConfig) {
        serviceGenConfig.setUpdatedAt(new Date());

        return serviceGenConfigMapper.updateServiceGenConfig(serviceGenConfig);
    }

    /**
     * 批量删除任务生成配置
     *
     * @param ids 需要删除的任务生成配置主键
     * @return 结果
     */
    @Override
    public int deleteServiceGenConfigByIds(Long[] ids) {
        return serviceGenConfigMapper.deleteServiceGenConfigByIds(ids);
    }

    /**
     * 删除任务生成配置信息
     *
     * @param id 任务生成配置主键
     * @return 结果
     */
    @Override
    public int deleteServiceGenConfigById(Long id) {
        return serviceGenConfigMapper.deleteServiceGenConfigById(id);
    }

    @Transactional
    @Override
    public int audit(ServiceGenConfigAuditReqVO reqVO) {

        // ===== 1️⃣ 基础参数校验 =====
        if (reqVO == null) {
            throw new BusinessException("审核参数不能为空");
        }

        Long id = reqVO.getId();
        if (id == null) {
            throw new BusinessException("审核配置ID不能为空");
        }

        Integer targetAuditStatus = reqVO.getAuditStatus();
        if (targetAuditStatus == null) {
            throw new BusinessException("审核结果不能为空");
        }

        // 只允许 1-通过 / 2-不通过（按你之前定义的枚举）
        if (!Objects.equals(targetAuditStatus, 1) && !Objects.equals(targetAuditStatus, 2)) {
            throw new BusinessException("非法的审核状态值：" + targetAuditStatus);
        }

        // ===== 2️⃣ 当前登录用户校验 =====
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            throw new BusinessException("当前用户不存在或未登录");
        }

        // ===== 3️⃣ 查询配置 =====
        ServiceGenConfig serviceGenConfig = this.selectServiceGenConfigById(id);
        if (serviceGenConfig == null) {
            throw new BusinessException("任务生成配置不存在");
        }

        // ===== 4️⃣ 是否需要审核校验 =====
        if (!Objects.equals(serviceGenConfig.getNeedAudit(), 1)) {
            throw new BusinessException("该配置无需审核");
        }

        // ===== 5️⃣ 当前审核状态校验（防重复/越权审核）=====
        if (!Objects.equals(serviceGenConfig.getAuditStatus(), 0)) {
            throw new BusinessException("当前配置不是待审核状态，无法审核");
        }

        // ===== 6️⃣ 审核实例校验 =====
        if (serviceGenConfig.getAuditInstanceId() == null) {
            throw new BusinessException("审核实例不存在，无法执行审核");
        }

        // ===== 7️⃣ 更新审核状态（本表）=====
        serviceGenConfig.setAuditStatus(targetAuditStatus);
        this.updateServiceGenConfig(serviceGenConfig);

        // ===== 8️⃣ 调用统一审核服务 =====
        AuditRequestDTO auditRequestDTO = new AuditRequestDTO();
        auditRequestDTO.setAuditId(serviceGenConfig.getAuditInstanceId());
        auditRequestDTO.setUserId(userId);
        auditRequestDTO.setUserType(AuditUserType.SYS_USER.getCode());
        auditRequestDTO.setComment(reqVO.getAuditRemark());
        auditRequestDTO.setCompanyId(serviceGenConfig.getCompanyId());
        auditRequestDTO.setAction(targetAuditStatus);

        AuditResult auditResult = auditService.doAudit(auditRequestDTO);
        //如果审核不成功抛出异常
        if( !auditResult.isSuccess()){
            throw new BusinessException(auditResult.getMessage());
        }

        return 1;
    }


    @Override
    public int companyAudit(ServiceGenConfigAuditReqVO reqVO) {

        // ===== 1️⃣ 基础参数校验 =====
        if (reqVO == null) {
            throw new BusinessException("审核参数不能为空");
        }

        Long id = reqVO.getId();
        if (id == null) {
            throw new BusinessException("审核配置ID不能为空");
        }

        Integer targetAuditStatus = reqVO.getAuditStatus();
        if (targetAuditStatus == null) {
            throw new BusinessException("审核结果不能为空");
        }

        // 只允许 1-通过 / 2-不通过（按你之前定义的枚举）
        if (!Objects.equals(targetAuditStatus, 1) && !Objects.equals(targetAuditStatus, 2)) {
            throw new BusinessException("非法的审核状态值：" + targetAuditStatus);
        }

        // ===== 2️⃣ 当前登录用户校验 =====
        Long userId = LoginContextManager.getCurrentCompanyUserId();
        if (userId == null) {
            throw new BusinessException("当前用户不存在或未登录");
        }

        // ===== 3️⃣ 查询配置 =====
        ServiceGenConfig serviceGenConfig = this.selectServiceGenConfigById(id);
        if (serviceGenConfig == null) {
            throw new BusinessException("任务生成配置不存在");
        }

        // ===== 4️⃣ 是否需要审核校验 =====
        if (!Objects.equals(serviceGenConfig.getNeedAudit(), 1)) {
            throw new BusinessException("该配置无需审核");
        }

        // ===== 5️⃣ 当前审核状态校验（防重复/越权审核）=====
        if (!Objects.equals(serviceGenConfig.getAuditStatus(), 0)) {
            throw new BusinessException("当前配置不是待审核状态，无法审核");
        }

        // ===== 6️⃣ 审核实例校验 =====
        if (serviceGenConfig.getAuditInstanceId() == null) {
            throw new BusinessException("审核实例不存在，无法执行审核");
        }

        // ===== 7️⃣ 更新审核状态（本表）=====
        serviceGenConfig.setAuditStatus(targetAuditStatus);
        this.updateServiceGenConfig(serviceGenConfig);

        // ===== 8️⃣ 调用统一审核服务 =====
        AuditRequestDTO auditRequestDTO = new AuditRequestDTO();
        auditRequestDTO.setAuditId(serviceGenConfig.getAuditInstanceId());
        auditRequestDTO.setUserId(userId);
        auditRequestDTO.setUserType(AuditUserType.COMPANY_USER.getCode());
        auditRequestDTO.setComment(reqVO.getAuditRemark());
        auditRequestDTO.setCompanyId(serviceGenConfig.getCompanyId());
        auditRequestDTO.setAction(targetAuditStatus);

        AuditResult auditResult = auditService.doAudit(auditRequestDTO);
        //如果审核不成功抛出异常
        if( !auditResult.isSuccess()){
            throw new BusinessException(auditResult.getMessage());
        }

        return 1;
    }

    /**
     * 任务的创建审核初始化处理器
     *
     * @param serviceGenConfig
     * @param userId
     */
    private void handleAuditInit(ServiceGenConfig serviceGenConfig, Long userId) {
        CreateAuditRequestDTO createAuditRequestDTO = new CreateAuditRequestDTO();
        createAuditRequestDTO.setBusinessId(serviceGenConfig.getId());
        createAuditRequestDTO.setBusinessType(AuditTypeEnum.AUDIT_FWDRWSCPZ.getCode());
        createAuditRequestDTO.setTempCode(AuditTypeEnum.AUDIT_FWDRWSCPZ.getCode());
        createAuditRequestDTO.setInitiatorId(userId);
        createAuditRequestDTO.setCompanyId(1L);
        createAuditRequestDTO.setCompanyId(serviceGenConfig.getCompanyId());
        Long finishAuditInstanceId = auditService.createAudit(createAuditRequestDTO);
        serviceGenConfig.setAuditInstanceId(finishAuditInstanceId);
    }


    @Override
    public ServiceGenConfigAuditInfoVO getAuditInfoById(Long id) {
        ServiceGenConfigAuditInfoVO serviceGenConfigAuditInfoVO = new ServiceGenConfigAuditInfoVO();
        ServiceGenConfig serviceGenConfig = this.selectServiceGenConfigById(id);
        ServiceGenConfigVO serviceGenConfigVO = BeanCopyUtils.copy(serviceGenConfig, ServiceGenConfigVO.class);
        serviceGenConfigAuditInfoVO.setServiceGenConfigVO(serviceGenConfigVO);
        //审核流水
        // 获取审核流程
        Long auditInstanceId = serviceGenConfig.getAuditInstanceId();
        List<AuditFlow> auditFlows = auditService.getAuditFlows(auditInstanceId);
        List<AuditFlowVO> auditFlowVOS = BeanCopyUtils.copyList(auditFlows, AuditFlowVO.class);

        for (AuditFlowVO auditFlowVO : auditFlowVOS) {

            // 1) 审核状态中文
            auditFlowVO.setStatusName(AuditStatus.fromCode(auditFlowVO.getStatus()).getDesc());

            // 2) 审核用户类型：Integer -> enum（避免 magic number / hashCode）
            AuditUserType userType = AuditUserType.fromCode(auditFlowVO.getAuditUserType());

            // 3) 根据类型查用户
            Long auditUserId = auditFlowVO.getAuditUserId();
            if (auditUserId == null) {
                auditFlowVO.setAuditUserName("-");
                continue;
            }

            if (userType.isSysUser()) {
                SysUser sysUser = sysUserService.selectUserById(auditUserId);
                auditFlowVO.setAuditUserName(sysUser != null ? sysUser.getUserName() : "-");
            } else {
                CompanyUser companyUser = companyUserService.selectCompanyUserById(auditUserId);
                auditFlowVO.setAuditUserName(companyUser != null ? companyUser.getUserName() : "-");
            }
        }
        serviceGenConfigAuditInfoVO.setAuditFlowVOList(auditFlowVOS);

        return serviceGenConfigAuditInfoVO;
    }


    @Override
    public List<ServiceGenConfig> selectDueConfigs(LocalTime startTime, LocalTime endTime, LocalDate today) {
        if (startTime == null || endTime == null || today == null) {
            return Collections.emptyList();
        }
        // 今天周几：1=周一 ... 7=周日（和你 frequency_value 的定义一致）
        int dow = today.getDayOfWeek().getValue();
        int dom = today.getDayOfMonth();

        // 是否跨天窗口：比如 23:59:30 -> 00:00:30
        boolean crossDay = startTime.isAfter(endTime);


        return serviceGenConfigMapper.selectDueConfigs(startTime, endTime, dow, dom, crossDay);

    }
}
