<?php
include(dirname(__DIR__) . '/includes/common.php');
if($islogin==1){}else exit("<script language='javascript'>window.location.href='./login.php';</script>");
$act=isset($_GET['act'])?daddslashes($_GET['act']):null;
@header('Content-Type: application/json; charset=UTF-8');
switch($act){
case 'list':
	$kw=isset($_GET['kw'])?daddslashes($_GET['kw']):'';
	$type=isset($_GET['type'])?daddslashes($_GET['type']):'-1';
	if($kw != ''){
		if($type == '2'){//接口id
			$sql =" a.cityid='{$kw}'";
		}elseif($type == '4'){//分类id
			$like = "'%\"".strval($kw)."\":%'";
			$sql =" a.endtime_arr like ".$like;
		}else{
			$sql =" a.qq like '%{$kw}%'";
		}
	}else if($type == 0 || $type == 1){
		$sql =" a.login_zt=".intval($type);
	}else if($type == '3'){	//过期的
		$sql =" a.login_zt='0'";
		$pagesize = 1000;
	}else{
		$sql =" 1";
	}
	$pagesize=isset($_GET['limit'])?intval($_GET['limit']):30;//每页显示数量
	if($pagesize>200)$pagesize=200;
	$page=isset($_GET['page'])?intval($_GET['page']):1;//当前页数
	$offset=isset($_GET['offset'])?intval($_GET['offset']):$pagesize*($page - 1);//SQL语句起始索引
	$login_class = get_login_class(1);
	$rs=$DB->query("SELECT a.*,b.citybz FROM pre_qq a LEFT JOIN pre_loginconfig b ON a.cityid=b.id WHERE".$sql." ORDER BY id DESC LIMIT $offset,$pagesize");
	$data = array();
	while($res = $rs->fetch(PDO::FETCH_ASSOC)){
		$endtime = is_end3($res['endtime_arr'])[0];
		if($type == '3'){	//过期
			if($date > $endtime){
				$res['endtime'] = $endtime;
				$res['endtime_arr'] = is_end3($res['endtime_arr'],1,$login_class);
				$data[] = $res;	
			}
			continue;
		}
		$res['endtime'] = $endtime;
		$res['endtime_is'] = $date>$endtime?1:0;
		$res['endtime_arr'] = is_end3($res['endtime_arr'],1,$login_class);
		$data[] = $res;
	}
	if(count($data) == 0){
		$total = 0;
		$pages = 1;
	}else{
		if($type == '3'){
			$total = count($data);
		}else{
			$total = $DB->getColumn("SELECT count(*) FROM pre_qq a LEFT JOIN pre_loginconfig b ON a.cityid=b.id WHERE".$sql);
		}
		$pages = ceil($total/$pagesize);	//总页数
	}
	exit(json_encode(array('total' => $total,'rows'=>$data)));
break;
case 'batch_delqq':
	$ids = isset($_POST['ids']) ? $_POST['ids'] : '';
	if(empty($ids)) exit('{"code":-1,"msg":"请选择要删除的QQ"}');
	
	if(is_array($ids)) {
		$arr = array_filter(array_map('intval', $ids));
	} else {
		$arr = array_filter(array_map('intval', explode('-', $ids)));
	}
	
	if(empty($arr)) exit('{"code":-1,"msg":"无效的QQID"}');
	
	$id = implode(',', $arr);
	
	// 记录删除前的数据用于调试
	error_log("批量删除QQ开始 - ID列表: " . implode(',', $arr) . ", 时间: " . date('Y-m-d H:i:s'));
	
	// 1. 先获取要删除的QQ信息
	$qq_list = $DB->getAll("SELECT * FROM `pre_qq` WHERE id IN(".$id.")");
	
	// 2. 先删除网站数据库中的QQ（确保网页上删除成功）
	$sql = "DELETE FROM `pre_qq` WHERE id IN(".$id.")";
	error_log("批量执行SQL: {$sql}");
	$result = $DB->exec($sql);
	
	// 检查SQL执行结果
	if($result === false) {
		$error_info = $DB->error();
		exit('{"code":-1,"msg":"删除失败：' . $error_info . '"}');
	}
	
	// 验证删除是否成功
	error_log("批量删除操作影响行数: {$result}");
	$check_count = $DB->getColumn("SELECT COUNT(*) FROM `pre_qq` WHERE id IN(".$id.")");
	if($check_count > 0) {
		exit('{"code":-1,"msg":"删除失败：仍有 {$check_count} 条数据存在"}');
	}
	
	// 3. 再尝试删除框架中的QQ（框架删除失败不影响网页删除）
	if($qq_list) {
		include_once(dirname(__DIR__) . '/includes/robot_fun.php');
		$frame_qqs = [];
		foreach($qq_list as $qq) {
			$frame_qqs[$qq['cityid']][] = $qq['qq'];
		}
		
		foreach($frame_qqs as $cityid => $qqs) {
			$login = $DB->getRow("SELECT * FROM `pre_loginconfig` WHERE id='{$cityid}'");
			if($login) {
				try {
					$qq_string = implode('-', $qqs);
					$frame_result = deleteqq($login, $qq_string, 1);
					error_log("框架批量删除结果 - 框架ID: {$cityid}, QQ列表: {$qq_string}, 结果: " . json_encode($frame_result));
				} catch(Exception $e) {
					error_log("框架批量删除失败 - 框架ID: {$cityid}, 错误: " . $e->getMessage());
				}
			}
		}
	}
	
	error_log("批量删除QQ成功 - 影响行数: {$result}");
	exit('{"code":1,"msg":"成功删除 ' . $result . ' 个QQ账号"}');
break;

case 'delete_qq':
	$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
	if($id <= 0) exit('{"code":-1,"msg":"无效的QQID"}');
	
	// 检查QQ是否存在
	$qq = $DB->getRow("SELECT * FROM `pre_qq` WHERE id='{$id}'");
	if(!$qq) exit('{"code":-1,"msg":"QQ账号不存在"}');
	
	// 记录删除前的数据用于调试
	error_log("删除QQ开始 - ID: {$id}, QQ号: {$qq['qq']}, 时间: " . date('Y-m-d H:i:s'));
	
	// 1. 先删除网站数据库中的QQ（确保网页上删除成功）
	$sql = "DELETE FROM `pre_qq` WHERE id='{$id}'";
	error_log("执行SQL: {$sql}");
	$result = $DB->exec($sql);
	
	// 检查SQL执行结果
	if($result === false) {
		$error_info = $DB->error();
		exit('{"code":-1,"msg":"删除失败：' . $error_info . '"}');
	}
	
	// 验证删除是否成功
	error_log("删除操作影响行数: {$result}");
	$check = $DB->getRow("SELECT * FROM `pre_qq` WHERE id='{$id}'");
	if($check) {
		error_log("删除QQ验证失败 - ID: {$id} 仍然存在");
		error_log("验证查询结果: " . json_encode($check));
		exit('{"code":-1,"msg":"删除失败：数据仍然存在"}');
	}
	
	// 2. 再尝试删除框架中的QQ（框架删除失败不影响网页删除）
	$login = $DB->getRow("SELECT * FROM `pre_loginconfig` WHERE id='{$qq['cityid']}'");
	if($login) {
		include_once(dirname(__DIR__) . '/includes/robot_fun.php');
		try {
			$frame_result = deleteqq($login, $qq['qq'], 1);
			error_log("框架删除结果 - QQ: {$qq['qq']}, 结果: " . json_encode($frame_result));
		} catch(Exception $e) {
			error_log("框架删除失败 - QQ: {$qq['qq']}, 错误: " . $e->getMessage());
		}
	}
	
	error_log("删除QQ成功 - ID: {$id}, 影响行数: {$result}");
	exit('{"code":1,"msg":"成功删除QQ账号"}');
break;
default:
	exit('{"code":-4,"msg":"No Act"}');
break;
}