package com.ruoyi.model.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyl.manager.oms.domain.OmsOrderService;
import com.cyl.manager.oms.mapper.OmsOrderServiceMapper;
import com.ruoyi.applet.pojo.dto.filterQualifiedUsersVo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.model.domain.AppletAddress;
import com.ruoyi.model.domain.AppletOrder;
import com.ruoyi.model.domain.AppletOutDate;
import com.ruoyi.model.service.IAppletAddressService;
import com.ruoyi.model.service.IAppletOutDateService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.model.mapper.AppUsersMapper;
import com.ruoyi.model.domain.AppUsers;
import com.ruoyi.model.service.IAppUsersService;

/**
 * 用户Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-03-27
 */
@Service
@Log4j2
public class AppUsersServiceImpl extends ServiceImpl<AppUsersMapper, AppUsers> implements IAppUsersService
{
    @Autowired
    private AppUsersMapper appUsersMapper;

    @Autowired
    private IAppletOutDateService appletOutDateService;

    @Autowired
    private OmsOrderServiceMapper omsOrderServiceMapper;

    @Autowired
    private IAppletAddressService appletAddressService;

    /**
     * 查询用户
     * 
     * @param userId 用户主键
     * @return 用户
     */
    @Override
    public AppUsers selectAppUsersByUserId(Long userId)
    {
        return appUsersMapper.selectAppUsersByUserId(userId);
    }

    /**
     * 查询用户列表
     * 
     * @param appUsers 用户
     * @return 用户
     */
    @Override
    public List<AppUsers> selectAppUsersList(AppUsers appUsers)
    {
        return appUsersMapper.selectAppUsersList(appUsers);
    }

    /**
     * 新增用户
     * 
     * @param appUsers 用户
     * @return 结果
     */
    @Override
    public int insertAppUsers(AppUsers appUsers)
    {
        appUsers.setCreateTime(DateUtils.getNowDate());
        return appUsersMapper.insertAppUsers(appUsers);
    }

    /**
     * 修改用户
     * 
     * @param appUsers 用户
     * @return 结果
     */
    @Override
    public int updateAppUsers(AppUsers appUsers)
    {
        appUsers.setUpdateTime(DateUtils.getNowDate());
        return appUsersMapper.updateById(appUsers);
    }

    /**
     * 批量删除用户
     * 
     * @param userIds 需要删除的用户主键
     * @return 结果
     */
    @Override
    public int deleteAppUsersByUserIds(Long[] userIds)
    {
        return appUsersMapper.deleteAppUsersByUserIds(userIds);
    }

    /**
     * 删除用户信息
     * 
     * @param userId 用户主键
     * @return 结果
     */
    @Override
    public int deleteAppUsersByUserId(Long userId)
    {
        return appUsersMapper.deleteAppUsersByUserId(userId);
    }

    @Override
    public AppUsers selectAppUsersByOpenId(String openid) {
        return appUsersMapper.selectAppUsersByOpenId(openid);
    }

