<?php
include("../includes/common.php");

// 验证访问密钥
$key = isset($_GET['key'])?trim($_GET['key']):null;
$monitor_key = $DB->getColumn("SELECT v FROM pre_config WHERE k='monitor_key'");
if($monitor_key && $key != $monitor_key){
    exit(json_encode(['code'=>-1, 'msg'=>'监控密钥错误'], JSON_UNESCAPED_UNICODE));
}

@header('Content-Type: application/json; charset=UTF-8');

// 获取上次运行时间
$last_time = $DB->getColumn("SELECT v FROM pre_config WHERE k='last_sync_time'");
if($last_time){
    $interval = time() - strtotime($last_time);
}else{
    $interval = 999999;
}

// 获取已启用的同步配置
$rs = $DB->query("SELECT a.*,b.* FROM pre_sync_config a LEFT JOIN pre_shequ b ON a.shequ_id=b.id WHERE a.status=1");
$sync_list = array();
while($row = $rs->fetch()){
    // 判断是否到达同步间隔
    if($interval < $row['sync_interval']*60){
        continue;
    }
    $sync_list[] = $row;
}

if(empty($sync_list)){
    exit(json_encode(['code'=>0, 'msg'=>'当前无需同步'], JSON_UNESCAPED_UNICODE));
}

// 更新运行时间
$DB->exec("REPLACE INTO pre_config SET k='last_sync_time',v='".$date."'");

$success = 0;
$fail = 0;
$add_success = 0;
$update_success = 0;
$class_success = 0;
$error = null;

