<?php
require '../conn/conn.php';
require '../conn/function.php';
require 'member_check.php';
$page=$_GET["page"];
$action=$_GET["action"];
$S_id=intval($_GET["S_id"]);
$sort=intval($_GET["sort"]);

if($page==""){
  $page=1;
}

if($S_id!=""){
  $aa="edit&S_id=".$S_id;
  $sql="select * from sl_short where S_id=".$S_id;
  $result = mysqli_query($conn, $sql);
  $row = mysqli_fetch_assoc($result);
  if (mysqli_num_rows($result) > 0) {
    $S_short=$row["S_short"];
    $S_remark=$row["S_remark"];
    $S_sort=$row["S_sort"];
    $S_times=$row["S_times"];
    $S_time=$row["S_time"];
    $S_type=$row["S_type"];
    $S_vip=$row["S_vip"];
    $S_fit=$row["S_fit"];
    $S_statistics=$row["S_statistics"];
    $S_statistics_domain=$row["S_statistics_domain"];
    $S_url=urldecode($row["S_url"]);
  }
  $title="编辑";
}else{
  $S_vip=0;
  $S_sort=0;
  $S_fit=0;
  $aa="add";
  $title="新增";
}

if($action=="up"){
  $_POST["M_id"]=$M_id;
  $_POST["S_id"]=$S_id;
  if($M_vip==1){
      $_POST["C_urlprice"]=0;
  }else{
      $_POST["C_urlprice"]=$C_urlprice;
  }
  if($C_urlprice>0){
    if($M_money-$C_urlprice>=0){
      $time=date('Y-m-d H:i:s');
      $no=date('YmdHis') . rand(10000000,99999999);
      $arr=json_decode(member("url_up",$_POST),true);
      mysqli_query($conn,$arr["up1"]);
      mysqli_query($conn,$arr["up2"]);
      mysqli_query($conn,$arr["up3"]);
      die("{\"msg\":\"success\"}");
    }else{
      die("{\"msg\":\"账户余额不足，请先充值！\"}");
    }
  }else{
    die("{\"msg\":\"金额有误！\"}");
  }
}

if($action=="edit"){
  $S_url=$_POST["S_url"];
  $_POST["S_id"]=$S_id;
  $_POST["M_id"]=$M_id;
  if($S_url!=""){
    mysqli_query($conn, member("url_edit",$_POST));
    mysqli_query($conn, "update sl_short set S_remark='".t($_POST["S_remark"])."',S_type=".intval($_POST["S_type"]).",S_fit=".intval($_POST["S_fit"]).",S_statistics='".$_POST["S_statistics"]."',S_statistics_domain='".$_POST["S_statistics_domain"]."' where S_id=".$S_id." and S_mid=".$M_id);
    die("{\"msg\":\"success\",\"id\":\"".$S_id."\"}");
  }else{
    die("{\"msg\":\"请填全信息\"}");
  }
}

if($action=="delall"){
  $id=$_POST["id"];
  $_POST["M_id"]=$M_id;
  if(count($id)>0){
    $shu=0;
    for ($i=0 ;$i<count($id);$i++){
      $_POST["S_id"]=$id[$i];
      mysqli_query($conn,member("url_del",$_POST));
      $shu=$shu+1 ;
      $ids=$ids.$id[$i].",";
    }
    $ids= substr($ids,0,strlen($ids)-1);
    if($shu>0) {
      die("{\"msg\":\"success\",\"ids\":\"".$ids."\"}");
    } else {
      die("{\"msg\":\"删除失败\"}");
    }
  } else {
    die("{\"msg\":\"未选择要删除的内容\"}");
  }
}


if($action=="excel"){
  $sql="select S_id,S_url,S_time,S_vip,S_times,S_short,S_mid from sl_short where S_mid=$M_id";
  $result = mysqli_query($conn, $sql);
  $arr = array();
  while($row = mysqli_fetch_array($result)) {
    $row["S_url"]=urldecode($row["S_url"]);
  $count=count($row);
    for($i=0;$i<$count;$i++){ 
      unset($row[$i]);
    }
    array_push($arr,$row);
  } 

  exportToCsv(["ID","原始链接","生成时间","是否永久","点击次数","短链接","所属会员ID"] , $arr ,'short_'.date('YmdHis'),[]);
  die();
}


