package com.ycwl.basic.service.mobile.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageInfo;
import com.ycwl.basic.integration.common.manager.DeviceConfigManager;
import com.ycwl.basic.integration.scenic.dto.scenic.ScenicV2DTO;
import com.ycwl.basic.integration.device.service.DeviceIntegrationService;
import com.ycwl.basic.integration.device.dto.device.DeviceV2DTO;
import com.ycwl.basic.integration.common.response.PageResponse;
import com.ycwl.basic.mapper.ExtraDeviceMapper;
import com.ycwl.basic.mapper.ScenicAccountMapper;
import com.ycwl.basic.model.jwt.JwtInfo;
import com.ycwl.basic.model.mobile.scenic.ScenicAppVO;
import com.ycwl.basic.model.mobile.scenic.ScenicDeviceCountVO;
import com.ycwl.basic.model.mobile.scenic.ScenicIndexVO;
import com.ycwl.basic.model.mobile.scenic.account.ScenicLoginReq;
import com.ycwl.basic.model.mobile.scenic.account.ScenicLoginRespVO;
import com.ycwl.basic.model.mobile.scenic.account.ScenicRegisterReq;
import com.ycwl.basic.model.mobile.scenic.account.ScenicRegisterRespVO;
import com.ycwl.basic.model.pc.device.entity.DeviceEntity;
import com.ycwl.basic.model.pc.device.resp.DeviceRespVO;
import com.ycwl.basic.model.pc.scenic.entity.ScenicAccountEntity;
import com.ycwl.basic.model.pc.scenic.entity.ScenicEntity;
import com.ycwl.basic.model.pc.scenic.req.ScenicReqQuery;
import com.ycwl.basic.model.pc.scenic.resp.ScenicRespVO;
import com.ycwl.basic.repository.DeviceRepository;
import com.ycwl.basic.repository.ScenicRepository;
import com.ycwl.basic.service.mobile.AppScenicService;
import com.ycwl.basic.service.pc.ScenicAccountService;
import com.ycwl.basic.utils.ApiResponse;
import com.ycwl.basic.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.ycwl.basic.constant.JwtRoleConstant.MERCHANT;

/**
 * @Author：longbinbin
 * @Date：2024/12/6 10:23
 */
@Slf4j
@Service
public class AppScenicServiceImpl implements AppScenicService {

    @Autowired
    private DeviceIntegrationService deviceIntegrationService;
    @Autowired
    private ScenicAccountMapper scenicAccountMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private ScenicAccountService scenicAccountService;
    @Autowired
    private DeviceRepository deviceRepository;
    @Autowired
    private ExtraDeviceMapper extraDeviceMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private ScenicRepository scenicRepository;

    @Override
    public ApiResponse<ScenicRespVO> getDetails(Long id) {
        ScenicEntity scenic = scenicRepository.getScenic(id);
        ScenicRespVO scenicRespVO = new ScenicRespVO();
        
        // 将ScenicEntity的值通过set/get方式写入到ScenicRespVO
        if (scenic != null) {
            scenicRespVO.setId(scenic.getId());
            scenicRespVO.setName(scenic.getName());
            scenicRespVO.setPhone(scenic.getPhone());
            scenicRespVO.setLogoUrl(scenic.getLogoUrl());
            scenicRespVO.setCoverUrl(scenic.getCoverUrl());
            scenicRespVO.setIntroduction(scenic.getIntroduction());
            scenicRespVO.setLongitude(scenic.getLongitude());
            scenicRespVO.setLatitude(scenic.getLatitude());
            scenicRespVO.setRadius(scenic.getRadius());
            scenicRespVO.setProvince(scenic.getProvince());
            scenicRespVO.setCity(scenic.getCity());
            scenicRespVO.setArea(scenic.getArea());
            scenicRespVO.setAddress(scenic.getAddress());
            scenicRespVO.setKfCodeUrl(scenic.getKfCodeUrl());
        }
        
        // 通过zt-device服务获取设备统计
        PageResponse<DeviceV2DTO> deviceListResponse = deviceIntegrationService.getScenicActiveDevices(id, 1, 1000);
        ScenicDeviceCountVO scenicDeviceCountVO = new ScenicDeviceCountVO();
        if (deviceListResponse != null && deviceListResponse.getList() != null) {
            scenicDeviceCountVO.setTotalDeviceCount(deviceListResponse.getList().size());
        } else {
            scenicDeviceCountVO.setTotalDeviceCount(0);
        }
        scenicRespVO.setLensNum(scenicDeviceCountVO.getTotalDeviceCount());
        return ApiResponse.success(scenicRespVO);
    }

