"""
实体管理 API（企业、用户、场站）
"""
from flask import request, jsonify
from lib.db import execute_query
from . import entity_bp


@entity_bp.route('/entities', methods=['GET'])
def get_entities():
    """获取企业、用户或场站列表（支持分页和搜索）"""
    try:
        entity_type = request.args.get('type', 'company')
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('page_size', 100))
        search = request.args.get('search', '')
        
        offset = (page - 1) * page_size
        
        if entity_type == 'company':
            # 获取企业列表 (company_state=0 表示启用)
            if search:
                companies = execute_query(
                    'SELECT id AS company_id, company_name FROM t_company WHERE company_state = 0 AND company_name LIKE %s ORDER BY company_name LIMIT %s OFFSET %s',
                    (f'%{search}%', page_size, offset)
                )
                total_result = execute_query(
                    'SELECT COUNT(*) as total FROM t_company WHERE company_state = 0 AND company_name LIKE %s',
                    (f'%{search}%',)
                )
            else:
                companies = execute_query(
                    'SELECT id AS company_id, company_name FROM t_company WHERE company_state = 0 ORDER BY company_name LIMIT %s OFFSET %s',
                    (page_size, offset)
                )
                total_result = execute_query(
                    'SELECT COUNT(*) as total FROM t_company WHERE company_state = 0'
                )
            total = total_result[0]['total'] if total_result else 0
            return jsonify({'success': True, 'data': companies, 'total': total, 'page': page, 'page_size': page_size})
        
        elif entity_type == 'station':
            # 获取场站列表
            if search:
                stations = execute_query(
                    'SELECT id AS station_id, station_name FROM t_station WHERE station_name LIKE %s ORDER BY station_name LIMIT %s OFFSET %s',
                    (f'%{search}%', page_size, offset)
                )
                total_result = execute_query(
                    'SELECT COUNT(*) as total FROM t_station WHERE station_name LIKE %s',
                    (f'%{search}%',)
                )
            else:
                stations = execute_query(
                    'SELECT id AS station_id, station_name FROM t_station ORDER BY station_name LIMIT %s OFFSET %s',
                    (page_size, offset)
                )
                total_result = execute_query(
                    'SELECT COUNT(*) as total FROM t_station'
                )
            total = total_result[0]['total'] if total_result else 0
            return jsonify({'success': True, 'data': stations, 'total': total, 'page': page, 'page_size': page_size})
        
        else:
            # 获取用户列表（支持分页和搜索，搜索支持用户名和手机号）
            if search:
                users = execute_query(
                    'SELECT id AS user_id, user_name, phone FROM t_user WHERE user_name LIKE %s OR phone LIKE %s ORDER BY user_name LIMIT %s OFFSET %s',
                    (f'%{search}%', f'%{search}%', page_size, offset)
                )
                total_result = execute_query(
                    'SELECT COUNT(*) as total FROM t_user WHERE user_name LIKE %s OR phone LIKE %s',
                    (f'%{search}%', f'%{search}%')
                )
            else:
                users = execute_query(
                    'SELECT id AS user_id, user_name, phone FROM t_user ORDER BY user_name LIMIT %s OFFSET %s',
                    (page_size, offset)
                )
                total_result = execute_query(
                    'SELECT COUNT(*) as total FROM t_user'
                )
            total = total_result[0]['total'] if total_result else 0
            return jsonify({'success': True, 'data': users, 'total': total, 'page': page, 'page_size': page_size})
    
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500


@entity_bp.route('/entities/by_ids', methods=['POST'])
def get_entities_by_ids():
    """根据 ID 列表查询实体信息（用于编辑回显）"""
    try:
        data = request.json
        entity_type = data.get('type', 'company')
        ids = data.get('ids', [])
        
        if not ids:
            return jsonify({'success': True, 'data': []})
        
        placeholders = ', '.join(['%s'] * len(ids))
        
        if entity_type == 'company':
            entities = execute_query(
                f'SELECT id AS company_id, company_name FROM t_company WHERE id IN ({placeholders})',
                tuple(ids)
            )
        elif entity_type == 'station':
            entities = execute_query(
                f'SELECT id AS station_id, station_name FROM t_station WHERE id IN ({placeholders})',
                tuple(ids)
            )
        else:
            entities = execute_query(
                f'SELECT id AS user_id, user_name FROM t_user WHERE id IN ({placeholders})',
                tuple(ids)
            )
        
        return jsonify({'success': True, 'data': entities})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500