    // 根据订单筛选符合条件的技师
    @Override
    public List<AppUsers> filterQualifiedUsers(filterQualifiedUsersVo filterVo) {
        List<AppUsers> qualifiedTechnicians = new ArrayList<>();

        ArrayList<Long> notAddressIds = new ArrayList<>();

        LambdaQueryChainWrapper<AppletAddress> addressQW = appletAddressService.lambdaQuery();
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        //根据不接单日期排除地址
        if (ObjectUtils.isNotEmpty(filterVo.getOrderId())){
            List<Date> dates = omsOrderServiceMapper.selectList(Wrappers.<OmsOrderService>
                                    lambdaQuery()
                            .select(OmsOrderService::getServiceDate)
                            .eq(OmsOrderService::getOrderId, filterVo.getOrderId()))
                    .stream().map(n -> {
                        try {
                            return sdf.parse(n.getServiceDate());
                        } catch (ParseException e) {
                            return null;
                        }
                    })
                    .filter(n -> ObjectUtils.isNotEmpty(n))
                    .collect(Collectors.toList());

            appletOutDateService.lambdaQuery().in(AppletOutDate::getDate, dates)
                    .select(AppletOutDate::getAddressId)
                    .groupBy(AppletOutDate::getAddressId)
                    .list().stream().forEach(n ->
                        notAddressIds.add(n.getAddressId())
                    );
        }


        // 2. 根据订单经纬度查询范围内的地址
        if (ObjectUtils.isNotEmpty(filterVo.getLatitude()) &&
                ObjectUtils.isNotEmpty(filterVo.getLongitude())) {

            BigDecimal orderLat = new BigDecimal(filterVo.getLatitude());
            BigDecimal orderLng = new BigDecimal(filterVo.getLongitude());
            
            // 将15公里转换为经纬度范围
            // 1度纬度约等于111公里
            // 1度经度约等于111*cos(纬度)公里
            BigDecimal range = new BigDecimal("15"); // 15公里范围
            BigDecimal latRange = range.divide(new BigDecimal("111"), 6, BigDecimal.ROUND_HALF_UP);
            BigDecimal lngRange = range.divide(new BigDecimal("111").multiply(new BigDecimal(Math.cos(orderLat.doubleValue() * Math.PI / 180))), 6, BigDecimal.ROUND_HALF_UP);
            
            // 计算经纬度范围
            BigDecimal latMin = orderLat.subtract(latRange);
            BigDecimal latMax = orderLat.add(latRange);
            BigDecimal lngMin = orderLng.subtract(lngRange);
            BigDecimal lngMax = orderLng.add(lngRange);

            // 查询所有有效的地址，并且在15公里范围内
            List<AppletAddress> addressList = appletAddressService.lambdaQuery()
                    .eq(AppletAddress::getStatus, "true")
                    .notIn(!notAddressIds.isEmpty(), AppletAddress::getId, notAddressIds)
                    .ge(AppletAddress::getLatitude, latMin.toString())
                    .le(AppletAddress::getLatitude, latMax.toString())
                    .ge(AppletAddress::getLongitude, lngMin.toString())
                    .le(AppletAddress::getLongitude, lngMax.toString())
                    .list();

            // 3. 筛选在范围内的地址
            List<Long> qualifiedUserId = new ArrayList<>();
            for (AppletAddress address : addressList) {
                if (StringUtils.isNotEmpty(address.getLatitude()) &&
                        StringUtils.isNotEmpty(address.getLongitude()) &&
                        StringUtils.isNotEmpty(address.getRangeNo())) {

                    BigDecimal addressLat = new BigDecimal(address.getLatitude());
                    BigDecimal addressLng = new BigDecimal(address.getLongitude());
                    BigDecimal rangeKm = new BigDecimal(address.getRangeNo()); // 公里数
                    
                    // 将公里数转换为经纬度范围
                    // 1度纬度约等于111公里
                    // 1度经度约等于111*cos(纬度)公里
                    latRange = rangeKm.divide(new BigDecimal("111"), 6, BigDecimal.ROUND_HALF_UP);
                    lngRange = rangeKm.divide(new BigDecimal("111").multiply(new BigDecimal(Math.cos(addressLat.doubleValue() * Math.PI / 180))), 6, BigDecimal.ROUND_HALF_UP);
                    
                    // 计算距离（经纬度差值）
                    BigDecimal latDiff = orderLat.subtract(addressLat).abs();
                    BigDecimal lngDiff = orderLng.subtract(addressLng).abs();
                    
                    // 如果在范围内，添加到合格地址列表
                    if (latDiff.compareTo(latRange) <= 0 && lngDiff.compareTo(lngRange) <= 0) {
                        qualifiedUserId.add(address.getUserId());
                    }
                }
            }

            // 4. 根据地址ID和技师等级查询符合条件的技师
            qualifiedTechnicians = appUsersMapper.selectList(
                    Wrappers.<AppUsers>lambdaQuery()
                          .eq(ObjectUtils.isNotEmpty(filterVo.getCompanionLevel()),AppUsers::getUserBcsRole, filterVo.getCompanionLevel())
//                        .and(ObjectUtils.isNotEmpty(filterVo.getCompanionLevel()), n -> {
//                            n.eq(AppUsers::getUserBcsRole, filterVo.getCompanionLevel())
//                                    .or()
//                            .in(filterVo.getCompanionLevel() == 0, AppUsers::getUserBcsRole, 1,2);
//                        })
                        .in(qualifiedUserId.size() > 0, AppUsers::getUserId, qualifiedUserId)
            );
        }

        return qualifiedTechnicians;
    }

    /**
     * 生成唯一的6位字母数字邀请码
     * @return 6位字母数字组合的邀请码
     */
    private String generateUniqueInvitationCode() {
        String characters = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        String code;
        
        do {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 6; i++) {
                sb.append(characters.charAt(random.nextInt(characters.length())));
            }
            code = sb.toString();
        } while (isInvitationCodeExists(code)); // 确保邀请码唯一
        
        return code;
    }
    
    /**
     * 检查邀请码是否已存在
     * @param code 邀请码
     * @return true表示已存在，false表示不存在
     */
    private boolean isInvitationCodeExists(String code) {
        return appUsersMapper.selectCount(
            Wrappers.<AppUsers>lambdaQuery()
                .eq(AppUsers::getInvitationCode, code)
        ) > 0;
    }

    @Override
    public String getUserCode(Long appUserId) {

        AppUsers byId = getById(appUserId);

        if (byId == null){
            log.error("用户不存在 ID：{}", appUserId);
            return null;
        }

        if (StringUtils.isNotEmpty(byId.getInvitationCode())){
            return byId.getInvitationCode();
        }

        //生成邀请码
        String invitationCode = generateUniqueInvitationCode();
        byId.setInvitationCode(invitationCode);
        updateById(byId);

        return byId.getInvitationCode();
    }

    @Override
    public AppUsers bindCode(String code) {
        AppUsers users = lambdaQuery().eq(AppUsers::getInvitationCode, code).one();
        if (users == null){
            throw new ServiceException("无效的邀请码");
        }
        users.setInvitationNumber(users.getInvitationNumber() + 1);
        updateById(users);

        //TODO 检查是否满足升级条件

        return users;
    }
}
