<?php
include("../includes/common.php");
$title='自动同步设置';
include './head.php';
if($islogin==1){}else exit("<script language='javascript'>window.location.href='./login.php';</script>");

// 获取所有对接站点
$rs = $DB->query("SELECT * FROM pre_shequ order by id asc");
$shequlist = array();
while ($res = $rs->fetch()) {
    $getInfo = \lib\Plugin::getConfig("third_" . $res["type"]);
    if ($getInfo) {
        $res['title'] = $getInfo['title'];
        $shequlist[] = $res;
    }
}

// 获取已启用的配置
$enabled_configs = array();
$rs = $DB->query("SELECT * FROM pre_sync_config WHERE status=1");
while($row = $rs->fetch()){
    $enabled_configs[$row['shequ_id']] = $row;
}

// 处理POST请求
if(isset($_POST['submit'])){
    $shequ_ids = isset($_POST['shequ_ids']) ? $_POST['shequ_ids'] : array();
    $sync_interval = intval($_POST['sync_interval']);
    $sync_limit = intval($_POST['sync_limit']);
    $monitor_key = trim($_POST['monitor_key']);
    
    $success = 0;
    $error = '';
    
    // 先禁用所有配置
    if($DB->exec("UPDATE pre_sync_config SET status=0") === false){
        $error .= '更新状态失败['.$DB->error().']<br/>';
    }
    
    // 处理选中的站点
    if(!empty($shequ_ids)){
        foreach($shequ_ids as $shequ_id){
            $data = [
                'shequ_id' => $shequ_id,
                'sync_interval' => $sync_interval,
                'sync_limit' => $sync_limit,
                'auto_update' => intval($_POST['auto_update_'.$shequ_id]),
                'delete_rule' => intval($_POST['delete_rule_'.$shequ_id]),
                'sync_class' => isset($_POST['sync_class_'.$shequ_id])?1:0,
                'sync_sort' => isset($_POST['sync_sort_'.$shequ_id])?1:0,
                'sync_goods_sort' => isset($_POST['sync_goods_sort_'.$shequ_id])?1:0,
                'sync_log' => isset($_POST['sync_log_'.$shequ_id])?1:0,
                'sync_name' => isset($_POST['sync_name_'.$shequ_id])?1:0,
                'sync_price' => isset($_POST['sync_price_'.$shequ_id])?1:0,
                'sync_cost' => isset($_POST['sync_cost_'.$shequ_id])?1:0,
                'sync_desc' => isset($_POST['sync_desc_'.$shequ_id])?1:0,
                'sync_image' => isset($_POST['sync_image_'.$shequ_id])?1:0,
                'add_class' => isset($_POST['add_class_'.$shequ_id])?1:0,
                'add_goods' => isset($_POST['add_goods_'.$shequ_id])?1:0,
                'markup_template' => intval($_POST['markup_template_'.$shequ_id]),
                'status' => 1,
                'addtime' => $date
            ];
            
            if($DB->getRow("SELECT * FROM pre_sync_config WHERE shequ_id='$shequ_id'")){
                if($DB->update('sync_config', $data, ['shequ_id'=>$shequ_id])){
                    $success++;
                }else{
                    $error .= '站点ID'.$shequ_id.'修改失败['.$DB->error().']<br/>';
                }
            }else{
                if($DB->insert('sync_config', $data)){
                    $success++;
                }else{
                    $error .= '站点ID'.$shequ_id.'添加失败['.$DB->error().']<br/>';
                }
            }
        }
    }
    
    $DB->exec("REPLACE INTO pre_config SET k='monitor_key',v='".$monitor_key."'");
    
    header('Content-Type: application/json; charset=utf-8');
    if($error){
        exit(json_encode(['code'=>0, 'msg'=>$error], JSON_UNESCAPED_UNICODE));
    }else{
        if($success > 0){
            exit(json_encode(['code'=>1, 'msg'=>'成功配置'.$success.'个站点!'], JSON_UNESCAPED_UNICODE));
        }else{
            exit(json_encode(['code'=>1, 'msg'=>'已成功禁用所有同步配置!'], JSON_UNESCAPED_UNICODE));
        }
    }
}

// 获取监控地址
$monitor_key = $DB->getColumn("SELECT v FROM pre_config WHERE k='monitor_key'");
$monitor_url = $siteurl.'admin/cx-api-synchronization.php'.($monitor_key?'?key='.$monitor_key:'');
// 获取最近运行时间
$last_run_time = $DB->getColumn("SELECT v FROM pre_config WHERE k='last_sync_time'");
if(!$last_run_time) $last_run_time = '从未运行';
?>

