package com.leromro.core.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leromro.common.core.domain.AjaxResult;
import com.leromro.common.core.redis.RedisCache;
import com.leromro.common.enums.ConstantsKey;
import com.leromro.common.exception.ServiceException;
import com.leromro.common.utils.SecurityUtils;
import com.leromro.core.domain.BusinessManagement;
import com.leromro.core.domain.BusinessPrice;
import com.leromro.core.domain.VolunteerInfo;
import com.leromro.core.domain.dto.VolunteerInfoDTO;
import com.leromro.core.domain.vo.VolunteerInfoDetailVO;
import com.leromro.core.domain.vo.VolunteerInfoVO;
import com.leromro.core.mapper.VolunteerInfoMapper;
import com.leromro.core.service.IBusinessManagementService;
import com.leromro.core.service.IBusinessPriceService;
import com.leromro.core.service.IVolunteerInfoService;
import com.leromro.core.utils.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 志愿者信息表 服务实现类
 * </p>
 *
 * @author lr
 * @since 2025-04-07
 */
@Service
public class VolunteerInfoServiceImpl extends ServiceImpl<VolunteerInfoMapper, VolunteerInfo> implements IVolunteerInfoService {

    @Autowired
    private VolunteerInfoMapper volunteerInfoMapper;

    @Autowired
    private IBusinessManagementService businessManagementService;

    @Autowired
    private IBusinessPriceService businessPriceService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 新增志愿者信息
     * @param dto
     * @param serviceCategory
     */
    @Override
    public void newVolunteerInfoByuserId(VolunteerInfoDTO dto, Long serviceCategory) {
        VolunteerInfo volunteerInfo = BeanUtil.copyProperties(dto, VolunteerInfo.class);
        Long userId = SecurityUtils.getUserId();
        //查询业务管理信息
        BusinessManagement businessManagement = businessManagementService.getOne(new LambdaQueryWrapper<BusinessManagement>()
                .eq(BusinessManagement::getBusinessManagementId, volunteerInfo.getBusinessManagementId()));
        if (StrUtil.isBlank(businessManagement.getBusinessTierName()) || businessManagement.getBusinessTierName().length() < 2){
            throw new RuntimeException("当前服务项目层级名称错误");
        }
        //把BusinessTierName按照-分割
        String[] businessTierName = businessManagement.getBusinessTierName().split("-");
        volunteerInfo.setProjectName(businessTierName[0]);
        volunteerInfo.setProjectTypeName(businessTierName[1]);
        switch(Integer.parseInt(String.valueOf(serviceCategory))) {
            case 1:
                break;
            case 2:
                volunteerInfo.setServiceSubjectName(businessTierName[2]);
                break;
            default:
                throw new RuntimeException("当前服务项目层级名称错误");
        }

        volunteerInfo.setVolunteerId(userId);
        volunteerInfo.setServiceCategory(serviceCategory);
        volunteerInfo.setCreateTime(DateTimeUtil.getNowTime());
        QueryWrapper<VolunteerInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("volunteer_id",userId).eq("service_category",serviceCategory);
        wrapper.ne(ObjectUtil.isNotNull(volunteerInfo.getVolunteerInfoId()),"volunteer_info_id",volunteerInfo.getVolunteerInfoId());

        Integer i = volunteerInfoMapper.selectCount(wrapper);
        if(i>0){
            throw new RuntimeException("此用户已有志愿者信息，不可重复创建，请前往修改");
        }
        if (ObjectUtil.isNull(volunteerInfo.getVolunteerInfoId())) {
            //新增，则校验手机号
            String redisCode = this.redisCache.getCacheObject(ConstantsKey.REDIS_PHONE_CODE.getKey() + "_" + volunteerInfo.getPhonenumber());
            if (StrUtil.isBlank(redisCode)) {
                throw new ServiceException("验证码已过期");
            }
            if (StrUtil.isBlank(dto.getCode())){
                throw new ServiceException("验证码不能为空");
            }
            if (!redisCode.equals(dto.getCode())) {
                throw new ServiceException("验证码错误");
            }
            this.save(volunteerInfo);
        }else {
            volunteerInfo.setAppStatus("1");
            volunteerInfoMapper.updateById(volunteerInfo);
        }

    }

    /**
     * 志愿者注册信息回显
     * @param serviceCategory
     * @param userId
     * @return
     */
    @Override
    public VolunteerInfo selectByUserID(Long serviceCategory, Long userId) {
        QueryWrapper<VolunteerInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("volunteer_id",userId).eq("service_category",serviceCategory);
        VolunteerInfo infos = volunteerInfoMapper.selectOne(wrapper);
        return infos;
    }

    /**     后台web页面志愿者列表
     * @param dto
     * @return
     */
    @Override
    public List<VolunteerInfo> webList(VolunteerInfoDTO dto) {
        List<VolunteerInfo> infos = volunteerInfoMapper.webList(dto);
        return infos;
    }
    /**     小程序用户志愿者列表
     * @param volunteerInfo
     * @return
     */
    @Override
    public List<VolunteerInfoVO> selectVolunteerInfoList(VolunteerInfo volunteerInfo) {
        //查询出志愿者信息
        List<VolunteerInfoVO> infos = volunteerInfoMapper.selectVolunteerInfoSimple(volunteerInfo);
        //查询出所有服务名称
        Map<Long, String> idMapTierName = businessManagementService.list().stream().collect(Collectors.toMap(BusinessManagement::getBusinessManagementId, BusinessManagement::getBusinessTierName));
        if (ObjectUtil.isNotEmpty(infos)){
            infos.forEach(info -> {
                info.setBusinessTierName(idMapTierName.get(info.getBusinessManagementId()));
            });
        }
        return infos;
    }

    /**
     * @param
     * @return
     */
    @Override
    public VolunteerInfoDetailVO selectLVolunteerInfoByVolunteerId(VolunteerInfo volunteerInfo) {
        VolunteerInfo info = this.getOne(new LambdaQueryWrapper<VolunteerInfo>()
                .eq(VolunteerInfo::getVolunteerId, volunteerInfo.getVolunteerId())
                .eq(VolunteerInfo::getBusinessManagementId, volunteerInfo.getBusinessManagementId()));
        if (ObjectUtil.isNull(info)){
            throw new ServiceException("获取志愿者信息异常，请稍后再试");
        }
        VolunteerInfoDetailVO vo = BeanUtil.copyProperties(info, VolunteerInfoDetailVO.class);
        //实时查询当前业务的服务费和服务时长
        BusinessPrice price = businessPriceService.getOne(new LambdaQueryWrapper<BusinessPrice>()
                .eq(BusinessPrice::getBusinessManagementId, info.getBusinessManagementId()));
        if (ObjectUtil.isNull(price) || ObjectUtil.isNull(price.getBusinessPrice())){
            throw new ServiceException("服务价格获取异常，请稍后再试");
        }

        vo.setBusinessPrice(price.getBusinessPrice());
        vo.setBusinessDuration(price.getBusinessDuration());
        return vo;
    }
}