    @Override
    public ApiResponse<ScenicLoginRespVO> login(ScenicLoginReq scenicLoginReq) throws Exception {
        ScenicAccountEntity scenicAccount = scenicAccountService.getScenicAccountByAccount(scenicLoginReq.getAccount());
        if (scenicAccount == null) {
            return ApiResponse.fail("账号不存在");
        }
        if (scenicAccount.getStatus() == 0) {
            return ApiResponse.fail("账号已被禁用");
        }
        if (scenicAccount.getIsActive() == null || scenicAccount.getIsActive() != 1) {
            return ApiResponse.fail("账号未激活");
        }
        if (!scenicAccount.getPassword().equals(scenicLoginReq.getPassword())) {
            return ApiResponse.fail("密码错误");
        }

        JwtInfo jwtInfo = new JwtInfo();
        jwtInfo.setName(scenicAccount.getName());
        jwtInfo.setAccount(scenicAccount.getAccount());
        jwtInfo.setUserId(scenicAccount.getId());
        jwtInfo.setRoleId(MERCHANT.type);
        String token = jwtTokenUtil.generateToken(jwtInfo, scenicAccount.getUpdateTime());

        ScenicLoginRespVO scenicLoginRespVO = new ScenicLoginRespVO();
        BeanUtil.copyProperties(scenicAccount,scenicLoginRespVO);
        List<Long> scenicIds = scenicAccountMapper.getAccountRelations(scenicAccount.getId());
        if (!scenicIds.isEmpty()) {
            scenicLoginRespVO.setScenicId(scenicIds);
        } else {
            scenicLoginRespVO.setScenicId(List.of(scenicAccount.getId()));
        }
        scenicLoginRespVO.setToken(token);
        return ApiResponse.success(scenicLoginRespVO);
    }

    @Override
    public ApiResponse<ScenicRegisterRespVO> register(ScenicRegisterReq scenicRegisterReq) {
        // 验证手机号格式
        if (scenicRegisterReq.getPhone() == null || !scenicRegisterReq.getPhone().matches("^1[3-9]\\d{9}$")) {
            return ApiResponse.fail("手机号格式不正确");
        }
        
        // 验证密码不能为空
        if (scenicRegisterReq.getPassword() == null || scenicRegisterReq.getPassword().trim().isEmpty()) {
            return ApiResponse.fail("密码不能为空");
        }
        
        // 检查手机号是否已存在
        try {
            ScenicAccountEntity existingAccount = scenicAccountService.getScenicAccountByAccount(scenicRegisterReq.getPhone());
            if (existingAccount != null) {
                return ApiResponse.fail("该手机号已注册");
            }
        } catch (Exception e) {
            // 如果抛出异常说明账号不存在，可以继续注册
        }
        
        // 创建新账号
        ScenicAccountEntity newAccount = new ScenicAccountEntity();
        newAccount.setAccount(scenicRegisterReq.getPhone());
        newAccount.setPhone(scenicRegisterReq.getPhone());
        newAccount.setPassword(scenicRegisterReq.getPassword());
        newAccount.setIsActive(0); // 未激活状态
        newAccount.setStatus(1); // 正常状态
        newAccount.setCreateTime(new Date());
        newAccount.setUpdateTime(new Date());
        
        try {
            int result = scenicAccountService.addScenicAccount(newAccount);
            if (result > 0) {
                ScenicRegisterRespVO response = new ScenicRegisterRespVO();
                response.setId(newAccount.getId());
                response.setAccount(newAccount.getAccount());
                response.setPhone(newAccount.getPhone());
                response.setIsActive(newAccount.getIsActive());
                response.setMessage("注册成功，请等待后台激活");
                return ApiResponse.success(response);
            } else {
                return ApiResponse.fail("注册失败");
            }
        } catch (Exception e) {
            log.error("注册失败", e);
            return ApiResponse.fail("注册失败：" + e.getMessage());
        }
    }

