package com.hotwj.platform.securityManagement.securityMeetingAttendee.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.flow.domain.SysFlowInstance;
import com.hotwj.platform.flow.domain.SysFlowTask;
import com.hotwj.platform.flow.service.ISysFlowService;
import com.hotwj.platform.integration.ocr.SignatureVerifyService;
import com.hotwj.platform.securityManagement.securityMeeting.domain.HotSecurityMeeting;
import com.hotwj.platform.securityManagement.securityMeeting.mapper.HotSecurityMeetingMapper;
import com.hotwj.platform.securityManagement.securityMeetingAttendee.domain.HotSecurityMeetingAttendee;
import com.hotwj.platform.securityManagement.securityMeetingAttendee.domain.bo.HotSecurityMeetingAttendeeBo;
import com.hotwj.platform.securityManagement.securityMeetingAttendee.domain.bo.HotSecurityMeetingMyQueryBo;
import com.hotwj.platform.securityManagement.securityMeetingAttendee.domain.vo.HotSecurityMeetingAttendeeVo;
import com.hotwj.platform.securityManagement.securityMeetingAttendee.domain.vo.HotSecurityMeetingMyVo;
import com.hotwj.platform.securityManagement.securityMeetingAttendee.mapper.HotSecurityMeetingAttendeeMapper;
import com.hotwj.platform.securityManagement.securityMeetingAttendee.service.IHotSecurityMeetingAttendeeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.model.LoginUser;
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.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 会议参会人员详情Service业务层处理
 *
 * @author shihongwei
 * @date 2026-02-03
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotSecurityMeetingAttendeeServiceImpl implements IHotSecurityMeetingAttendeeService {

    private final HotSecurityMeetingAttendeeMapper baseMapper;
    private final ISysFlowService flowService;
    private final HotSecurityMeetingMapper meetingMapper;
    private final SignatureVerifyService signatureVerifyService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean completeSign(String taskId, Long photoOssId, Long signOssId) {
        // 1. 获取任务详情
        SysFlowTask task = flowService.getTaskById(taskId);
        if (task == null) {
            throw new ServiceException("任务不存在");
        }

        // 2. 校验权限
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser != null && !task.getApproverId().equals(String.valueOf(loginUser.getBusinessUserId()))) {
            throw new ServiceException("无权操作此任务");
        }

        // 3. 获取会议ID (BusinessId)
        SysFlowInstance instance = flowService.getInstanceByTaskId(taskId);
        if (instance == null) {
            throw new ServiceException("流程实例不存在");
        }
        Long meetingId = Long.valueOf(instance.getBusinessId());
        String personId = task.getApproverId();

        // 4. 校验参数
        if (photoOssId == null) {
            throw new ServiceException("请上传参会照片");
        }
        if (signOssId == null) {
            throw new ServiceException("请上传签名");
        }

        // 4.1 校验会议开始时间（预定会议未到开始时间不可参会）
        HotSecurityMeeting meeting = meetingMapper.selectById(meetingId);
        if (meeting == null) {
            throw new ServiceException("会议不存在");
        }
        Date now = new Date();
        Date startTime = meeting.getStartTime();
        if (startTime == null || now.before(startTime)) {
            throw new ServiceException("会议尚未开始，不能参会");
        }

        // 5. 更新参会人员记录
        // 查找记录
        HotSecurityMeetingAttendee attendee = baseMapper.selectOne(
                Wrappers.<HotSecurityMeetingAttendee>lambdaQuery()
                        .eq(HotSecurityMeetingAttendee::getMeetingId, meetingId)
                        .eq(HotSecurityMeetingAttendee::getPersonId, personId)
                        .last("limit 1")
        );

        if (attendee == null) {
            // 尝试仅通过meetingId和创建者(如果personId不对)？ 不，必须匹配personId
            // 如果找不到，可能是数据不一致
            throw new ServiceException("参会人员记录不存在");
        }
        if (DriverLoginContextHelper.isDriverPort() && signOssId != null) {
            if (StringUtils.isBlank(attendee.getName())) {
                throw new ServiceException("参会人员姓名不能为空");
            }
            signatureVerifyService.validateSelfSignature(signOssId, attendee.getName());
        }

        attendee.setAttendeePhotoOssId(photoOssId);
        attendee.setAttendeeSignOssId(signOssId);
        attendee.setFinishTime(new Date());
        baseMapper.updateById(attendee);

        // 6. 完成待办任务
        flowService.audit(taskId, true, "签到完成", personId);

        return true;
    }

    /**
     * 查询我的会议列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 结果
     */
    @Override
    public TableDataInfo<HotSecurityMeetingMyVo> queryMyMeetingList(HotSecurityMeetingMyQueryBo bo, PageQuery pageQuery) {
        String personId = String.valueOf(LoginHelper.getBusinessUserId());
        Page<HotSecurityMeetingMyVo> page = baseMapper.selectMyMeetingList(pageQuery.build(), personId, bo.getStatus());
        return TableDataInfo.build(page);
    }

    /**
     * 查询会议参会人员详情
     *
     * @param id 主键
     * @return 会议参会人员详情
     */
    @Override
    public HotSecurityMeetingAttendeeVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询会议参会人员详情列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 会议参会人员详情分页列表
     */
    @Override
    public TableDataInfo<HotSecurityMeetingAttendeeVo> queryPageList(HotSecurityMeetingAttendeeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotSecurityMeetingAttendee> lqw = buildQueryWrapper(bo);
        Page<HotSecurityMeetingAttendeeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的会议参会人员详情列表
     *
     * @param bo 查询条件
     * @return 会议参会人员详情列表
     */
    @Override
    public List<HotSecurityMeetingAttendeeVo> queryList(HotSecurityMeetingAttendeeBo bo) {
        LambdaQueryWrapper<HotSecurityMeetingAttendee> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotSecurityMeetingAttendee> buildQueryWrapper(HotSecurityMeetingAttendeeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotSecurityMeetingAttendee> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(HotSecurityMeetingAttendee::getId);
        lqw.eq(bo.getCompanyId() != null, HotSecurityMeetingAttendee::getCompanyId, bo.getCompanyId());
        lqw.eq(StringUtils.isNotBlank(bo.getPersonId()), HotSecurityMeetingAttendee::getPersonId, bo.getPersonId());
        lqw.eq(bo.getMeetingId() != null, HotSecurityMeetingAttendee::getMeetingId, bo.getMeetingId());
        lqw.eq(bo.getAttendeePhotoOssId() != null, HotSecurityMeetingAttendee::getAttendeePhotoOssId, bo.getAttendeePhotoOssId());
        lqw.eq(bo.getAttendeeSignOssId() != null, HotSecurityMeetingAttendee::getAttendeeSignOssId, bo.getAttendeeSignOssId());
        lqw.eq(bo.getFinishTime() != null, HotSecurityMeetingAttendee::getFinishTime, bo.getFinishTime());
        lqw.like(StringUtils.isNotBlank(bo.getCreateByName()), HotSecurityMeetingAttendee::getCreateByName, bo.getCreateByName());
        lqw.like(StringUtils.isNotBlank(bo.getUpdateByName()), HotSecurityMeetingAttendee::getUpdateByName, bo.getUpdateByName());
        lqw.eq(bo.getIsDeleted() != null, HotSecurityMeetingAttendee::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增会议参会人员详情
     *
     * @param bo 会议参会人员详情
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotSecurityMeetingAttendeeBo bo) {
        HotSecurityMeetingAttendee add = MapstructUtils.convert(bo, HotSecurityMeetingAttendee.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改会议参会人员详情
     *
     * @param bo 会议参会人员详情
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotSecurityMeetingAttendeeBo bo) {
        HotSecurityMeetingAttendee update = MapstructUtils.convert(bo, HotSecurityMeetingAttendee.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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