<?php
/**
 * 商品管理
 */
$title = '商品管理';
include "header.php";
$sum = 32; #每页数量
$page = shop::page($sum, $_QET['page']); #取出翻页数据
$shop_list = shop::shop_list($sum, $page['count'], $page['limit'], $_QET['cid']); #获取商品列表
$paging = shop::paging($shop_list['count'], $_QET['page']); #取出翻页按钮数据
if (!empty($_QET['unset'])) {
    $a = $DB->query("DELETE FROM `sky_goods` WHERE (`gid`='{$_QET['unset']}')"); #删除
    if ($a) {
        show_msg('成功提示', '编号:' . $_QET['unset'] . '删除成功,请点击下方按钮返回', '1');
    } else show_msg('温馨提示', '编号:' . $_QET['unset'] . '删除失败,原因->' . $DB->error(), '2');
}

$rec = $DB->query("SELECT * FROM `sky_class` ORDER BY `sort` DESC ");
$cid_arr = [];
while ($res = $DB->fetch($rec)) {
    $cid_arr[] = ['cid' => $res['cid'], 'name' => $res['name'], 'state' => $res['state']];
}

?>
<!-- third party css -->
<link href="<?= $cdnserver == null ? '../' : $cdnserver ?>assets/css/vendor/dataTables.bootstrap4.css" rel="stylesheet"
      type="text/css"/>
<link href="<?= $cdnserver == null ? '../' : $cdnserver ?>assets/css/vendor/responsive.bootstrap4.css" rel="stylesheet"
      type="text/css"/>