<div class="col-xs-12 col-sm-10 col-lg-8 center-block" style="float: none;">
    <div class="block">
        <div class="block-title"><h3 class="panel-title">自动同步设置</h3></div>
        <div class="card">
            <div class="card-body">
                <form onsubmit="return save()" method="post" class="form-horizontal" role="form">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">监控地址</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" value="<?php echo $monitor_url?>" readonly>
                            <small class="help-block">请将此地址添加到服务器计划任务,建议执行频率为5分钟</small>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">最近运行</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" value="<?php echo $last_run_time?>" readonly>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">计划任务</label>
                        <div class="col-sm-10">
                            <pre>*/5 * * * * curl --silent <?php echo $monitor_url?></pre>
                            <small class="help-block">Linux服务器Crontab计划任务设置示例</small>
                        </div>
                    </div>
                    <hr/>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">监控密钥</label>
                        <div class="col-sm-10">
                            <div class="input-group">
                                <input type="text" class="form-control" name="monitor_key" value="<?php echo $monitor_key?>" placeholder="请设置监控密钥">
                                <span class="input-group-btn">
                                    <button class="btn btn-default" type="button" onclick="generateKey()">生成密钥</button>
                                </span>
                            </div>
                            <small class="help-block">设置后需要在监控地址后面加上 ?key=监控密钥 才能访问，为空则不限制访问</small>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">选择站点</label>
                        <div class="col-sm-10">
                            <div class="site-nav">
                                <div class="site-nav-header">
                                    <div class="site-nav-title">
                                        <h4>对接站点列表</h4>
                                        <span class="site-count">已选择 <b id="selected_count">0</b> 个站点</span>
                                    </div>
                                    <div class="site-nav-actions">
                                        <label class="select-all">
                                            <input type="checkbox" onclick="checkAll(this)">
                                            <span>全选</span>
                                        </label>
                                        <a href="./shequlist.php" class="btn btn-link">
                                            <i class="fa fa-plus"></i> 添加站点
                                        </a>
                                    </div>
                                </div>
                                <div class="site-list">
                                    <?php foreach($shequlist as $row){
                                        $checked = isset($enabled_configs[$row['id']]) ? ' checked' : '';
                                        echo '<div class="site-item'.($checked?' active':'').'">';
                                        echo '<div class="site-item-header">';
                                        echo '<label class="site-checkbox">';
                                        echo '<input type="checkbox" name="shequ_ids[]" value="'.$row['id'].'" onclick="toggleSiteConfig(this,'.$row['id'].')"'.$checked.'>';
                                        echo '<span class="site-title">'.$row['title'].'</span>';
                                        echo '</label>';
                                        echo '<div class="site-url">'.$row['url'].'</div>';
                                        if($row['remark']) echo '<div class="site-remark">'.$row['remark'].'</div>';
                                        echo '</div>';
                                        
                                        echo '<div class="site-config'.($checked?' show':'').'" id="config_'.$row['id'].'">';
                                        echo '<div class="config-section">';
                                        echo '<div class="config-title">基础设置</div>';
                                        echo '<div class="config-row">';
                                        echo '<div class="config-item">';
                                        echo '<label>自动更新</label>';
                                        echo '<select name="auto_update_'.$row['id'].'" class="form-control">';
                                        echo '<option value="1">开启</option>';
                                        echo '<option value="0">关闭</option>';
                                        echo '</select>';
                                        echo '</div>';
                                        echo '<div class="config-item">';
                                        echo '<label>下架商品处理</label>';
                                        echo '<select name="delete_rule_'.$row['id'].'" class="form-control">';
                                        echo '<option value="0">保留商品</option>';
                                        echo '<option value="1">下架商品</option>';
                                        echo '<option value="2">删除商品</option>';
                                        echo '</select>';
                                        echo '<small class="select-desc">保留商品：不处理下架商品<br>下架商品：将下架商品设为下架状态<br>删除商品：直接删除下架商品</small>';
                                        echo '</div>';
                                        echo '</div>';
                                        echo '</div>';
                                        
                                        echo '<div class="config-section">';
                                        echo '<div class="config-title">同步选项</div>';
                                        echo '<div class="checkbox-group">';
                                        echo '<label class="checkbox-item" title="同步商品分类信息，更新商品所属分类"><input type="checkbox" name="sync_class_'.$row['id'].'" value="1"><span>分类</span><small class="option-desc">更新商品所属分类，仅影响已有商品</small></label>';
                                        echo '<label class="checkbox-item" title="同步分类排序"><input type="checkbox" name="sync_sort_'.$row['id'].'" value="1"><span>分类排序</span><small class="option-desc">同步分类的排序</small></label>';
                                        echo '<label class="checkbox-item" title="同步商品排序"><input type="checkbox" name="sync_goods_sort_'.$row['id'].'" value="1"><span>商品排序</span><small class="option-desc">同步商品的排序</small></label>';
                                        echo '<label class="checkbox-item" title="记录商品上架日志"><input type="checkbox" name="sync_log_'.$row['id'].'" value="1"><span>上架日志</span><small class="option-desc">新增商品时记录上架日志</small></label>';
                                        echo '<label class="checkbox-item" title="同步商品名称"><input type="checkbox" name="sync_name_'.$row['id'].'" value="1"><span>名称</span><small class="option-desc">同步商品名称</small></label>';
                                        echo '<label class="checkbox-item" title="同步商品销售价格"><input type="checkbox" name="sync_price_'.$row['id'].'" value="1"><span>价格</span><small class="option-desc">同步商品销售价格</small></label>';
                                        echo '<label class="checkbox-item" title="同步商品成本价格"><input type="checkbox" name="sync_cost_'.$row['id'].'" value="1"><span>成本</span><small class="option-desc">同步商品成本价格</small></label>';
                                        echo '<label class="checkbox-item" title="同步商品详细描述"><input type="checkbox" name="sync_desc_'.$row['id'].'" value="1"><span>描述</span><small class="option-desc">同步商品详细描述</small></label>';
                                        echo '<label class="checkbox-item" title="同步商品图片资源"><input type="checkbox" name="sync_image_'.$row['id'].'" value="1"><span>图片</span><small class="option-desc">同步商品图片资源</small></label>';
                                        echo '</div>';
                                        echo '</div>';
                                        
                                        echo '<div class="config-section">';
                                        echo '<div class="config-title">新增选项</div>';
                                        echo '<div class="config-row">';
                                        echo '<div class="config-item">';
                                        echo '<label>加价模板</label>';
                                        echo '<select name="markup_template_'.$row['id'].'" class="form-control">';
                                        echo '<option value="0">不使用加价模板</option>';
                                        $rs=$DB->query("SELECT * FROM pre_price ORDER BY id ASC");
                                        while($res = $rs->fetch()){
                                            echo '<option value="'.$res['id'].'">'.$res['name'].'</option>';
                                        }
                                        echo '</select>';
                                        echo '<small class="select-desc">选择加价模板后，新增商品时将自动应用加价规则</small>';
                                        echo '</div>';
                                        echo '</div>';
                                        echo '<div class="checkbox-group">';
                                        echo '<label class="checkbox-item" title="允许添加新的商品分类，禁用时只能使用已有分类"><input type="checkbox" name="add_class_'.$row['id'].'" value="1"><span>允许新增分类</span><small class="option-desc">禁用时，没有对应分类的商品将不会被添加</small></label>';
                                        echo '<label class="checkbox-item" title="允许添加新的商品"><input type="checkbox" name="add_goods_'.$row['id'].'" value="1"><span>允许新增商品</span><small class="option-desc">允许添加新的商品</small></label>';
                                        echo '</div>';
                                        echo '</div>';
                                        echo '</div>';
                                        echo '</div>';
                                    }?>
                                </div>
                            </div>
                            <small class="help-block">只显示已添加的对接站点，如需添加请前往<a href="./shequlist.php">对接站点管理</a></small>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">同步间隔</label>
                        <div class="col-sm-10">
                            <div class="input-group">
                                <select name="sync_interval" class="form-control" required>
                                    <option value="0">0分钟(调试)</option>
                                    <option value="1">1分钟</option>
                                    <option value="3">3分钟</option>
                                    <option value="5" selected>5分钟</option>
                                    <option value="10">10分钟</option>
                                    <option value="15">15分钟</option>
                                    <option value="30">30分钟</option>
                                    <option value="60">1小时</option>
                                </select>
                                <span class="input-group-addon">建议5分钟以上</span>
                            </div>
                            <small class="help-block">设置两次同步之间的最小时间间隔。0分钟表示每次都同步，仅建议在调试时使用，正式运行时建议设置5分钟以上，以免对接站点压力过大</small>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">同步数量</label>
                        <div class="col-sm-10">
                            <div class="input-group">
                                <select name="sync_limit" class="form-control" required>
                                    <option value="10">10个/次</option>
                                    <option value="30">30个/次</option>
                                    <option value="50" selected>50个/次</option>
                                    <option value="100">100个/次</option>
                                    <option value="200">200个/次</option>
                                    <option value="500">500个/次</option>
                                    <option value="1000">1000个/次</option>
                                </select>
                                <span class="input-group-addon">建议50个/次</span>
                            </div>
                            <small class="help-block">每次同步的最大商品数量,数量越大同步越快,但也越容易超时,建议根据服务器性能调整</small>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <input type="submit" name="submit" value="保存" class="btn btn-primary form-control"/>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
