<?php
/**
 * 商品一键
 */

$title = '商品一键上架';
include "header.php";
$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']];
}
$re = $DB->query("SELECT * FROM `sky_shequ` WHERE `type` !=4 ");
$shequ_arr = [];
while ($res = $DB->fetch($re)) {
    $shequ_arr[] = ['url' => $res['url'], 'id' => $res['id'], 'type' => $res['type']];
}
?>
<div class="row">
    <div class="col-xl-12">
        <div class="card">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-12">
                        <h3 class="mb-3 header-title text-success"><?= $title ?></h3>
                        <form class="form-horizontal layui-form">
                            <div class="form-group mb-3">
                                <label for="example-input-normal">请选择需要上架商品的分类(<a
                                            href="admin.class.add.php">添加</a>)</label>
                                <select class="custom-select mt-3" lay-verify="required" lay-search name="cid">
                                    <option></option>
                                    <?php
                                    foreach ($cid_arr as $v) {
                                        $state = $v['state'] == 1 ? '显示中' : '已掩藏';
                                        echo '<option value="' . $v['cid'] . '">' . $v['name'] . '[' . $state . ']</option>';
                                    }
                                    ?>
                                </select>
                            </div>
                            <div class="form-group mb-3">
                                <label for="example-input-normal">请选择是否删除需要上架分类下的旧商品！</label>
                                <select class="custom-select mt-3" lay-verify="required" lay-search name="delete">
                                    <option></option>
                                    <option value="1">删除该分类下的全部商品</option>
                                    <option value="2">保留该分类下的全部商品</option>
                                </select>
                            </div>
                            <div class="form-group mb-3">
                                <label for="example-input-normal">请选择需要上架商品的货源(<a href="admin.class.add.php">添加</a>)[玖伍,亿乐,同系统]
                                    <font color="red">卡易信不支持一键上架</font></label>
                                <select class="custom-select mt-3" lay-verify="required" lay-filter="sid" lay-search
                                        name="sid">
                                    <option></option>
                                    <?php
                                    foreach ($shequ_arr as $item) {
                                        switch ($item['type']) {
                                            case 1:
                                                $type = '玖伍社区';
                                                break;
                                            case 2:
                                                $type = '亿乐社区';
                                                break;
                                            case 3:
                                                $type = '小储系统';
                                                break;
                                        }
                                        echo '<option value="' . $item['id'] . '" data="' . $item['type'] . '" >' . $item['url'] . ' [ ' . $type . ' ]</option>';
                                    }
                                    ?>
                                </select>
                            </div>
                            <div class="form-group mb-3" id="shopdata" style="display: none">
                                <label for="example-input-normal">需要上架的商品<font color="red">(可多选)</font> <a
                                            href="javascript:shop_add.select_all()">[全选/全部取消]</a></label>
                                <div class="" id="sid_data" data-type="0"></div>
                            </div>
                            <div class="form-group mb-3">
                                <label for="example-input-normal">一键上架的商品每日限购数量</label>
                                <input type="number"
                                       value="1000"
                                       lay-verify="required" name="quota"
                                       class="form-control" placeholder="每日该商品库存,售完即止！">
                            </div>
                            <div class="form-group mb-3">
                                <label for="example-input-normal">一键商品缓冲间隔时间(ms,1000=1s)</label>
                                <input type="number"
                                       value="2000"
                                       lay-verify="required" name="delay"
                                       class="form-control" placeholder="如填2100则一个商品上架完后,间隔2.1s再上架另外一个！">
                            </div>
                            <div class="form-group mb-3">
                                <label for="example-input-normal">商品利润比例，默认100%</label>
                                <input type="number"
                                       value="100" name="profits"
                                       class="form-control" lay-verify="required" placeholder="不可留空哦">
                            </div>
                            <div class="form-group mb-3">
                                <label for="example-input-normal">商品每份数量,若不填写则默认为最小数量</label>
                                <input type="number"
                                       value="" name="copies"
                                       class="form-control" placeholder="可直接留空,若不留空则为最小份数,若填写的数低于或大于商品最小最大份数,则默认最小或最大！">
                            </div>
                            <div class="form-group mb-3">
                                <label for="example-input-normal">商品最小下单数，可直接留空,自动获取！</label>
                                <input type="number"
                                       value="" name="min"
                                       class="form-control" placeholder="可直接留空,自动获取！">
                            </div>
                            <div class="form-group mb-3">
                                <label for="example-input-normal">商品最大下单数，可直接留空,自动获取！</label>
                                <input type="number"
                                       value="" name="max"
                                       class="form-control" placeholder="可直接留空,自动获取！">
                            </div>
                            <div class="form-group mb-3">
                                <label for="example-input-normal">一键上架的商品名称，若不填写,则自动获取</label>
                                <input type="text"
                                       value="" name="name"
                                       class="form-control" placeholder="可直接留空,自动获取，若不为空，则会将商品名称设置为：自定义名称-商品份数">
                            </div>
                            <div class="form-group mb-3">
                                <label for="example-input-normal">一键上架的商品弹窗,可留空</label>
                                <input type="text"
                                       value="" name="alert"
                                       class="form-control" placeholder="可直接留空,留空不弹">
                            </div>
                            <div class="form-group mb-3" style="">
                                <label for="example-input-normal" style="position: relative;bottom: 0;left: 0">一键上架的商品说明，若不填写,则自动获取</label>
                                <textarea class="form-control" name="docs" rows="3"
                                          placeholder="可留空，自动获取"></textarea>
                            </div>
                            <div class="form-group mb-3">
                                <label for="example-input-normal">扩展参数<font color="red">(可多选)</font></label>
                                <div class="">
                                    <?php
                                    $met = 0;
                                    $method = [1, 2, 3, 4, 5, 6, 7];
                                    $method_name = ['允许在线购买', '允许余额购买', '允许被兑换', '允许被对接', '启用商品价格监控', '允许被克隆', '允许购买多份'];
                                    foreach ($method_name as $v) {
                                        ?>
                                        <input type="checkbox" name="method[]"
                                               lay-skin="primary" value="<?= ($met + 1) ?>" lay-filter="ckeck"
                                               title="<?= $method_name[$met] ?>"
                                               <?= in_array(($met + 1), $method) ? ' checked=""' : null ?>>
                                        <?php $met++;
                                    } ?>
                                </div>
                            </div>
                            <button type="submit" lay-submit lay-filter="submit"
                                    class="btn btn-block btn-xs btn-success">开始上架商品
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include "bottom.php"; ?>
<script>
    layui.use('form', function () {
        var form = layui.form;
        form.on('select(sid)', function (data) {
            var id = data.value;
            if (id == '') return false;
            var index = layer.msg('商品列表获取中...', {icon: 16, time: 999999});
            $.post('ajax.php?act=product_list', {id: id}, function (res) {
                if (res.code == 1) {
                    var content = "";
                    for (var a = 0; a < res['data'].length; a++) {
                        if (res['data'][a]['type'] != undefined) {
                            $("#shopdata").attr('data-type', 'jiuwu');
                            content += '<input type="checkbox" name="commodity[]" value="' + res['data'][a]['gid'] + '*' + res['data'][a]['type'] + '" data-type="' + res['data'][a]['type'] + '"  lay-skin="primary" title="' + res['data'][a]['title'] + '">';
                        } else {
                            $("#shopdata").attr('data-type', 'yile');
                            content += '<input type="checkbox" name="commodity[]" value="' + res['data'][a]['gid'] + '" data-type="' + res['data'][a]['type'] + '"  lay-skin="primary" title="' + res['data'][a]['title'] + '">';
                        }
                    }
                    $("#sid_data").html(content);
                    form.render('checkbox');
                    layer.msg('共' + res['data'].length + '个商品!', {icon: 1});

                    $("#shopdata").show();
                    layer.close(index);
                } else if (res.code == 2) { //小储系统
                    var content = "";
                    for (var a = 0; a < res['data'].length; a++) {
                        content += '<input type="checkbox" name="commodity[]"  value="' + res['data'][a]['gid'] + '" lay-skin="primary" title="' + res['data'][a]['name'] + ',成本:' + res['data'][a]['price'] + '">';
                    }
                    $("#shopdata").attr('data-type', 'xiaoc');
                    $("#sid_data").html(content);
                    form.render('checkbox');
                    layer.msg('共' + res['data'].length + '个商品!', {icon: 1});
                    $("#shopdata").show();
                    layer.close(index);
                } else {
                    layer.alert('error:' + res.msg);
                    layer.close(index);
                }
            });
        });
        form.on('submit(submit)', function (data) {
            data.field['type'] = $("#shopdata").attr('data-type');
            if (data.field['delay'] < 1100) {
                layer.alert('缓存延迟最低不可少于1100毫秒！');
                return false;
            }
            $.post('ajax.php?act=conversion', data.field, function (res) {
                if (res.code == 1) {
                    var index = layer.msg('开始上架商品,本次共需上架商品数量为：' + res.data.commodity.length + '个！', {
                        icon: 16,
                        time: 999999,
                        shade: [0.5, '#000']
                    });
                    shop_add.conversion(res.data, 0);
                } else
                    layer.alert(res.msg);
            });
            return false;
        });
    });
    var shop_add = { //商品上架类
        select_all: function () { //全选，返选
            var type = $("#sid_data").attr('data-type');
            if (type == '0') {
                $("#sid_data").attr('data-type', '1');
                $("#sid_data input[type='checkbox']").attr("checked", true);
                $("#sid_data input[type='checkbox']").prop("checked", true);
            } else {
                $("#sid_data").attr('data-type', '0');
                $("#sid_data input[type='checkbox']").attr('checked', false);
                $("#sid_data input[type='checkbox']").prop("checked", false);
            }
            shop_add.LayerReloads('checkbox');
        },
        LayerReloads: function (str) { //重载layui form 全部
            layui.use('form', function () {
                var form = layui.form;
                if (str == '') {
                    form.render();
                } else {
                    form.render(str);
                }
            });
        },
        conversion: function (data, sum) { //规则转换,删除数组内的gid
            if (data.commodity.length <= sum) {
                layer.close();
                layer.alert('恭喜你,商品已经全部上架完！<br>本次共成功上架' + data.commodity.length + '个商品！', {
                    anim: 4,
                    icon: 1,
                    title: '商品上架成功提醒！',
                    btn: ['确定', '查看上架的商品'],
                    shade: [0.5, '#000'],
                    btn2: function (layero, index) {
                        window.open('admin.goods.list.php?cid=' + data.cid);
                    }
                });
                return false;
            }

            var gid = data['commodity'][sum];

            if (data.type == 'jiuwu') { //需切割出type
                arr = gid.split('*');
                gid = arr[0];
                type = arr[1]; //玖伍分类ID
            } else {
                type = null;
            }
            /**
             * 开始获取商品数据！
             */
            setTimeout(function () {
                shop_data = shop_add.merchandise(data.sid, gid, type, data, (sum + 1));
            }, 1100);
        },
        merchandise: function (sid, gid, type, data, sum) {
            $.post('ajax.php?act=Goods_in_detail', {
                id: sid,
                gid: gid,
                typs: type
            }, function (res) {
                if (res.code == 1) {
                    shop_add.add_merchandise(res.data, data, gid, type, sum);
                } else {
                    layer.alert('商品数据获取失败,建议将商品缓冲间隔时间调长点！<br>本次成功上架' + (sum - 1) + '个商品！');
                }
            })
        },
        // resdata = 商品数据，data = 信息配置
        add_merchandise: function (resdata, data, gid, type = null, sum) { //开始上架商品！
            var datarf = []; //初始化
            /**
             * 商品参数解析！
             */
            if (resdata.pipei == 'yile') {
                if (resdata.inputs.length >= 1) {
                    var am = resdata.inputs[0];
                    var postpe = am[2];
                    var uina = am[0];
                    for (let a = 1; a < resdata.inputs.length; a++) {
                        var am = resdata.inputs[a];
                        var postpe = postpe + '|' + am[2];
                        uina += '|' + am[0];
                    }
                    input = uina;
                    datarf['input'] = input;
                } else {
                    var postpe = '';
                    input = '';
                    datarf['input'] = input;
                }
                submit_the_field = postpe;
                datarf['submit_the_field'] = submit_the_field;
            } else {
                submit_the_field = resdata.pipei;
                datarf['submit_the_field'] = submit_the_field;
                if (resdata.inputs.length >= 1) {
                    var uina = resdata.inputs[0];
                    for (let a = 1; a < resdata.inputs.length; a++) {
                        uina += '|' + resdata.inputs[a];
                    }
                    input = uina;
                    datarf['input'] = input;
                } else {
                    input = '';
                    datarf['input'] = input;
                }
            }

            if (data.copies != undefined && data.copies != '') { //开启份数自定义！
                datarf['quantity'] = data.copies;
                if (data.copies < resdata.min) {
                    datarf['quantity'] = resdata.min;
                }
                if (data.copies > resdata.max) {
                    datarf['quantity'] = resdata.max;
                }
            } else {
                datarf['quantity'] = resdata.min;
            }

            if (data.name == undefined || data.name == '') {
                datarf['name'] = resdata.name;
            } else {
                datarf['name'] = data.name;
            }

            if (data.docs == undefined || data.docs == '') {
                datarf['docs'] = resdata.content;
            } else {
                datarf['docs'] = data.docs;
            }

            if (data.max == undefined || data.max == '') {
                datarf['max'] = resdata.max;
            } else {
                datarf['max'] = data.max;
            }
            if (data.min == undefined || data.min == '') {
                datarf['min'] = resdata.min;
            } else {
                datarf['min'] = data.min;
            }

            datarf['profits'] = data.profits;
            datarf['cid'] = data.cid;
            datarf['state'] = 1;
            datarf['method'] = data.method;
            datarf['image'] = resdata.image;
            datarf['quota'] = data.quota;
            datarf['money'] = resdata.price * datarf['quantity'];
            datarf['alert'] = data.alert;
            datarf['SupplyId'] = data.sid; //社区ID
            datarf['SupplyType'] = type;
            datarf['GoodsArguments'] = datarf['submit_the_field']; //下单参数
            datarf['GoodsId'] = gid; //对接货源商品ID
            datarf['GoodsType'] = resdata.goods_type; //玖伍商品分类
            datarf['operation'] = 4;
            setTimeout(function () {
                $.ajax({
                    type: "post",
                    url: "ajax.php?act=Save_the_content",
                    /*data: datarf,未知原因，无法使用*/
                    data: {
                        cid: datarf['cid'],
                        state: datarf['state'],
                        name: datarf['name'],
                        method: datarf['method'],
                        image: datarf['image'],
                        input: datarf['input'],
                        quota: datarf['quota'],
                        money: datarf['money'],
                        alert: datarf['alert'],
                        docs: datarf['docs'],
                        SupplyId: datarf['SupplyId'],
                        SupplyType: datarf['SupplyType'],
                        GoodsArguments: datarf['GoodsArguments'],
                        GoodsId: datarf['GoodsId'],
                        GoodsType: datarf['GoodsType'],
                        quantity: datarf['quantity'],
                        operation: datarf['operation'],
                        profits: datarf['profits'],
                        min: datarf['min'],
                        max: datarf['max'],
                    },
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            setTimeout(function () {
                                var index = layer.msg('正在上架第' + (sum) + '个商品<font color=#228b22>[' + resdata.name + ']</font><br>共需上架：' + data.commodity.length + '个商品！', {
                                    icon: 16,
                                    time: 999999,
                                    shade: [0.5, '#000'],
                                    anim: Math.ceil(Math.random() * 6)
                                });
                                shop_add.conversion(data, sum);
                            }, data['delay']);
                        } else {
                            layer.alert(res.msg + '<br>可能可以在网站维护界面修复,前两个按钮！', {icon: 2})
                        }
                    },
                    error: function () {
                        layer.alert('失败！');
                    }
                });
            }, 1100);
        }
    }
</script>