<!-- third party css end -->
<!-- App css -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <div class="row mb-2">
                    <div class="col-sm-12">
                        <span class="btn btn-group p-0">
                            <select class="custom-select" name="goods_state" style="width: 16em">
                                <option value="">批量操作商品(需选中)</option>
                                <option value="-1">修改状态为上架</option>
                                <option value="-2">修改状态为下架</option>
                                <option value="-3">批量删除商品(危险操作)</option>
                                <option value="-4">批量设置商品参数</option>
                                <?php
                                foreach ($cid_arr as $v) {
                                    $state = $v['state'] == 1 ? '显示中' : '已掩藏';
                                    echo '<option value="' . $v['cid'] . '">移动到分类：' . $v['name'] . '[' . $state . ']</option>';
                                }
                                ?>
                            </select>
                        </span>
                        <a href="admin.goods.add.php" class="btn btn-danger"><i
                                    class="layui-icon layui-icon-add-circle-fine mr-2"></i>
                            添加商品
                        </a>
                        <a href="admin.class.list.php" class="btn btn-warning"><i
                                    class="layui-icon layui-icon-light mr-2"></i>
                            查看分类
                        </a>
                        <a href="admin.order.list.php" class="btn btn-success"><i
                                    class="layui-icon layui-icon-light mr-2"></i>
                            查看订单
                        </a>
                        <a href="javascript:goods.FreightTem()" class="btn btn-info"><i
                                    class="layui-icon layui-icon-light mr-2"></i>
                            运费模板
                        </a>
                        <a href="javascript:goods.profit()" class="btn btn-primary"><i
                                    class="layui-icon layui-icon-light mr-2"></i>
                            利润百分比
                        </a>
                    </div>
                </div>

                <div class="table-responsive">
                    <table id="table" class="table table-centered table-striped dt-responsive nowrap w-100 font-13"
                           id="products-datatable">
                        <thead>
                        <tr style="white-space: nowrap">
                            <th><input name="checkbox_all" id="list_all" type="checkbox" onclick="goods.select_all()"
                                       value="true">GID
                            </th>
                            <th>商品排序</th>
                            <th>商品分类</th>
                            <th>商品图文</th>
                            <th>商品售价</th>
                            <th>利润比例</th>
                            <th>每日库存</th>
                            <th>每份数量</th>
                            <th>对接类型</th>
                            <th>商品状态</th>
                            <th>记事本</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody id="">
                        <?php foreach ($shop_list['data'] as $v) {
                            $arr_pr = price::price_list($v['money'], $mid_arr, $v['profits']);
                            ?>
                            <tr style="white-space: nowrap;font-size: 0.9em">
                                <td>
                                    <input type="checkbox" name="checkbox[]" class="list_box box_<?= $v['gid'] ?>"
                                           onclick="goods.select_id(<?= $v['gid'] ?>)" value="<?= $v['gid'] ?>"/>
                                    <a href="admin.order.list.php?gid=<?= $v['gid'] ?>" title="查看商品下的订单"
                                       class="badge badge-info-lighten">
                                        <?= $v['gid'] ?>
                                    </a>
                                </td>
                                <td>
                                    <?= $v['sort'] ?>
                                </td>
                                <td>
                                    <a href="admin.class.add.php?cid=<?= $v['cids'] ?>"><?= $v['cid'] ?></a>
                                </td>
                                <td class="table-user">
                                    <img src="<?= $v['image'] ?>"
                                         onerror="this.src='../assets/cloud/image/error_img.png'" alt="table-user"
                                         class="mr-2 rounded-circle">
                                    <a href="javascript:layer.alert('商品编号：<?= $v['gid'] ?><br>最少购买：<?= ($v['min'] == '' ? '不限制' : $v['min'] . '个') ?><br>最多购买：<?= ($v['max'] == '' ? '不限制' : $v['max'] . '个') ?><br>购买链接：<a href=<?= is_https(false) . href() . '/?gid=' . $v['gid'] . '&cid=' . $v['cids'] ?> target=_blank ><?= is_https(false) . href() . '/?gid=' . $v['gid'] . '&cid=' . $v['cids'] ?></a><br><a class=\'badge badge-success-lighten font-13 mt-1\' href=javascript:goods.SharePoster(<?= $v['gid'] ?>) >生成商品海报图</a>',{title:'商品信息',btn:false,shade: [0.8, '#000'],shadeClose:true,})"
                                       class="text-body font-weight-semibold"><?= mb_strlen($v['name'], 'utf-8') > 6 ? mb_substr($v['name'], 0, 6, 'utf-8') . '...' : $v['name']; ?></a>
                                </td>
                                <td id="price_<?= $v['gid'] ?>" data-rules=<?= json_encode($arr_pr) ?>>
                                    <span style="color: orangered">[<?= $arr_pr[0]['name'] ?> / 游客售价]</span><br> <a
                                            href="javascript:goods.rules(<?= $v['gid'] ?>,'<?= mb_strlen($v['name'], 'utf-8') > 8 ? mb_substr($v['name'], 0, 8, 'utf-8') . '...' : $v['name']; ?>');">[查看列表]</a> <?= $arr_pr[0]['price'] ?>
                                    元
                                </td>
                                <td>
                                    <span class="layui-badge layui-bg-orange"><?= $v['profits'] ?>%</span>
                                </td>
                                <td>
                                    <?= $v['quota'] ?>份
                                </td>
                                <td>
                                    <?= $v['quantity'] ?>个
                                </td>
                                <td>
                                    <?= $v['sqid'] ?>
                                </td>
                                <td>
                                    <?= $v['state'] ?>
                                </td>
                                <td title="<?= $v['note'] ?>" id="note_<?= $v['gid'] ?>">
                                    <?= ($v['note'] == '' ? '<span class="badge badge-warning-lighten" onclick="goods.note_set(\'' . $v['note'] . '\',' . $v['gid'] . ')">设置' : '<span  class="badge badge-info-lighten" onclick="goods.note_set(\'' . $v['note'] . '\',' . $v['gid'] . ')">查看') ?></span>
                                </td>
                                <td>
                                    <a href="admin.goods.add.php?gid=<?= $v['gid'] ?>" class="action-icon"> <i
                                                class="layui-icon layui-icon-set-fill"></i></a>
                                    <a href="javascript:unset(<?= $v['gid'] ?>)" class="action-icon"> <i
                                                class="layui-icon layui-icon-delete"></i></a>
                                </td>
                            </tr>
                        <?php } ?>
                        </tbody>
                    </table>
                </div>
                <nav>
                    <ul class="pagination pagination-rounded" style="overflow: auto">
                        <li class="page-item">
                            <a class="page-link" href="?page=1<?= !empty($_QET['cid']) ? '&cid=' . $_QET['cid'] : '' ?>"
                               aria-label="Previous">
                                <span aria-hidden="true">«</span>
                                <span class="sr-only">Previous</span>
                            </a>
                        </li>
                        <?php foreach ($paging as $v) { ?>
                            <li class="page-item <?= $v['active'] ?>"><a class="page-link"
                                                                         href="?page=<?= $v['number'] ?><?= !empty($_QET['cid']) ? '&cid=' . $_QET['cid'] : '' ?>"><?= $v['number'] ?></a>
                            </li>
                        <?php } ?>
                        <li class="page-item">
                            <a class="page-link"
                               href="?page=<?= $shop_list['count'] ?><?= !empty($_QET['cid']) ? '&cid=' . $_QET['cid'] : '' ?>"
                               aria-label="Next">
                                <span aria-hidden="true">»</span>
                                <span class="sr-only">Next</span>
                            </a>
                        </li>
                        <?php if (!empty($_QET['cid'])) { ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=1" aria-label="Nexst">
                                    <span aria-hidden="true">查看全部</span>
                                    <span class="sr-only">Nexst</span>
                                </a>
                            </li>
                        <?php } ?>
                    </ul>
                </nav>
            </div> <!-- end card-body-->
        </div> <!-- end card-->
    </div> <!-- end col -->