</div></div>
<script>
function toggleSiteConfig(checkbox, siteId) {
    var $siteItem = $(checkbox).closest('.site-item');
    if($(checkbox).prop('checked')) {
        $siteItem.addClass('active');
        $('#config_' + siteId).addClass('show');
    } else {
        $siteItem.removeClass('active');
        $('#config_' + siteId).removeClass('show');
    }
    updateCount();
}

function checkAll(obj){
    var checked = $(obj).prop('checked');
    $("input[name='shequ_ids[]']").each(function(){
        $(this).prop('checked', checked);
        toggleSiteConfig(this, $(this).val());
    });
}

function updateCount(){
    var count = $("input[name='shequ_ids[]']:checked").length;
    $("#selected_count").text(count);
}

function save(){
    var ii = layer.load(2, {shade:[0.1,'#fff']});
    $.ajax({
        type : 'POST',
        url : window.location.href,
        data : $("form").serialize() + '&submit=1',
        dataType : 'json',
        success : function(data) {
            layer.close(ii);
            if(data.code == 1){
                layer.alert(data.msg, {icon: 1}, function(){
                    window.location.reload();
                });
            }else{
                layer.alert(data.msg, {icon: 2});
            }
        },
        error:function(data){
            layer.close(ii);
            layer.msg('服务器错误');
            $("input[type='submit']").attr("disabled",false);
        }
    });
    return false;
}