foreach($sync_list as $row){
    // 获取分类列表
    $class_list = third_call($row['type'], $row, 'class_list');
    if(!is_array($class_list)){
        $error .= '站点ID'.$row['shequ_id'].'获取分类列表失败：'.$class_list.'<br/>';
        $fail++;
        continue;
    }
    
    // 获取上次同步位置
    $last_class = $DB->getColumn("SELECT v FROM pre_config WHERE k='last_sync_class_".$row['shequ_id']."'");
    $last_goods = $DB->getColumn("SELECT v FROM pre_config WHERE k='last_sync_goods_".$row['shequ_id']."'");
    
    // 记录已同步的商品数量
    $synced_count = 0;
    $start_sync = false;
    
    // 如果允许添加分类,先处理所有分类
    if($row['sync_class']==1 && $row['add_class']==1){
        foreach($class_list as $sort => $class){
            $exists_class = $DB->getRow("select cid from pre_class where name=:name limit 1", [':name'=>$class['name']]);
            if(!$exists_class){
                $sql="insert into `pre_class` (`name`,`shopimg`,`sort`,`active`) values (:name,:shopimg,:sort,1)";
                if($DB->exec($sql, [':name'=>$class['name'], ':shopimg'=>isset($class['shopimg'])?$class['shopimg']:'', ':sort'=>$sort+1])){
                    $class_success++;
                }
            }else{
                // 只有在启用了分类排序同步时才更新排序
                if($row['sync_sort']==1){
                    $DB->exec("update pre_class set sort=:sort where cid=:cid", [':sort'=>$sort+1, ':cid'=>$exists_class['cid']]);
                }
            }
        }
    }
    
    foreach($class_list as $class){
        // 如果已达到同步数量限制则跳出
        if($synced_count >= $row['sync_limit']){
            // 保存当前位置
            $DB->exec("REPLACE INTO pre_config SET k='last_sync_class_".$row['shequ_id']."',v='".$class['cid']."'");
            $DB->exec("REPLACE INTO pre_config SET k='last_sync_goods_".$row['shequ_id']."',v='0'");
            break;
        }
        
        // 判断是否从上次位置继续
        if(!$last_class || $start_sync){
            $start_sync = true;
        }elseif($class['cid'] == $last_class){
            $start_sync = true;
            continue;
        }else{
            continue;
        }
        
        // 获取商品列表
        $goods_list = third_call($row['type'], $row, 'goods_list_by_cid', [$class['cid']]);
        if(!is_array($goods_list)){
            $error .= '站点ID'.$row['shequ_id'].'分类ID'.$class['cid'].'获取商品列表失败：'.$goods_list.'<br/>';
            continue;
        }
        
        // 处理商品列表
        $start_goods = false;
        foreach($goods_list as $goods){
            // 如果已达到同步数量限制则跳出
            if($synced_count >= $row['sync_limit']){
                // 保存当前位置
                $DB->exec("REPLACE INTO pre_config SET k='last_sync_class_".$row['shequ_id']."',v='".$class['cid']."'");
                $DB->exec("REPLACE INTO pre_config SET k='last_sync_goods_".$row['shequ_id']."',v='".$goods['tid']."'");
                break;
            }
            
            // 判断是否从上次位置继续
            if(!$last_goods || $start_goods){
                $start_goods = true;
            }elseif($goods['tid'] == $last_goods){
                $start_goods = true;
                continue;
            }else{
                continue;
            }
            
            // 查找已存在商品
            $tool = $DB->getRow("SELECT * FROM pre_tools WHERE shequ=:shequ AND goods_id=:goods_id LIMIT 1", [':shequ'=>$row['shequ_id'], ':goods_id'=>$goods['tid']]);
            
            // 如果商品已下架且设置了删除规则
            if($goods['close']==1 && $row['delete_rule']>0){
                if($tool){
                    if($row['delete_rule']==1){
                        // 将商品设为下架
                        $DB->exec("UPDATE pre_tools SET close=1 WHERE tid=:tid", [':tid'=>$tool['tid']]);
                    }elseif($row['delete_rule']==2){
                        // 删除商品
                        $DB->exec("DELETE FROM pre_tools WHERE tid=:tid", [':tid'=>$tool['tid']]);
                    }
                }
                continue;
            }
            
            // 如果商品已存在则更新
            if($tool){
                if($row['auto_update']==1){
                    $data = [];
                    if($row['sync_name']==1) $data['name'] = $goods['name'];
                    if($row['sync_price']==1) $data['price'] = $goods['price'];
                    if($row['sync_cost']==1) $data['cost'] = isset($goods['cost'])?$goods['cost']:0;
                    if($row['sync_desc']==1) $data['desc'] = $goods['desc'];
                    if($row['sync_image']==1) $data['shopimg'] = $goods['shopimg'];
                    if($row['sync_goods_sort']==1) $data['sort'] = isset($goods['sort'])?$goods['sort']:$tool['tid'];
                    if(!empty($data)){
                        $data['close'] = $goods['close'];
                        if($DB->update('tools', $data, ['tid'=>$tool['tid']])!==false){
                            $update_success++;
                            $synced_count++;
                        }
                    }
                }
            }
            // 否则添加新商品
            elseif($row['add_goods']==1){
                // 获取分类ID
                $mcid = 0;
                if($row['sync_class']==1){
                    $exists_class = $DB->getRow("select cid from pre_class where name=:name limit 1", [':name'=>$class['name']]);
                    if($exists_class){
                        $mcid = $exists_class['cid'];
                    }
                }
                
                if($mcid > 0 || $row['sync_class']==0){
                    $sql="INSERT INTO `pre_tools` (`cid`,`name`,`price`,`cost`,`cost2`,`prid`,`prices`,`input`,`inputs`,`desc`,`alert`,`shopimg`,`value`,`is_curl`,`curl`,`shequ`,`goods_id`,`goods_type`,`goods_param`,`repeat`,`multi`,`min`,`max`,`validate`,`valiserv`,`close`,`active`,`addtime`,`sort`) VALUES (:cid,:name,:price,:cost,:cost2,:prid,:prices,:input,:inputs,:desc,:alert,:shopimg,:value,:is_curl,:curl,:shequ,:goods_id,:goods_type,:goods_param,:repeat,:multi,:min,:max,:validate,:valiserv,:close,:active,NOW(),:sort)";
                    $data = [':cid'=>$mcid, ':name'=>$goods['name'], ':price'=>$goods['price'], ':cost'=>0, ':cost2'=>0, ':prid'=>$row['markup_template'], ':prices'=>'', ':input'=>$goods['input'], ':inputs'=>$goods['inputs'], ':desc'=>$goods['desc'], ':alert'=>$goods['alert'], ':shopimg'=>$goods['shopimg'], ':value'=>1, ':is_curl'=>2, ':curl'=>null, ':shequ'=>$row['shequ_id'], ':goods_id'=>$goods['tid'], ':goods_type'=>isset($goods['isfaka'])?($goods['isfaka']?'1':'0'):'0', ':goods_param'=>null, ':repeat'=>isset($goods['repeat'])?$goods['repeat']:0, ':multi'=>isset($goods['multi'])?$goods['multi']:0, ':min'=>isset($goods['min'])?$goods['min']:1, ':max'=>isset($goods['max'])?$goods['max']:1, ':validate'=>isset($goods['validate'])?$goods['validate']:0, ':valiserv'=>isset($goods['valiserv'])?$goods['valiserv']:0, ':close'=>isset($goods['close'])?$goods['close']:0, ':active'=>1, ':sort'=>0];
                    if($DB->exec($sql, $data)!==false){
                        $add_success++;
                        $synced_count++;
                        
                        // 如果启用了商品排序同步，优先使用对接站点的sort值，如果没有则使用tid
                        if($row['sync_goods_sort']==1){
                            $tid = $DB->lastInsertId();
                            $sort = isset($goods['sort'])?$goods['sort']:$tid;
                            $DB->exec("UPDATE pre_tools SET sort=:sort WHERE tid=:tid", [':sort'=>$sort, ':tid'=>$tid]);
                        }
                        
                        // 根据配置决定是否添加商品上架日志
                        if($row['sync_log']==1){
                            $log_content = "【商品上架】" . $goods['name'];
                            $today = date('Y-m-d');
                            // 检查今天是否已有日志
                            $log = $DB->getRow("select * from pre_toollogs where date=:date limit 1", [':date'=>$today]);
                            if($log){
                                // 如果已有日志则追加内容
                                $new_content = $log['content'] . "\n" . $log_content;
                                $DB->exec("update pre_toollogs set content=:content where id=:id", [':content'=>$new_content, ':id'=>$log['id']]);
                            }else{
                                // 如果没有日志则创建新日志
                                $DB->exec("insert into `pre_toollogs` (`content`,`date`,`addtime`,`active`) values (:content,:date,:addtime,1)", 
                                    [':content'=>$log_content, ':date'=>$today, ':addtime'=>$today]);
                            }
                        }
                    }
                }
            }
        }
        
        // 如果已处理完当前分类的所有商品,重置商品位置
        if($synced_count < $row['sync_limit']){
            $DB->exec("REPLACE INTO pre_config SET k='last_sync_goods_".$row['shequ_id']."',v='0'");
        }
    }
    
    // 如果已处理完所有分类,重置分类位置
    if($synced_count < $row['sync_limit']){
        $DB->exec("REPLACE INTO pre_config SET k='last_sync_class_".$row['shequ_id']."',v=''");
    }
    
    $success++;
}

$result = array('code'=>0, 'msg'=>'成功同步'.$success.'个站点,'.$fail.'个站点失败，新增'.$add_success.'个商品，更新'.$update_success.'个商品，新增'.$class_success.'个分类！');
if($error){
    $result['error'] = $error;
}
exit(json_encode($result, JSON_UNESCAPED_UNICODE));
