package com.ffii.fhsmsc.modules.User_group.service;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.sql.Timestamp;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ffii.core.support.JdbcDao;
import com.ffii.fhsmsc.modules.User_group.req.*;
import com.ffii.fhsmsc.modules.User_group.constant.*;
import com.ffii.fhsmsc.modules.User_group.enity.*;
import java.util.Optional;
import java.util.Date;
import com.ffii.fhsmsc.modules.User_group.repository.UserGroupMembersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import com.ffii.fhsmsc.modules.User_group.repository.User_authorityRepository;

@Service
public class UserGroupCombineService {
    @Autowired
    private UserGroupMembersRepository userGroupMembersRepository;
    @Autowired
    private User_authorityRepository userAuthorityRepository;
    @Autowired
    private JdbcDao jdbcDao;

    public List<UserGroupMembers> getGroupMembersWithAuthorities(Long orgId, String relationshipType) {
        if (relationshipType != null && !relationshipType.isEmpty()) {
            return userGroupMembersRepository.findByUserGrpOrgIdAndRelationshipType(orgId, relationshipType);
        }
        return userGroupMembersRepository.findByUserGrpOrgId(orgId);
    }

    @Transactional
    public void addMemberWithAuthorities(UserGroupMemberBatchReq req) {
        for (UserGroupMemberBatchReq.MemberWithAuthorities member : req.getMembers()) {
            // 1. 检查用户是否已经是组织成员
            Optional<UserGroupMembers> existingMember = userGroupMembersRepository
                .findByUserGrpOrgIdAndUserId(req.getOrgId(), member.getUserId());
    
            if (!existingMember.isPresent()) {
                // 如果不是成员，创建新的成员关系
                UserGroupMembers groupMember = new UserGroupMembers();
                groupMember.setUser_Grp_Org_ID(req.getOrgId());
                groupMember.setUser_ID(member.getUserId());
                groupMember.setR_Ship_Creator(req.getRelationshipType());
                groupMember.setCreation_Date_Time(new Date());
                
                userGroupMembersRepository.save(groupMember);
            }
    
            // 2. 删除现有权限（如果有）
            String deleteSql = "DELETE FROM user_authority WHERE userId = :userId";
            Map<String, Object> params = new HashMap<>();
            params.put("userId", member.getUserId());
            jdbcDao.executeUpdate(deleteSql, params);
    
            // 3. 添加新的权限
            if (member.getAuthorityIds() != null && !member.getAuthorityIds().isEmpty()) {
                for (Long authId : member.getAuthorityIds()) {
                    User_authority userAuthority = new User_authority();
                    userAuthority.setUserId(member.getUserId());
                    userAuthority.setAuthId(authId);
                    userAuthorityRepository.save(userAuthority);
                }
            }
        }
    }

    @Transactional
    public void updateMember(Long userId, MemberUpdateReq req) {
        Optional<UserGroupMembers> memberOpt = userGroupMembersRepository.findByUserGrpOrgIdAndUserId(
            req.getOrgId(), userId);
            
        if (!memberOpt.isPresent()) {
            throw new RuntimeException("Member not found");
        }

        UserGroupMembers member = memberOpt.get();
        member.setR_Ship_Creator(req.getRelationshipType());
        userGroupMembersRepository.save(member);
    }

    @Transactional
    public void removeMember(Long orgId, Long userId, String relationshipType) {
        Optional<UserGroupMembers> memberOpt = userGroupMembersRepository.findByUserGrpOrgIdAndUserId(orgId, userId);
        
        if (!memberOpt.isPresent()) {
            throw new RuntimeException("Member not found");
        }

        UserGroupMembers member = memberOpt.get();
        if (!member.getR_Ship_Creator().equals(relationshipType)) {
            throw new RuntimeException("Invalid relationship type for member");
        }

        userGroupMembersRepository.deleteByUserGrpOrgIdAndUserId(orgId, userId);
    }

    @Transactional(readOnly = true)
    public List<Map<String, Object>> getMemberAuthorities(int userId) {
        String sql = "SELECT ua.*, a.name as auth_name " +
                    "FROM user_authority ua " +
                    "JOIN authority a ON ua.authId = a.id " +
                    "WHERE ua.userId = :userId";
        
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        
        return jdbcDao.queryForList(sql, params);
    }

    @Transactional(readOnly = true)
    public List<Map<String, Object>> getAllAuthorities() {
        return jdbcDao.queryForList("SELECT * FROM authority", new HashMap<>());
    }

    private void validatePermission(String relationshipType, String operation) {
        if (!RelationshipRules.canPerformOperation(relationshipType, operation)) {
            throw new RuntimeException("Operation not allowed for relationship type: " + relationshipType);
        }
    }
} 