$sql="select count(S_id) as S_count from sl_short where S_mid=$M_id and S_sort=".$sort;
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$S_counts=$row["S_count"];
?>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<title>短链接管理 - 后台管理</title>
<link rel="icon" href="../media/<?php echo $C_ico?>" type="image/ico">
<link href="../css/bootstrap.min.css" rel="stylesheet">
<link href="../css/materialdesignicons.min.css" rel="stylesheet">
<link href="../css/style.min.css" rel="stylesheet">
<link rel="stylesheet" href="../js/jconfirm/jquery-confirm.min.css">
<style type="text/css">

.showpic{height: 100px;border: solid 1px #DDDDDD;padding: 5px;}
.showpicx{width: 100%;max-width: 500px}
.list-group a{text-decoration:none}
.part{display:inline-block;width:40%;overflow:hidden;text-overflow:ellipsis;white-space: nowrap;}
.pagination{margin: 0px;}
</style>
</head>
  
<body>
<div class="lyear-layout-web">
  <div class="lyear-layout-container">
  <?php require 'nav.php';?>
    <main class="lyear-layout-content">
      <div class="container-fluid">
        <div class="row">
                <div class="col-lg-6">
                  <form id="list">
                  <div class="card card-primary">
                    <div class="card-header">
                      <h4>短链接分组</h4>
                      <a class="pull-right btn btn-xs btn-warning" href="sort.php">新增分组</a>
                    </div>
                    <div class="card-body">
                      <a href="?sort=0" class="
                      <?php
                      if($sort==0){
                        echo "btn btn-primary";
                      }else{
                        echo "btn btn-default";
                      }
                      ?>
                      ">默认分组（<?php echo getrs("select count(S_id) as S_count from sl_short where S_sort=0 and S_mid=$M_id","S_count");?>）</a>

                      <?php
                      $sql="select * from sl_sort where S_mid=0 or S_mid=".intval($_SESSION["M_id"]);
                      $result = mysqli_query($conn,  $sql);
                      if (mysqli_num_rows($result) > 0) {
                      while($row = mysqli_fetch_assoc($result)) {
                              if($sort==$row["S_id"]){
                                $class="btn btn-primary";
                              }else{
                                $class="btn btn-default";
                              }
                              $count=getrs("select count(S_id) as S_count from sl_short where S_sort=".$row["S_id"]." and S_mid=$M_id","S_count");
                              echo "<a href=\"?sort=".$row["S_id"]."\" class=\"".$class."\">".$row["S_title"]."（".$count."）</a> ";
                          }
                      } 
                      ?>
                    </div>
                  </div>

                  <div class="card card-primary">
                    <div class="card-header">
                      <h4>短链接列表</h4>

                      <a class="pull-right btn btn-xs btn-success" href="creat.php">生成短链</a>
                      <a class="pull-right btn btn-xs btn-info" href="?action=excel" style="margin-right: 10px;">导出excel</a>
                    </div>
                        <ul class="list-group">
                          <li class="list-group-item " style="background: #f7f7f7"><div class="part">短链接</div><div class="part">原网址/生成时间</div><div class="pull-right">会员/访问次数</div></li>
                          <?php 
                            $sql="select * from sl_short where S_mid=".$M_id." and S_sort=".$sort." order by S_time desc,S_id desc limit ".(($page-1)*10).",10";
                                $result = mysqli_query($conn, $sql);
                                if (mysqli_num_rows($result) > 0) {
                                while($row = mysqli_fetch_assoc($result)) {
                                  if($row["S_id"]==$S_id){
                                    $active="active";
                                  }else{
                                    $active="";
                                  }

                                  if($row["S_vip"]==1){
                                    $vip="<span style=\"color:#090;font-weight:bold;border:solid 1px #090;font-size:12.5px;padding:2px 5px;\">永久短链</span>";
                                  }else{
                                    $vip="<span style=\"color:#f60;font-weight:bold;border:solid 1px #f60;font-size:12.5px;padding:2px 5px;\">".$C_day."天临时短链</span> <button class=\"btn btn-xs btn-warning\" type=\"button\" onclick=\"up('".$row["S_id"]."');return false;\">升级</button>";
                                  }

                                  switch($row["S_type"]){
                                    case 0:
                                    $type="普通跳转";
                                    break;
                                    case 1:

                                    $type="防红跳转";
                                    break;

                                    case 2:
                                    $type="强开直链";
                                    break;

                                  }

                                  switch($row["S_mid"]){
                                    case -1:
                                    $M_login="管理员";
                                    break;
                                    case 0:
                                    $M_login="未登录";
                                    break;
                                    default:
                                    $M_login=getrs("select * from sl_member where M_id=".$row["S_mid"],"M_login");
                                    break;
                                  }

                                  echo "<a id=\"".$row["S_id"]."\" href=\"?S_id=".$row["S_id"]."&page=$page\" class=\"list-group-item ".$active."\">
                                  <div class=\"part\"><input type=\"checkbox\" name=\"id[]\" value=\"".$row["S_id"]."\"> <b>".$row["S_short"]."</b><br>".$vip." <button class=\"btn btn-xs btn-danger\" type=\"button\" onclick=\"window.location.href='statistics.php?id=".$row["S_id"]."';return false;\">统计</button> ".$type."</div> 
                                  <div class=\"part\"><b>".urldecode($row["S_url"])."</b><br>".$row["S_time"]."</div>
                                  <div class=\"pull-right\" style=\"text-align:right\"><b>".$M_login."</b><br>".$row["S_times"]."次</div>
                                  </a>";
                                }
                              }
                                
                          ?>
                        </ul>
                  </div>
                  <label><input type="checkbox" id="selectAll" name="selectAll"> 全选</label>
                  <button class="btn btn-sm btn-danger" type="button" onClick="delall()"><i class="fa fa-times-circle" ></i> 删除所选</button>
                  <a href="creat.php" class="btn btn-sm btn-primary"><i class="fa fa-plus-circle"></i> 新增短链接</a>
                  <ul class="pagination" id="pagination" style="float: right;"></ul>
                  <input type="hidden" id="PageCount" runat="server" />
                  <input type="hidden" id="PageSize" runat="server" value="10" />
                  <input type="hidden" id="countindex" runat="server" value="10"/>
                  <!--设置最多显示的页码数 可以手动设置 默认为7-->
                  <input type="hidden" id="visiblePages" runat="server" value="7" />
                </form>
                </div>

                <?php if($S_id!=""){?>
                <div class="col-lg-6">
                  <form id="form">
                  <div class="card card-primary">
                    <div class="card-header ">
                      <h4><?php echo $title?>短链接</h4>
                    </div>
                    <div class="card-body">

                      <div class="form-group row">
                          <label class="col-md-3 col-form-label" >二维码活码</label>
                          <div class="col-md-9">
                            <p><img src="../qrcode.php?url=<?php echo $S_short?>" style="width: 200px;"></p>
                          </div>
                        </div>

                        <div class="form-group row">
                          <label class="col-md-3 col-form-label" >短链接</label>
                          <div class="col-md-9">
                            <p><?php echo $S_short?></p>
                          </div>
                        </div>

                          <div class="form-group row">
                            <label class="col-md-3 col-form-label" >指向网址</label>
                            <div class="col-md-9">
                              <input type="text"  name="S_url" class="form-control" value="<?php echo $S_url?>">
                            </div>
                          </div>


                          <div class="form-group row">
                            <label class="col-md-3 col-form-label" >短链备注</label>
                            <div class="col-md-9">
                              <input type="text"  name="S_remark" class="form-control" value="<?php echo $S_remark?>">
                            </div>
                          </div>


                          <div class="form-group row">
                            <label class="col-md-3 col-form-label" >短链分组</label>
                            <div class="col-md-9">
                              <select class="form-control" name="S_sort">
                                <option value="0" <?php
                                if($S_sort==0){
                                           echo "selected='selected'";
                                          }else{
                                          echo "";
                                          }
                                ?>>默认分组</option>
                                <?php
                                  $sql="select * from sl_sort where S_mid=0 or S_mid=".intval($_SESSION["M_id"]);
                                  $result = mysqli_query($conn,  $sql);
                                  if (mysqli_num_rows($result) > 0) {
                                  while($row = mysqli_fetch_assoc($result)) {
                                          if($S_sort==$row["S_id"]){
                                            $selected="selected='selected'";
                                          }else{
                                            $selected="";
                                          }
                                          echo "<option value=\"".$row["S_id"]."\" $selected>".$row["S_title"]."</option>";
                                      }
                                  } 
                                ?>
                              </select>
                            </div>
                          </div>

                          <div class="form-group row">
                          <label class="col-md-3 col-form-label" >跳转方式</label>
                          <div class="col-md-9">
                            <label><input type="radio" name="S_type" value="0" <?php if($S_type==0){echo "checked='checked'";}?>> 普通跳转</label>
                            <label><input type="radio" name="S_type" value="1" <?php if($S_type==1){echo "checked='checked'";}?>> 防红跳转</label>
                            <label><input type="radio" name="S_type" value="2" <?php if($S_type==2){echo "checked='checked'";}?>> 强开直链</label>
                          </div>
                        </div>
                        
                        <div class="form-group row">
                          <label class="col-md-3 col-form-label" >页面自适应</label>
                          <div class="col-md-9">
                            <label><input type="radio" name="S_fit" value="1" <?php if($S_fit==1){echo "checked='checked'";}?>> 是</label>
                            <label><input type="radio" name="S_fit" value="0" <?php if($S_fit==0){echo "checked='checked'";}?>> 否</label>

                          </div>
                        </div>

                          <div class="form-group row">
                            <label class="col-md-3 col-form-label" >生成时间</label>
                            <div class="col-md-9">
                              <p><?php echo $S_time?></p>
                            </div>
                          </div>

                          <div class="form-group row">
                            <label class="col-md-3 col-form-label" >短链时效</label>
                            <div class="col-md-9">
                              <p><?php if($S_vip==1){echo "永久短链";}else{echo $C_day."天临时短链 <button class=\"btn btn-xs btn-danger\" type=\"button\" onclick=\"up('".$S_id."')\">升级</button>";}?></p>
                            </div>
                          </div>

                          <div class="form-group row">
                            <label class="col-md-3 col-form-label" >访问次数</label>
                            <div class="col-md-9">
                              <p><?php echo $S_times?></p>
                            </div>
                          </div>

                          <div class="form-group row">
                            <label class="col-md-3 col-form-label" >第三方统计代码</label>
                            <div class="col-md-9">
                              <textarea  name="S_statistics" class="form-control" ><?php echo $S_statistics?></textarea>
                            </div>
                          </div>

                          <div class="form-group row">
                            <label class="col-md-3 col-form-label" >统计网站 <?php
                          if($S_statistics_domain!=""){
                            echo "<a href=\"".$S_statistics_domain."\" target=\"_blank\">直达</a>";
                          }
                          ?></label>
                            <div class="col-md-9">
                              <input type="text"  name="S_statistics_domain" class="form-control" value="<?php echo $S_statistics_domain?>">

                            </div>
                          </div>

                        <div class="form-group row">
                          <label class="col-md-3 col-form-label" ></label>
                          <div class="col-md-9">
                            <button class="btn btn-info" type="button" onClick="save()"><?php echo $title?></button>
                          </div>
                        </div>
                    </div>
                  </div>
                  </form>
                </div>
                <?php }?>
              </div>
        
      </div>
      
    </main>
    <!--End 页面主要内容-->
  </div>
</div>

<script type="text/javascript" src="../js/jquery.min.js"></script>
<script type="text/javascript" src="../js/bootstrap.min.js"></script>
<script type="text/javascript" src="../js/perfect-scrollbar.min.js"></script>
<script type="text/javascript" src="../js/main.min.js"></script>

<script src="../js/bootstrap-notify.min.js"></script>
<script type="text/javascript" src="../js/lightyear.js"></script>
<script src="../js/jqPaginator.min.js" type="text/javascript"></script>
<script src="../js/jconfirm/jquery-confirm.min.js"></script>
<script type="text/javascript">

  function loadData(num) {
            $("#PageCount").val("<?php echo $S_counts?>");
        }
function loadpage(id) {
    var myPageCount = parseInt($("#PageCount").val());
    var myPageSize = parseInt($("#PageSize").val());
    var countindex = myPageCount % myPageSize > 0 ? (myPageCount / myPageSize) + 1 : (myPageCount / myPageSize);
    $("#countindex").val(countindex);

    $.jqPaginator('#pagination', {
        totalPages: parseInt($("#countindex").val()),
        visiblePages: parseInt($("#visiblePages").val()),
        currentPage: id,
        first: '<li class="first page-item"><a href="javascript:;" class="page-link">|<</a></li>',
        prev: '<li class="prev page-item"><a href="javascript:;" class="page-link"><i class="arrow arrow2"></i><</a></li>',
        next: '<li class="next page-item"><a href="javascript:;" class="page-link">><i class="arrow arrow3"></i></a></li>',
        last: '<li class="last page-item"><a href="javascript:;" class="page-link">>|</a></li>',
        page: '<li class="page page-item"><a href="javascript:;" class="page-link">{{page}}</a></li>',
        onPageChange: function (num, type) {
            if (type == "change") {
                window.location="?sort=<?php echo $sort?>&page="+num;
            }
        }
    });
}
$(function () {
    loadData(<?php echo $page?>);
    loadpage(<?php echo $page?>);

});

    function save(){
      lightyear.loading('show');
        $.ajax({
                url:'?action=<?php echo $aa?>',
                type:'post',
                data:$("#form").serialize(),
                success:function (data) {
                  data=JSON.parse(data);
                  lightyear.loading('hide');
                  if(data.msg=="success"){
                    lightyear.notify('保存成功', 'success', 100);
                    setTimeout("window.location.href='?S_id="+data.id+"'", 2000 )
                  }else{
                      lightyear.notify(data.msg, 'danger', 100);
                  }
                }
              });
      }

      function delall() {

    $.alert({
        title: '确认删除',
        content: '确认删除？',
    buttons: {
      confirm: {
        text: '确认',
        btnClass: 'btn-primary',
        action: function(){
          $.ajax({
            url: '?action=delall',
            type: 'post',
            data: $("#list").serialize(),
            success: function(data) {
                data = JSON.parse(data);
                if (data.msg == "success") {
                  lightyear.notify('删除成功', 'success', 100);
                    id = data.ids.split(",");
                    for (var i = 0; i < id.length; i++) {
                        $("#" + id[i]).hide();
                    };
                } else {
                  lightyear.notify(data.msg, 'danger', 100);

                }
            }
        });
        }
      },
      cancel: {
        text: '取消',
        action: function () {

        }
      }
    }
    });
}

function up(S_id) {
    $.alert({
        title: '确认升级',
        content: '是否<?php
        if($M_vip==1){
            echo "免费";
        }else{
            echo "花费".$C_urlprice."元";
        }
        ?>升级为永久短链并去除广告？',
    buttons: {
      confirm: {
        text: '确认',
        btnClass: 'btn-primary',
        action: function(){
          $.ajax({
            url: '?action=up&S_id='+S_id,
            success: function(data) {
                data = JSON.parse(data);
                if (data.msg == "success") {
                  lightyear.notify('升级成功', 'success', 100);
                  setTimeout("location.reload();", 1000 )
                } else {
                  lightyear.notify(data.msg, 'danger', 100);
                }
            }
        });
        }
      },
      cancel: {
        text: '取消',
        action: function () {

        }
      }
    }
    });
}

$('input[name="selectAll"]').on("click",function(){
        if($(this).is(':checked')){
            $('input[name="id[]"]').each(function(){
                $(this).prop("checked",true);
            });
        }else{
            $('input[name="id[]"]').each(function(){
                $(this).prop("checked",false);
            });
        }
    });
  var path=window.location.pathname;
  $("a").each(function(){
    if(path.indexOf($(this).attr("href"))!=-1){
      console.log($(this).attr("href"));
      $(this).parent("li").addClass("active");
      $(this).parent("li").parent("ul").parent("li").addClass("open active");
    }
  });
</script>
</body>
</html>