package com.hotwj.platform.securityManagement.hiddenDangerInspection.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotwj.platform.common.helper.DriverLoginContextHelper;
import com.hotwj.platform.driverManagement.driver.domain.HotDriver;
import com.hotwj.platform.flow.service.ISysFlowService;
import com.hotwj.platform.integration.ocr.SignatureVerifyService;
import com.hotwj.platform.noticeManagerment.systemNotification.domain.bo.HotSystemNotificationGroupBo;
import com.hotwj.platform.noticeManagerment.systemNotification.service.IHotSystemNotificationService;
import com.hotwj.platform.securityManagement.hiddenDangerInspection.domain.HotHiddenDangerInspection;
import com.hotwj.platform.securityManagement.hiddenDangerInspection.domain.bo.HotHiddenDangerInspectionBo;
import com.hotwj.platform.securityManagement.hiddenDangerInspection.domain.vo.HotHiddenDangerInspectionVo;
import com.hotwj.platform.securityManagement.hiddenDangerInspection.mapper.HotHiddenDangerInspectionMapper;
import com.hotwj.platform.securityManagement.hiddenDangerInspection.service.IHotHiddenDangerInspectionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.YearMonth;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 隐患排查-排查项目Service业务层处理
 *
 * @author shihongwei
 * @date 2025-12-31
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotHiddenDangerInspectionServiceImpl implements IHotHiddenDangerInspectionService {

    private final HotHiddenDangerInspectionMapper baseMapper;
    private final ISysFlowService flowService;
    private final IHotSystemNotificationService notificationService;
    private final SignatureVerifyService signatureVerifyService;

    /**
     * 查询隐患排查-排查项目
     *
     * @param id 主键
     * @return 隐患排查-排查项目
     */
    @Override
    public HotHiddenDangerInspectionVo queryById(Long id) {
        HotHiddenDangerInspectionVo vo = baseMapper.selectVoById(id);
        if (vo != null && StringUtils.isNotBlank(vo.getInstanceId())) {
            String userId = LoginHelper.getBusinessUserId();
            vo.setTaskId(flowService.getTaskId(vo.getInstanceId(), userId));
        }
        return vo;
    }

    /**
     * 分页查询隐患排查-排查项目列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 隐患排查-排查项目分页列表
     */
    @Override
    public TableDataInfo<HotHiddenDangerInspectionVo> queryPageList(HotHiddenDangerInspectionBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotHiddenDangerInspection> lqw = buildQueryWrapper(bo);
        Page<HotHiddenDangerInspectionVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        fillFlowExtras(result.getRecords());

        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<HotHiddenDangerInspectionVo> queryMobilePlanPage(String keyword, PageQuery pageQuery) {
        Long companyId = LoginHelper.getCompanyId();
        if (companyId == null) {
            throw new ServiceException("当前登录用户无公司信息");
        }
        boolean isDriver = DriverLoginContextHelper.isDriverPort();
        String driverId = null;
        String vehicleId = null;
        if (isDriver) {
            HotDriver driver = DriverLoginContextHelper.getCurrentDriver();
            driverId = driver.getId();
            vehicleId = driver.getVehicleId();
        }
        String currentMonth = YearMonth.now().toString();
        Page<HotHiddenDangerInspectionVo> page = pageQuery.build();
        List<HotHiddenDangerInspectionVo> rows = baseMapper.selectMobilePlanPage(
                page,
                companyId,
                !isDriver,
                driverId,
                vehicleId,
                StringUtils.trimToNull(keyword),
                currentMonth
        );
        page.setRecords(rows);
        fillFlowExtras(rows);
        return TableDataInfo.build(page);
    }

    /**
     * 查询符合条件的隐患排查-排查项目列表
     *
     * @param bo 查询条件
     * @return 隐患排查-排查项目列表
     */
    @Override
    public List<HotHiddenDangerInspectionVo> queryList(HotHiddenDangerInspectionBo bo) {
        LambdaQueryWrapper<HotHiddenDangerInspection> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotHiddenDangerInspection> buildQueryWrapper(HotHiddenDangerInspectionBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotHiddenDangerInspection> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(HotHiddenDangerInspection::getId);
        lqw.eq(bo.getCompanyId() != null, HotHiddenDangerInspection::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getPlanId() != null, HotHiddenDangerInspection::getPlanId, bo.getPlanId());
        lqw.like(StringUtils.isNotBlank(bo.getProjectName()), HotHiddenDangerInspection::getProjectName, bo.getProjectName());
        lqw.eq(StringUtils.isNotBlank(bo.getProjectId()), HotHiddenDangerInspection::getProjectId, bo.getProjectId());
        lqw.eq(StringUtils.isNotBlank(bo.getCheckContentJson()), HotHiddenDangerInspection::getCheckContentJson, bo.getCheckContentJson());
        lqw.eq(StringUtils.isNotBlank(bo.getDangerDesc()), HotHiddenDangerInspection::getDangerDesc, bo.getDangerDesc());
        lqw.eq(StringUtils.isNotBlank(bo.getAttachmentUrl()), HotHiddenDangerInspection::getAttachmentUrl, bo.getAttachmentUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getCheckerId()), HotHiddenDangerInspection::getCheckerId, bo.getCheckerId());
        lqw.like(StringUtils.isNotBlank(bo.getCheckerName()), HotHiddenDangerInspection::getCheckerName, bo.getCheckerName());
        if (StringUtils.isNotBlank(bo.getKeyword())) {
            String keyword = bo.getKeyword().trim();
            lqw.like(HotHiddenDangerInspection::getProjectName, keyword);
        }
        lqw.eq(bo.getCheckDate() != null, HotHiddenDangerInspection::getCheckDate, bo.getCheckDate());
        lqw.eq(bo.getApproverId() != null, HotHiddenDangerInspection::getApproverId, bo.getApproverId());
        lqw.like(StringUtils.isNotBlank(bo.getApproverName()), HotHiddenDangerInspection::getApproverName, bo.getApproverName());
        lqw.eq(bo.getStatus() != null, HotHiddenDangerInspection::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getSignImgUrl()), HotHiddenDangerInspection::getSignImgUrl, bo.getSignImgUrl());
        lqw.eq(bo.getIsDeleted() != null, HotHiddenDangerInspection::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    private void fillFlowExtras(List<HotHiddenDangerInspectionVo> records) {
        if (records == null || records.isEmpty()) {
            return;
        }
        String userId = LoginHelper.getBusinessUserId();
        for (HotHiddenDangerInspectionVo vo : records) {
            if (vo == null) {
                continue;
            }
            if (StringUtils.isNotBlank(vo.getInstanceId())) {
                vo.setTaskId(flowService.getTaskId(vo.getInstanceId(), userId));
            }
            if (StringUtils.isBlank(vo.getFlowStatus())) {
                if (vo.getStatus() == null || vo.getStatus() == 0L) {
                    vo.setFlowStatus("TODO");
                } else if (vo.getStatus() == 3L || vo.getStatus() == 9L) {
                    vo.setFlowStatus("DONE");
                } else {
                    vo.setFlowStatus("PROCESSING");
                }
            }
        }
    }

    /**
     * 新增隐患排查-排查项目
     *
     * @param bo 隐患排查-排查项目
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotHiddenDangerInspectionBo bo) {
        HotHiddenDangerInspection add = MapstructUtils.convert(bo, HotHiddenDangerInspection.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改隐患排查-排查项目
     *
     * @param bo 隐患排查-排查项目
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotHiddenDangerInspectionBo bo) {
        HotHiddenDangerInspection original = baseMapper.selectById(bo.getId());
        HotHiddenDangerInspection update = MapstructUtils.convert(bo, HotHiddenDangerInspection.class);
        validEntityBeforeSave(update);
        String signImgUrl = bo.getSignImgUrl();
        if (DriverLoginContextHelper.isDriverPort() && StringUtils.isNotBlank(signImgUrl)) {
            String checkerName = bo.getCheckerName();

            if (original == null || StringUtils.isBlank(checkerName)) {
                throw new ServiceException("排查人姓名不能为空");
            }
            signatureVerifyService.validateSelfSignature(parseSignatureOssId(signImgUrl), checkerName);
        }
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag && (original == null || StringUtils.isBlank(original.getInstanceId()))) {
            String initiator = String.valueOf(LoginHelper.getBusinessUserId());
            String approverId = bo.getApproverId() != null ? String.valueOf(bo.getApproverId()) : null;
            if (StringUtils.isBlank(approverId)) {
                throw new ServiceException("请选择审核人");
            }
            String instanceId = flowService.startFlow(
                    "HIDDEN_DANGER_CHECK",
                    String.valueOf(update.getId()),
                    update.getCompanyId(),
                    initiator,
                    approverId
            );
            update.setInstanceId(instanceId);
            update.setFlowStatus("SUBMITTED");
            baseMapper.updateById(update);

            try {
                HotSystemNotificationGroupBo bos = new HotSystemNotificationGroupBo();
                bos.setLevel("普通");
                bos.setContent("你有一条隐患排查需要处理。");
                bos.setSourceType("隐患管理");
                bos.setSenderType("SYSTEM");
                bos.setReceiverType("管理员");
                bos.setReceiverIds(java.util.Collections.singletonList(approverId));
                bos.setIsDeleted(0L);
                notificationService.insertByBo(bos);
            } catch (Exception e) {
                log.warn("Hidden danger inspection assign notify failed approverId={} inspectionId={}", approverId, update.getId(), e);
            }
        }
        return flag;
    }

    private Long parseSignatureOssId(String signImgUrl) {
        String first = signImgUrl.split(",")[0].trim();
        if (!first.matches("^\\d+$")) {
            throw new ServiceException("签名文件格式错误");
        }
        return Long.parseLong(first);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void audit(HotHiddenDangerInspectionBo bo) {
        // 1. 校验参数
        if (bo.getTaskId() == null) {
            throw new ServiceException("流程任务ID不能为空");
        }

        // 2. 更新业务数据
        HotHiddenDangerInspection update = MapstructUtils.convert(bo, HotHiddenDangerInspection.class);
        boolean flag = baseMapper.updateById(update) > 0;

        if (flag) {
            // 4. 完成流程任务
            // 如果有隐患，我们认为流程是"驳回"的（需要整改）
            boolean auditPass = bo.getAuditHasDanger() != null && bo.getAuditHasDanger() == 0L;
            flowService.audit(
                    bo.getTaskId(),
                    auditPass,
                    bo.getAuditConclusion(),
                    LoginHelper.getBusinessUserId()
            );
        }
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HotHiddenDangerInspection entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除隐患排查-排查项目信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