function generateKey() {
    var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    var key = "";
    for(var i=0; i<32; i++) {
        key += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    $("input[name=\'monitor_key\']").val(key);
}

$(document).ready(function(){
    updateCount();
    // 加载已保存的配置
    <?php
    foreach($enabled_configs as $config){
        echo 'var config_'.$config['shequ_id'].' = '.json_encode($config).';';
        echo '
        if(config_'.$config['shequ_id'].'){
            var siteId = '.$config['shequ_id'].';
            $("#config_"+siteId).show();
            $("select[name=\'auto_update_"+siteId+"\']").val(config_'.$config['shequ_id'].'.auto_update);
            $("select[name=\'delete_rule_"+siteId+"\']").val(config_'.$config['shequ_id'].'.delete_rule);
            $("select[name=\'markup_template_"+siteId+"\']").val(config_'.$config['shequ_id'].'.markup_template);
            $("input[name=\'sync_class_"+siteId+"\']").prop("checked", config_'.$config['shequ_id'].'.sync_class == 1);
            $("input[name=\'sync_sort_"+siteId+"\']").prop("checked", config_'.$config['shequ_id'].'.sync_sort == 1);
            $("input[name=\'sync_goods_sort_"+siteId+"\']").prop("checked", config_'.$config['shequ_id'].'.sync_goods_sort == 1);
            $("input[name=\'sync_log_"+siteId+"\']").prop("checked", config_'.$config['shequ_id'].'.sync_log == 1);
            $("input[name=\'sync_name_"+siteId+"\']").prop("checked", config_'.$config['shequ_id'].'.sync_name == 1);
            $("input[name=\'sync_price_"+siteId+"\']").prop("checked", config_'.$config['shequ_id'].'.sync_price == 1);
            $("input[name=\'sync_cost_"+siteId+"\']").prop("checked", config_'.$config['shequ_id'].'.sync_cost == 1);
            $("input[name=\'sync_desc_"+siteId+"\']").prop("checked", config_'.$config['shequ_id'].'.sync_desc == 1);
            $("input[name=\'sync_image_"+siteId+"\']").prop("checked", config_'.$config['shequ_id'].'.sync_image == 1);
            $("input[name=\'add_class_"+siteId+"\']").prop("checked", config_'.$config['shequ_id'].'.add_class == 1);
            $("input[name=\'add_goods_"+siteId+"\']").prop("checked", config_'.$config['shequ_id'].'.add_goods == 1);
        }';
    }
    ?>
    
    // 设置公共配置
    var first_config = null;
    <?php
    foreach($enabled_configs as $config){
        echo 'first_config = '.json_encode($config).';';
        break;
    }
    ?>
    if(first_config){
        $("select[name='sync_interval']").val(first_config.sync_interval);
        $("select[name='sync_limit']").val(first_config.sync_limit);
    }
});
</script>
<style>
/* 导航栏样式 */
.site-nav {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.05);
    overflow: hidden;
}

