package com.hotwj.platform.config.squareInfo.service.impl;

import cn.hutool.core.date.DateUtil;
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.config.squareInfo.domain.HotSquareInfo;
import com.hotwj.platform.config.squareInfo.domain.bo.HotSquareInfoBo;
import com.hotwj.platform.config.squareInfo.domain.vo.HotSquareInfoVo;
import com.hotwj.platform.config.squareInfo.mapper.HotSquareInfoMapper;
import com.hotwj.platform.config.squareInfo.service.IHotSquareInfoService;
import com.hotwj.platform.driverManagement.driver.domain.HotDriver;
import com.hotwj.platform.driverManagement.driver.mapper.HotDriverMapper;
import com.hotwj.platform.noticeManagerment.systemNotification.domain.bo.HotSystemNotificationGroupBo;
import com.hotwj.platform.noticeManagerment.systemNotification.service.IHotSystemNotificationService;
import com.hotwj.platform.resourceManagement.companySafetyManager.domain.HotCompanySafetyManager;
import com.hotwj.platform.resourceManagement.companySafetyManager.mapper.HotCompanySafetyManagerMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 广场信息Service业务层处理
 *
 * @author shihongwei
 * @date 2026-01-29
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotSquareInfoServiceImpl implements IHotSquareInfoService {

    private final HotSquareInfoMapper baseMapper;
    private final IHotSystemNotificationService notificationService;
    private final HotCompanySafetyManagerMapper companySafetyManagerMapper;
    private final HotDriverMapper driverMapper;

    /**
     * 查询广场信息
     *
     * @param id 主键
     * @return 广场信息
     */
    @Override
    public HotSquareInfoVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询广场信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 广场信息分页列表
     */
    @Override
    public TableDataInfo<HotSquareInfoVo> queryPageList(HotSquareInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotSquareInfo> lqw = buildQueryWrapper(bo);
        Page<HotSquareInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的广场信息列表
     *
     * @param bo 查询条件
     * @return 广场信息列表
     */
    @Override
    public List<HotSquareInfoVo> queryList(HotSquareInfoBo bo) {
        LambdaQueryWrapper<HotSquareInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotSquareInfo> buildQueryWrapper(HotSquareInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        Object beginCreateTime = params.get("beginCreateTime");
        Object endCreateTime = params.get("endCreateTime");
        LambdaQueryWrapper<HotSquareInfo> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(HotSquareInfo::getId);
        lqw.eq(bo.getCompanyId() != null, HotSquareInfo::getCompanyId, bo.getCompanyId());
        lqw.like(StringUtils.isNotBlank(bo.getTitle()), HotSquareInfo::getTitle, bo.getTitle());
        lqw.like(StringUtils.isNotBlank(bo.getContent()), HotSquareInfo::getContent, bo.getContent());
        lqw.eq(StringUtils.isNotBlank(bo.getImageOssIds()), HotSquareInfo::getImageOssIds, bo.getImageOssIds());
        lqw.like(StringUtils.isNotBlank(bo.getContactName()), HotSquareInfo::getContactName, bo.getContactName());
        lqw.eq(StringUtils.isNotBlank(bo.getContactPhone()), HotSquareInfo::getContactPhone, bo.getContactPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getPublisherPhone()), HotSquareInfo::getPublisherPhone, bo.getPublisherPhone());
        lqw.eq(bo.getPublisherType() != null, HotSquareInfo::getPublisherType, bo.getPublisherType());
        lqw.eq(bo.getAuditStatus() != null, HotSquareInfo::getAuditStatus, bo.getAuditStatus());
        lqw.eq(bo.getAuditResult() != null, HotSquareInfo::getAuditResult, bo.getAuditResult());
        lqw.eq(StringUtils.isNotBlank(bo.getAuditRemark()), HotSquareInfo::getAuditRemark, bo.getAuditRemark());
        lqw.like(StringUtils.isNotBlank(bo.getCreateByName()), HotSquareInfo::getCreateByName, bo.getCreateByName());
        lqw.like(StringUtils.isNotBlank(bo.getUpdateByName()), HotSquareInfo::getUpdateByName, bo.getUpdateByName());
        lqw.eq(bo.getIsDeleted() != null, HotSquareInfo::getIsDeleted, bo.getIsDeleted());
        lqw.eq(bo.getCreateBy() != null, HotSquareInfo::getCreateBy, bo.getCreateBy());
        lqw.ge(beginCreateTime != null, HotSquareInfo::getCreateTime, beginCreateTime);
        if (endCreateTime != null) {
            Date endDate = endCreateTime instanceof Date ? (Date) endCreateTime : DateUtil.parse(endCreateTime.toString());
            lqw.lt(HotSquareInfo::getCreateTime, DateUtil.offsetDay(endDate, 1));
        }
        return lqw;
    }

    /**
     * 新增广场信息
     *
     * @param bo 广场信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotSquareInfoBo bo) {
        HotSquareInfo add = MapstructUtils.convert(bo, HotSquareInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改广场信息
     *
     * @param bo 广场信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotSquareInfoBo bo) {
        HotSquareInfo old = null;
        if (bo.getId() != null) {
            old = baseMapper.selectById(bo.getId());
        }
        HotSquareInfo update = MapstructUtils.convert(bo, HotSquareInfo.class);
        validEntityBeforeSave(update);
        boolean updated = baseMapper.updateById(update) > 0;
        if (updated) {
            sendAuditNotificationIfNeeded(old, bo);
        }
        return updated;
    }

    private void sendAuditNotificationIfNeeded(HotSquareInfo old, HotSquareInfoBo bo) {
        if (bo == null || bo.getId() == null || bo.getAuditStatus() == null) {
            return;
        }
        Long newAuditStatus = bo.getAuditStatus();
        if (!Long.valueOf(1L).equals(newAuditStatus) && !Long.valueOf(2L).equals(newAuditStatus)) {
            return;
        }
        Long oldAuditStatus = old == null ? null : old.getAuditStatus();
        if (newAuditStatus.equals(oldAuditStatus)) {
            return;
        }

        String receiverType;
        String receiverId = null;
        Long publisherType = bo.getPublisherType() != null ? bo.getPublisherType() : (old == null ? null : old.getPublisherType());
        String publisherPhone = StringUtils.isNotBlank(bo.getPublisherPhone()) ? bo.getPublisherPhone() : (old == null ? null : old.getPublisherPhone());
        Long companyId = bo.getCompanyId() != null ? bo.getCompanyId() : (old == null ? null : old.getCompanyId());

        if (Long.valueOf(1L).equals(publisherType)) {
            receiverType = "管理员";
            if (StringUtils.isNotBlank(publisherPhone)) {
                HotCompanySafetyManager manager = companySafetyManagerMapper.selectOne(
                        Wrappers.<HotCompanySafetyManager>lambdaQuery()
                                .eq(HotCompanySafetyManager::getPhone, publisherPhone)
                                .eq(companyId != null, HotCompanySafetyManager::getCompanyId, companyId)
                                .eq(HotCompanySafetyManager::getIsDeleted, 0L)
                                .eq(HotCompanySafetyManager::getIsResigned, 0L)
                                .eq(HotCompanySafetyManager::getStatus, 1L)
                                .last("limit 1")
                );
                if (manager != null && manager.getId() != null) {
                    receiverId = String.valueOf(manager.getId());
                }
            }
        } else {
            receiverType = "驾驶员";
            if (StringUtils.isNotBlank(publisherPhone)) {
                HotDriver driver = driverMapper.selectOne(
                        Wrappers.<HotDriver>lambdaQuery()
                                .eq(HotDriver::getPhone, publisherPhone)
                                .eq(companyId != null, HotDriver::getCompanyId, companyId)
                                .eq(HotDriver::getIsDeleted, 0L)
                                .last("limit 1")
                );
                if (driver != null && StringUtils.isNotBlank(driver.getId())) {
                    receiverId = driver.getId();
                }
            }
        }

        if (StringUtils.isBlank(receiverId)) {
            log.warn("广场信息审核通知发送失败，未匹配到接收人 squareInfoId={} publisherType={} publisherPhone={} companyId={}",
                    bo.getId(), publisherType, publisherPhone, companyId);
            return;
        }

        String title = StringUtils.isNotBlank(bo.getTitle()) ? bo.getTitle() : (old == null ? "广场信息" : StringUtils.blankToDefault(old.getTitle(), "广场信息"));
        String content;
        if (Long.valueOf(1L).equals(newAuditStatus)) {
            content = "您发布的广场信息《" + title + "》已审核通过并发布。";
        } else {
            String remark = StringUtils.isNotBlank(bo.getAuditRemark()) ? bo.getAuditRemark() : (old == null ? null : old.getAuditRemark());
            content = StringUtils.isNotBlank(remark)
                    ? "您发布的广场信息《" + title + "》审核未通过，原因：" + remark + "。"
                    : "您发布的广场信息《" + title + "》审核未通过。";
        }

        HotSystemNotificationGroupBo notifyBo = new HotSystemNotificationGroupBo();
        notifyBo.setLevel("普通");
        notifyBo.setContent(content);
        notifyBo.setSourceType("广场信息");
        notifyBo.setSenderType("SYSTEM");
        notifyBo.setReceiverType(receiverType);
        notifyBo.setReceiverId(receiverId);
        notifyBo.setIsDeleted(0L);
        try {
            notificationService.insertByBo(notifyBo);
        } catch (Exception e) {
            log.warn("广场信息审核通知发送异常 squareInfoId={} receiverType={} receiverId={}", bo.getId(), receiverType, receiverId, e);
        }
    }

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

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