</div>
<div id="content_s" style="display: none">
    <div class="form-horizontal layui-form">
        <?php
        $method = [1, 2, 3, 4, 5, 6, 7];
        $met = 0;
        $method_name = ['允许在线购买', '允许余额购买', '允许被兑换', '允许被对接', '启用商品价格监控', '允许被克隆', '允许购买多份'];
        foreach ($method_name as $v) {
            ?>
            <input type="checkbox" name="method[]"
                   lay-skin="primary" value="<?= ($met + 1) ?>" title="[<?= ($met + 1) ?>] <?= $method_name[$met] ?>"
                   <?= in_array(($met + 1), $method) ? ' checked=""' : null ?>>
            <?php $met++;
        } ?>
    </div>
</div>
<style>
    .level {
        text-align: center;
        margin-bottom: 1.5em;
        box-shadow: 3px 3px 16px 2px #e5e8eb;
        overflow: hidden;
        border-radius: 0.5em;
        max-width: 300px;
    }
</style>
<?php include "bottom.php"; ?>
<script>
    function unset(a) {
        layer.alert('删除后不可撤销，是否确认删除？', {
            icon: 3, title: '温馨提示', btn: ['取消', '确定删除'], btn2: function (layero, index) {
                window.location.href = '?unset=' + a;
            }
        })
    }

    var goods = {
        note_set: function (note = '', gid) {
            layer.prompt({
                formType: 2,
                value: note,
                title: '请填写商品' + gid + '记事本内容,除站长外他人看不到',
                area: ['300px', '350px']
            }, function (value, index, elem) {
                $.ajax({
                    type: "post",
                    url: "ajax.php?act=note_set",
                    data: {
                        note: value,
                        gid: gid
                    },
                    dataType: "json",
                    success: function (data) {
                        if (data.code == 1) {
                            layer.msg(data.msg, {
                                icon: 1, time: 500, end: function (layero, index) {
                                    location.reload();
                                }
                            });
                        } else {
                            layer.msg(data.msg, {icon: 2});
                        }
                    },
                    error: function () {
                        layer.alert('加载失败！');
                    }
                });
                layer.close(index);
            });
        },
        profit: function () {
            var arr = goods.pitch_on();
            if (arr.length == 0) {
                layer.msg('请先选中1个商品！');
                return false;
            }
            ;

            layer.prompt({
                formType: 3,
                value: 100,
                title: '默认商品可获得100%的利润',
            }, function (value, index, elem) {
                value = value - 0;
                layer.alert('是否要批量设置以下商品<br>' + arr + '<br>的利润比例为：' + value + '%？', {
                    title: '操作确认', icon: 3, btn: ['确定', '取消'], btn1: function (layero, index) {
                        //操作
                        var load = layer.load(3);
                        $.ajax({
                            type: "POST",
                            url: "./ajax.php?act=BatchProfitEdit",
                            data: {
                                gid: arr,
                                profits: value,
                            },
                            dataType: "json",
                            success: function (data) {
                                layer.close(load);
                                if (data.code == 1) {
                                    layui.use(['table'], function () {
                                        location.reload();
                                    });
                                    layer.alert(data.msg, {icon: 1, title: '批量操作成功'});
                                } else layer.msg(data.msg, {icon: 2});
                            },
                            error: function () {
                                layer.alert('加载失败！');
                            }
                        });
                    }
                });

                layer.close(index);
            });
        },
        FreightTem: function () {
            var arr = goods.pitch_on();
            if (arr.length == 0) {
                layer.msg('请先选中1个商品！');
                return false;
            }
            ;
            var load = layer.load(3);
            $.ajax({
                type: "POST",
                url: "./ajax.php?act=BatchFreightTem",
                dataType: "json",
                success: function (data) {
                    layer.close(load);
                    if (data.code == 1) {
                        var content = '<div style="width: 100%;" class="layui-elip"><a href="javascript:goods.BatchFreightTem(\'' + arr.join('|') + '\',-1)" style="color: tomato">点击设置</a>：不使用运费模板</div>';
                        $.each(data.data, function (key, val) {
                            console.log(val);
                            content += '<div style="width: 100%;" class="layui-elip"><a href="javascript:goods.BatchFreightTem(\'' + arr.join('|') + '\',' + val.id + ')" style="color: tomato">点击设置</a>：' + val.name + ' | ' + val.id + '</div>';
                        });
                        layer.open({
                            title: '批量设置运费模板',
                            content: content,
                            btn: ['取消'],
                        });
                    } else layer.msg(data.msg, {icon: 2});
                },
                error: function () {
                    layer.alert('加载失败！');
                }
            });
        },
        BatchFreightTem: function (gid, id) {
            var gid_arr = gid.split('|');
            layer.alert('是否要设置商品：<br>' + gid + '<br>的运费模板为：' + id + '？', {
                title: '操作确认', icon: 3, btn: ['确定', '取消'], btn1: function (layero, index) {
                    //操作
                    var load = layer.load(3);
                    $.ajax({
                        type: "POST",
                        url: "./ajax.php?act=BatchFreightTemEdit",
                        data: {
                            gid: gid_arr,
                            id: id,
                        },
                        dataType: "json",
                        success: function (data) {
                            layer.close(load);
                            if (data.code == 1) {
                                layui.use(['table'], function () {
                                    location.reload();
                                });
                                layer.alert(data.msg, {icon: 1, title: '批量操作成功'});
                            } else layer.msg(data.msg, {icon: 2});
                        },
                        error: function () {
                            layer.alert('加载失败！');
                        }
                    });
                }
            });
        },
        select_id: function (id) {
            if ($('.box_' + id).prop('checked') == true) {
                $('.box_' + id).attr("checked", true);
                $('.box_' + id).prop("checked", true);
            } else {
                $('.box_' + id + ',#list_all').attr('checked', false);
                $('.box_' + id + ',#list_all').prop("checked", false);
            }
        },
        select_all: function () {
            if ($('#list_all').prop('checked') == true) {
                $(".list_box,#list_all").attr("checked", true);
                $(".list_box,#list_all").prop("checked", true);
            } else {
                $(".list_box,#list_all").attr('checked', false);
                $(".list_box,#list_all").prop("checked", false);
            }
        },
        sort: function (gid, type) {
            $.ajax({
                type: 'POST',
                url: 'ajax.php?act=setGoodsSort',
                data: {
                    gid: gid,
                    type: type
                },
                dataType: 'json',
                success: function (data) {
                    location.reload();
                },
                error: function (data) {
                    layer.msg('服务器错误');
                    return false;
                }
            });
        }
        , pitch_on: function () {
            var amount = new Array();
            $("#table input[type='checkbox']").each(function () {
                if ($(this).is(":checked")) {
                    if ($(this).val() != 'true' && $(this).val() != '') amount.push($(this).val());
                }
            });
            return amount;
        },
        pitch_ons: function () {
            var amount = new Array();
            $("#mmda input[type='checkbox']").each(function () {
                if ($(this).is(":checked")) {
                    if ($(this).val() != 'true' && $(this).val() != '') amount.push($(this).val());
                }
            });
            return amount;
        },
        ajax_state: function (type, arr, cid = -1) {
            var index = layer.msg('正在调整中...', {icon: 16, time: 9999999});
            $.ajax({
                type: "post",
                url: "ajax.php?act=Goods_State_all",
                data: {type: type, arr: arr, cid: cid},
                dataType: "json",
                success: function (data) {
                    if (data.code > 0) {
                        layer.alert(data.msg, {
                            icon: 1, end: function (layero, index) {
                                location.reload();
                            }
                        });
                    } else {
                        layer.msg(data.msg, {icon: 2});
                    }
                },
                error: function () {
                    layer.alert('修改失败！');
                    layer.close(index);
                }
            });
        },
        rules: function (gid, name) {
            var arr_json = JSON.parse($("#price_" + gid).attr('data-rules'));
            if (arr_json.length == 0) {
                layer.msg('你怎么一个等级都没有？，最少要有一个等级！');
                return false;
            }
            var content = ''; //初始化
            count = 1;//初始化
            opacity = 0.7; //初始化
            $.each(arr_json, function (key, val) {
                if (count == 1) {
                    tips = '<span style="float: right;margin-right: 1em;">V' + count + ' / 游客级</span>';
                } else {
                    tips = '<span style="float: right;margin-right: 1em;">V' + count + '级</span>';
                }
                content += '<div class="layui-row layui-col-space8 level" style="opacity: ' + opacity + '">' +
                    '<div class="layui-col-xs12 font-14" style="background: linear-gradient(to right,#8e2de2, #4a00e0);color:white;text-align: left;text-indent: 1em">' + val['name'] + '| 赚' + val.profits + '元利润' + tips + '</div>' +
                    '<div class="layui-col-xs6 text-success ">金额：' + val.price + '元</div>' +
                    '<div class="layui-col-xs6 text-danger ">兑换：' + val.points + '点</div>' +
                    '</div>';
                ++count;
                opacity = opacity + 0.035;
            });
            content += '<p style="text-align: center" class="layui-text">小储云加盟系统 <a href="admin.level.list.php" target="_blank">[管理]</a></p>';
            layer.alert(content, {
                area: ['auto', '96%'],
                title: name + ' 等级 | 价格表',
                btn: false,
                shade: [0.3],
                shadeClose: true
            })
        },
        SharePoster: function (gid) {
            layer.msg('正在生成中...', {icon: 16, time: 9999999})
            $.ajax({
                type: "post",
                url: "/ajax.php?act=SharePoster",
                data: {gid: gid},
                dataType: "json",
                success: function (data) {
                    if (data.code == 1) {
                        layer.alert('<img src="' + data.src + '" width=300 heigth=450 />', {
                            area: ['340px', '490px'],
                            title: false,
                            btn: false, shade: [0.8, '#000'],
                            shadeClose: true,
                        })
                    } else {
                        layer.msg(data.msg, {icon: 2});
                    }
                },
                error: function () {
                    layer.alert('生成失败！');
                }
            });
        }
    }

    $("select[name='goods_state']").change(function () {
        var arr = goods.pitch_on();
        if (arr.length == 0) return;
        var type = $(this).children('option:selected').val();
        if (type == '') return;
        switch (type) {
            case '-1': //上架
                layer.alert('是否将这' + arr.length + '个商品设置为上架状态？', {
                    title: '商品批量上架',
                    icon: 3,
                    btn: ['确认', '取消'],
                    btn1: function (layero, index) {
                        goods.ajax_state(1, arr);
                    }
                })
                break;
            case '-2': //下架
                layer.alert('是否将这' + arr.length + '个商品设置为下架状态？', {
                    title: '商品批量下架',
                    icon: 3,
                    btn: ['确认', '取消'],
                    btn1: function (layero, index) {
                        goods.ajax_state(2, arr);
                    }
                })
                break;
            case '-3': //删除
                layer.alert('是否将这' + arr.length + '个商品删除？', {
                    title: '商品批量删除',
                    icon: 3,
                    btn: ['确认', '取消'],
                    btn1: function (layero, index) {
                        goods.ajax_state(3, arr);
                    }
                })
                break;
            case '-4': //商品参数
                layer.alert('<div id="mmda">' + $("#content_s").html() + '</div>', {
                    success: function (layero, index) {
                        layui.use('form', function () {
                            var form = layui.form;
                            form.render();
                            //各种基于事件的操作，下面会有进一步介绍
                        });
                    },
                    btn: ['批量修改', '取消'],
                    title: '批量设置商品参数',
                    yes: function (layero, index) {
                        var goods_arr = goods.pitch_ons();
                        layer.alert('是否将这' + arr.length + '个商品批量设置为当前选择参数？', {
                            title: '批量设置商品参数确认!',
                            icon: 3,
                            btn: ['确认', '取消'],
                            btn1: function (layero, index) {
                                goods.ajax_state(4, arr, goods_arr);
                            }
                        })
                    }
                });
                break;
            default: //分类
                layer.alert('是否将这' + arr.length + '个商品移动到分类:' + type + '里面？', {
                    title: '商品批量移动确认!',
                    icon: 3,
                    btn: ['确认', '取消'],
                    btn1: function (layero, index) {
                        goods.ajax_state(5, arr, type);
                    }
                })
                break;
        }
    })
</script>