.site-nav-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 24px;
    background: #f8fafc;
    border-bottom: 1px solid #e2e8f0;
}

.site-nav-title {
    display: flex;
    align-items: center;
    gap: 16px;
}

.site-nav-title h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #1a202c;
}

.site-count {
    font-size: 14px;
    color: #64748b;
}

.site-count b {
    color: #3182ce;
}

.site-nav-actions {
    display: flex;
    align-items: center;
    gap: 16px;
}

.select-all {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    font-weight: normal;
    margin: 0;
}

.site-list {
    padding: 16px;
}

/* 站点项样式 */
.site-item {
    background: #fff;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    margin-bottom: 16px;
    transition: all 0.2s;
}

.site-item:hover {
    border-color: #90cdf4;
}

.site-item.active {
    border-color: #4299e1;
}

.site-item-header {
    padding: 16px 20px;
    cursor: pointer;
}

.site-checkbox {
    display: flex;
    align-items: center;
    gap: 12px;
    margin: 0;
    cursor: pointer;
    font-weight: normal;
}

.site-title {
    font-size: 15px;
    font-weight: 500;
    color: #2d3748;
}

.site-url {
    margin-top: 8px;
    font-size: 13px;
    color: #718096;
}

.site-remark {
    margin-top: 4px;
    font-size: 12px;
    color: #a0aec0;
}

/* 配置区域样式 */
.site-config {
    display: none;
    padding: 0 20px 20px;
    border-top: 1px solid #e2e8f0;
    background: #f8fafc;
}

.site-config.show {
    display: block;
}

.config-section {
    margin-top: 20px;
}

.config-title {
    font-size: 14px;
    font-weight: 600;
    color: #2d3748;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
}

.config-title:before {
    content: "";
    display: inline-block;
    width: 4px;
    height: 16px;
    background: #4299e1;
    margin-right: 8px;
    border-radius: 2px;
}

.config-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
}

.config-item {
    margin-bottom: 16px;
}

.config-item label {
    display: block;
    margin-bottom: 8px;
    color: #4a5568;
    font-size: 13px;
}

.checkbox-group {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 12px;
    margin-bottom: 8px;
}

.checkbox-item {
    position: relative;
    display: flex;
    align-items: flex-start;
    flex-wrap: wrap;
    padding: 12px 16px;
    background: #fff;
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.2s;
    margin: 0;
    font-weight: normal;
    min-height: 48px;
}

.checkbox-item:hover {
    border-color: #90cdf4;
    background: #ebf8ff;
}

.checkbox-item input[type="checkbox"] {
    flex-shrink: 0;
    width: 16px;
    height: 16px;
    margin: 2px 8px 0 0;
}

.checkbox-item span {
    font-size: 13px;
    color: #2d3748;
    font-weight: 500;
    margin-right: 8px;
    white-space: nowrap;
}

.option-desc {
    font-size: 12px;
    color: #718096;
    margin-top: 4px;
    width: 100%;
    display: block;
    word-break: break-word;
}

/* 基础设置下拉框描述 */
.config-item select {
    margin-bottom: 4px;
}

.config-item .select-desc {
    font-size: 12px;
    color: #718096;
    display: block;
    margin-top: 4px;
}

/* 美化表单控件 */
.form-control {
    height: 36px;
    padding: 0 12px;
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    box-shadow: none;
    color: #4a5568;
    font-size: 14px;
    background-color: #fff;
    transition: all 0.2s;
}

.form-control:focus {
    border-color: #4299e1;
    box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.15);
}

.form-control:hover {
    border-color: #cbd5e0;
}

/* 按钮样式 */
.btn-link {
    color: #4299e1;
    text-decoration: none;
    font-size: 14px;
}

.btn-link:hover {
    color: #2b6cb0;
    text-decoration: none;
}

.btn-link i {
    margin-right: 4px;
}

@media (max-width: 768px) {
    .site-nav-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
    }
    
    .site-nav-actions {
        width: 100%;
        justify-content: space-between;
    }
    
    .config-row {
        grid-template-columns: 1fr;
    }
    
    .checkbox-group {
        grid-template-columns: 1fr;
    }
    
    .checkbox-item {
        padding: 10px 12px;
    }
    
    .site-item-header {
        padding: 12px 16px;
    }
    
    .site-config {
        padding: 0 16px 16px;
    }
    
    .col-sm-10 {
        padding-left: 15px;
        padding-right: 15px;
    }
    
    .form-group {
        margin-bottom: 15px;
    }
    
    .control-label {
        margin-bottom: 8px;
    }
}
</style>
<?php include './foot.php';?> 