    @Override
    public ApiResponse<List<DeviceRespVO>> getDevices(Long scenicId) {
        PageResponse<DeviceV2DTO> deviceV2ListResponse = deviceIntegrationService.listDevices(1, 1000, null, null, null, 1, scenicId, null);
        List<DeviceRespVO> deviceRespVOList = deviceV2ListResponse.getList().stream().map(device -> {
            DeviceRespVO deviceRespVO = new DeviceRespVO();
            deviceRespVO.setId(device.getId());
            deviceRespVO.setName(device.getName());
            deviceRespVO.setNo(device.getNo());

            DeviceConfigManager config = deviceRepository.getDeviceConfigManager(device.getId());
            deviceRespVO.setPreviewUrl(config.getString("preview_url"));
            deviceRespVO.setPreviewCoverUrl(config.getString("preview_cover_url"));
            return deviceRespVO;
        }).collect(Collectors.toList());
        for (DeviceRespVO deviceRespVO : deviceRespVOList) {
            DeviceEntity onlineStatus = deviceRepository.getOnlineStatus(deviceRespVO.getId());
            if (onlineStatus != null) {
                deviceRespVO.setUpdateAt(onlineStatus.getKeepaliveAt());
                deviceRespVO.setKeepaliveAt(onlineStatus.getKeepaliveAt());
                if (onlineStatus.getKeepaliveAt() == null) {
                    deviceRespVO.setOnline(0);
                } else if (new Date().getTime() - onlineStatus.getKeepaliveAt().getTime() > 300000) {
                    deviceRespVO.setOnline(0);
                } else {
                    deviceRespVO.setOnline(onlineStatus.getOnline());
                }
            } else {
                deviceRespVO.setOnline(0);
                deviceRespVO.setKeepaliveAt(null);
                deviceRespVO.setUpdateAt(null);
            }
        }
        List<DeviceRespVO> extraDeviceList = extraDeviceMapper.listExtraDeviceByScenicId(scenicId);
        for (DeviceRespVO deviceRespVO : extraDeviceList) {
            ScenicV2DTO scenicBasic = scenicRepository.getScenicBasic(deviceRespVO.getScenicId());
            deviceRespVO.setScenicName(scenicBasic.getName());
            if (redisTemplate.hasKey("ext_device:online:"+deviceRespVO.getNo())) {
                String onlineTs = redisTemplate.opsForValue().get("ext_device:online:"+deviceRespVO.getNo());
                if (!StringUtils.isNumeric(onlineTs)) {
                    deviceRespVO.setOnline(0);
                    continue;
                }
                long ts = Long.parseLong(onlineTs);
                Date keepaliveAt = new Date(ts*1000);
                deviceRespVO.setUpdateAt(keepaliveAt);
                deviceRespVO.setKeepaliveAt(keepaliveAt);
                deviceRespVO.setOnline(keepaliveAt.getTime() > System.currentTimeMillis()-1000*60*5 ? 1 : 0);
            } else {
                deviceRespVO.setOnline(0);
            }
        }
        deviceRespVOList.addAll(0, extraDeviceList);
        return ApiResponse.success(deviceRespVOList);
    }
    
    /**
     * 计算两点之间的距离（米）
     * 使用 Haversine 公式
     */
    private BigDecimal calculateDistance(BigDecimal lat1, BigDecimal lon1, BigDecimal lat2, BigDecimal lon2) {
        if (lat1 == null || lon1 == null || lat2 == null || lon2 == null) {
            return BigDecimal.ZERO;
        }
        
        final double R = 6371000; // 地球半径（米）
        
        double lat1Rad = Math.toRadians(lat1.doubleValue());
        double lat2Rad = Math.toRadians(lat2.doubleValue());
        double deltaLat = Math.toRadians(lat2.subtract(lat1).doubleValue());
        double deltaLon = Math.toRadians(lon2.subtract(lon1).doubleValue());
        
        double a = Math.sin(deltaLat/2) * Math.sin(deltaLat/2) +
                Math.cos(lat1Rad) * Math.cos(lat2Rad) *
                Math.sin(deltaLon/2) * Math.sin(deltaLon/2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        
        double distance = R * c;
        return BigDecimal.valueOf(distance);
    }
}
