package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.model.UserMembership;
import com.example.demo.model.MembershipLevel;
import com.example.demo.repository.UserRepository;
import com.example.demo.repository.UserMembershipRepository;
import com.example.demo.repository.MembershipLevelRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/members")
@CrossOrigin(origins = "*")
public class MemberApiController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserMembershipRepository userMembershipRepository;

    @Autowired
    private MembershipLevelRepository membershipLevelRepository;

    // 获取会员列表
    @GetMapping
    public ResponseEntity<Map<String, Object>> getMembers(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String level) {
        
        try {
            Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by("createdAt").descending());
            Page<User> userPage = userRepository.findAll(pageable);
            
            List<Map<String, Object>> members = userPage.getContent().stream()
                .map(user -> {
                    Map<String, Object> member = new HashMap<>();
                    member.put("id", user.getId());
                    member.put("username", user.getUsername());
                    member.put("email", user.getEmail());
                    member.put("phone", user.getPhone());
                    member.put("nickname", user.getNickname());
                    member.put("points", user.getPoints());
                    member.put("role", user.getRole());
                    member.put("isActive", user.getIsActive());
                    member.put("createdAt", user.getCreatedAt());
                    member.put("lastLoginAt", user.getLastLoginAt());
                    
                    // 获取会员信息
                    Optional<UserMembership> membership = userMembershipRepository
                        .findByUserIdAndStatus(user.getId(), "ACTIVE");
                    
                    if (membership.isPresent()) {
                        UserMembership userMembership = membership.get();
                        Optional<MembershipLevel> membershipLevel = membershipLevelRepository
                            .findById(userMembership.getMembershipLevelId());
                        
                        if (membershipLevel.isPresent()) {
                            Map<String, Object> membershipInfo = new HashMap<>();
                            membershipInfo.put("display_name", membershipLevel.get().getDisplayName());
                            membershipInfo.put("end_date", userMembership.getEndDate());
                            membershipInfo.put("status", userMembership.getStatus());
                            member.put("membership", membershipInfo);
                        }
                    }
                    
                    return member;
                })
                .toList();
            
            Map<String, Object> response = new HashMap<>();
            response.put("list", members);
            response.put("total", userPage.getTotalElements());
            response.put("page", page);
            response.put("pageSize", pageSize);
            response.put("totalPages", userPage.getTotalPages());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "获取会员列表失败");
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    // 获取会员详情
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getMemberDetail(@PathVariable Long id) {
        try {
            Optional<User> userOpt = userRepository.findById(id);
            if (userOpt.isEmpty()) {
                return ResponseEntity.notFound().build();
            }
            
            User user = userOpt.get();
            Map<String, Object> member = new HashMap<>();
            member.put("id", user.getId());
            member.put("username", user.getUsername());
            member.put("email", user.getEmail());
            member.put("phone", user.getPhone());
            member.put("nickname", user.getNickname());
            member.put("points", user.getPoints());
            member.put("role", user.getRole());
            member.put("isActive", user.getIsActive());
            member.put("createdAt", user.getCreatedAt());
            member.put("lastLoginAt", user.getLastLoginAt());
            
            // 获取会员信息
            Optional<UserMembership> membership = userMembershipRepository
                .findByUserIdAndStatus(user.getId(), "ACTIVE");
            
            if (membership.isPresent()) {
                UserMembership userMembership = membership.get();
                Optional<MembershipLevel> membershipLevel = membershipLevelRepository
                    .findById(userMembership.getMembershipLevelId());
                
                if (membershipLevel.isPresent()) {
                    Map<String, Object> membershipInfo = new HashMap<>();
                    membershipInfo.put("display_name", membershipLevel.get().getDisplayName());
                    membershipInfo.put("end_date", userMembership.getEndDate());
                    membershipInfo.put("status", userMembership.getStatus());
                    member.put("membership", membershipInfo);
                }
            }
            
            return ResponseEntity.ok(member);
            
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "获取会员详情失败");
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    // 更新会员信息
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateMember(
            @PathVariable Long id,
            @RequestBody Map<String, Object> updateData) {
        try {
            Optional<User> userOpt = userRepository.findById(id);
            if (userOpt.isEmpty()) {
                return ResponseEntity.notFound().build();
            }
            
            User user = userOpt.get();
            
            // 更新用户基本信息
            if (updateData.containsKey("username")) {
                user.setUsername((String) updateData.get("username"));
            }
            if (updateData.containsKey("points")) {
                user.setPoints((Integer) updateData.get("points"));
            }
            
            userRepository.save(user);
            
            // 更新会员等级
            if (updateData.containsKey("level")) {
                String levelName = (String) updateData.get("level");
                Optional<MembershipLevel> levelOpt = membershipLevelRepository
                    .findByDisplayName(levelName);
                
                if (levelOpt.isPresent()) {
                    MembershipLevel level = levelOpt.get();
                    
                    // 更新或创建会员信息
                    Optional<UserMembership> membershipOpt = userMembershipRepository
                        .findByUserIdAndStatus(user.getId(), "ACTIVE");
                    
                    if (membershipOpt.isPresent()) {
                        UserMembership membership = membershipOpt.get();
                        membership.setMembershipLevelId(level.getId());
                        userMembershipRepository.save(membership);
                    }
                }
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "会员信息更新成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "更新会员信息失败");
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    // 删除会员
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteMember(@PathVariable Long id) {
        try {
            Optional<User> userOpt = userRepository.findById(id);
            if (userOpt.isEmpty()) {
                return ResponseEntity.notFound().build();
            }
            
            // 软删除：设置为非活跃状态
            User user = userOpt.get();
            user.setIsActive(false);
            userRepository.save(user);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "会员删除成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "删除会员失败");
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    // 批量删除会员
    @DeleteMapping("/batch")
    public ResponseEntity<Map<String, Object>> deleteMembers(@RequestBody Map<String, List<Long>> request) {
        try {
            List<Long> ids = request.get("ids");
            if (ids == null || ids.isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of("error", "请提供要删除的会员ID列表"));
            }
            
            List<User> users = userRepository.findAllById(ids);
            users.forEach(user -> user.setIsActive(false));
            userRepository.saveAll(users);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "批量删除成功");
            response.put("deletedCount", users.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "批量删除失败");
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }
}
