<?php

$articleModule = array_map(fn($case) => [
    'label' => ucfirst($case->toString()),
    'value' => $case->value,
], \App\Enums\ArticleModuleEnum::cases());

$articlePublishedStatus = array_map(fn($case) => [
    'label' => ucfirst($case->toString()),
    'value' => $case->value,
], \App\Enums\SpiderArticlePublishedStatusEnum::cases());
?>
        <!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="utf-8">
    <title>浏览页面</title>
    <link rel="stylesheet" href="/component/pear/css/pear.css"/>
    <link rel="stylesheet" href="/admin/css/reset.css"/>
    <link rel="stylesheet" href="/admin/css/reset.css"/>
</head>
<body class="pear-container">
<!-- 顶部查询表单 -->
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form top-search-from">

            <div class="layui-form-item">
                <label class="layui-form-label">文章标题</label>
                <div class="layui-input-block">
                    <input type="text" name="title" value="" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">创建时间</label>
                <div class="layui-input-block">
                    <div class="layui-input-block" id="created_at">
                        <input type="text" autocomplete="off" value="<?= date('Y-m-d', strtotime('-1 month')) ?>"
                               name="created_at[]" id="created_at-date-start" class="layui-input inline-block"
                               placeholder="开始时间">
                        -
                        <input type="text" autocomplete="off" value="<?= date('Y-m-d') ?>" name="created_at[]"
                               id="created_at-date-end" class="layui-input inline-block" placeholder="结束时间">
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">文章类型</label>
                <div class="layui-input-block">
                    <select name="module">
                        <option value="">请选择</option>
                        <?php foreach ($articleModule as $module): ?>
                        <option value="<?= $module['value'] ?>"><?= $module['label'] ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">发布状态</label>
                <div class="layui-input-block">
                    <select name="published_status">
                        <?php foreach ($articlePublishedStatus as $status): ?>
                        <option value="<?= $status['value'] ?>"><?= $status['label'] ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="layui-form-item layui-inline">
                <label class="layui-form-label"></label>
                <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="table-query">
                    <i class="layui-icon layui-icon-search"></i>查询
                </button>
                <button type="reset" class="pear-btn pear-btn-md" lay-submit lay-filter="table-reset">
                    <i class="layui-icon layui-icon-refresh"></i>重置
                </button>
            </div>
            <div class="toggle-btn">
                <a class="layui-hide">展开<i class="layui-icon layui-icon-down"></i></a>
                <a class="layui-hide">收起<i class="layui-icon layui-icon-up"></i></a>
            </div>
        </form>
    </div>
</div>

<!-- 数据表格 -->
<div class="layui-card">
    <div class="layui-card-body">
        <table id="data-table" lay-filter="data-table"></table>
    </div>
</div>

<!-- 表格行工具栏 -->
<script type="text/html" id="table-bar">
    <button class="pear-btn pear-btn-xs tool-btn" lay-event="pre-publish">预发布</button>
    <button class="pear-btn pear-btn-xs tool-btn" lay-event="edit">预览数据</button>
    <button class="pear-btn pear-btn-xs tool-btn" lay-event="delete">删除</button>
</script>

<script src="/component/layui/layui.js?v=2.8.12"></script>
<script src="/component/pear/pear.js"></script>
<script src="/admin/js/permission.js"></script>
<script src="/admin/js/common.js"></script>
<script>

    // 相关常量
    const PRIMARY_KEY = "id";
    const UPDATE_API = "/admin/update";
    const DELETE_API = "/admin/delete";

    // ----------------------
    const UPDATE_URL = "/articles/update";

    // page
    const VIEW_URL = "/admin/spider-article/view";

    // api
    const INDEX_API = '/admin/api/spider-article';
    const PRE_PUBLISH_API = '/admin/api/spider-article/pre-publish';

    // 字段 创建时间 created_at
    layui.use(["laydate"], function () {
        layui.laydate.render({
            elem: "#created_at",
            range: ["#created_at-date-start", "#created_at-date-end"],

        });
    })

    // 表格渲染
    layui.use(["table", "form", "common", "popup", "util"], function () {
        let table = layui.table;
        let form = layui.form;
        let $ = layui.$;
        let common = layui.common;
        let util = layui.util;

        // 表头参数
        let cols = [
            {
                type: "checkbox"
            }, {
                title: "文章标题",
                field: "title",
            }, {
                title: "文章类型",
                field: "module",
            }, {
                field:'published_status', title: '发布状态', templet: function(d){
                    if(d.published_status === '未同步'){
                        return '<span style="color: red">' + d.published_status + '</span>';
                    } else {
                        return '<span style="color: green">' + d.published_status + '</span>';
                    }
                },
                // field: "published_status",
            }, {
                title: "采集时间",
                field: "created_at",
            }, {
                title: "来源链接",
                field: "source_url",
            }, {
                title: "操作",
                toolbar: "#table-bar",
                align: "center",
                fixed: "right",
                width: 230,
            }
        ];

        // 渲染表格
        function render() {
            table.render({
                elem: "#data-table",
                url: INDEX_API,
                page: true,
                cols: [cols],
                skin: "line",
                size: "lg",
                toolbar: "#table-toolbar",
                autoSort: false,
                defaultToolbar: [{
                    title: "刷新",
                    layEvent: "refresh",
                    icon: "layui-icon-refresh",
                }, "filter", "print", "exports"],
                done: function () {
                    layer.photos({photos: 'div[lay-id="data-table"]', anim: 5});
                }
            });
        }

        // 获取表格中下拉或树形组件数据
        let apis = [];
        apis.push(["roles", "/role/select?format=select"]);
        let apiResults = {};
        apiResults["roles"] = [];
        let count = apis.length;
        layui.each(apis, function (k, item) {
            let [field, url] = item;
            $.ajax({
                url: url,
                dateType: "json",
                success: function (res) {
                    if (res.code) {
                        return layui.popup.failure(res.msg);
                    }

                    function travel(items) {
                        for (let k in items) {
                            let item = items[k];
                            apiResults[field][item.value] = item.name;
                            if (item.children) {
                                travel(item.children);
                            }
                        }
                    }

                    travel(res.data);
                },
                complete: function () {
                    if (--count === 0) {
                        render();
                    }
                }
            });
        });
        if (!count) {
            render();
        }

        // 编辑或删除行事件
        table.on("tool(data-table)", function (obj) {
            if (obj.event === "edit") {
                edit(obj);
            }
            if (obj.event === "delete") {
                alert('未生效');
            }

            // 预发布
            if (obj.event === 'pre-publish') {
                console.log(obj.data.id)
                layer.confirm('确定发布吗？', function (index) {
                    // obj.del(); // 删除对应行（tr）的 DOM 结构，并更新缓存
                    // layer.close(index);
                    let loading = layer.load();
                    $.ajax({
                        url: PRE_PUBLISH_API,
                        data: {
                            id: obj.data.id
                        },
                        dataType: "json",
                        type: "post",
                        success: (res) => {
                            layer.close(index);
                            if (res.code) {
                                return layui.popup.failure(res.msg);
                            }
                            return layui.popup.success("操作成功", refreshTable);
                        },
                        error: function () {
                            return layui.popup.failure("操作失败");
                        },
                        complete: function () {
                            layer.close(loading);
                        }
                    })
                    // 向后端发送删除请求，执行完毕后，可通过 reloadData 方法完成数据重载
                    /*
                    table.reloadData(id, {
                      scrollPos: 'fixed'  // 保持滚动条位置不变 - v2.7.3 新增
                    });
                    */
                });
            }
        });

        // 表格顶部工具栏事件
        table.on("toolbar(data-table)", function (obj) {
            if (obj.event === "add") {
                add();
            } else if (obj.event === "refresh") {
                refreshTable();
            } else if (obj.event === "batchRemove") {
                batchRemove(obj);
            }
        });

        // 表格顶部搜索事件
        form.on("submit(table-query)", function (data) {
            table.reload("data-table", {
                page: {
                    curr: 1
                },
                where: data.field
            })
            return false;
        });

        // 表格顶部搜索重置事件
        form.on("submit(table-reset)", function (data) {
            table.reload("data-table", {
                where: []
            })
        });

        // 表格排序事件
        table.on("sort(data-table)", function (obj) {
            table.reload("data-table", {
                initSort: obj,
                scrollPos: "fixed",
                where: {
                    field: obj.field,
                    order: obj.type
                }
            });
        });

        // 表格新增数据
        let add = function () {
            layer.open({
                type: 2,
                title: "新增",
                shade: 0.1,
                area: [common.isModile() ? "100%" : "98%", common.isModile() ? "100%" : "95%"],
                content: VIEW_URL
            });
        }

        // 表格编辑数据
        let edit = function (obj) {
            let value = obj.data[PRIMARY_KEY];
            layer.open({
                type: 2,
                title: "预览",
                shade: 0.1,
                area: [common.isModile() ? "100%" : "98%", common.isModile() ? "100%" : "95%"],
                content: VIEW_URL + "?" + PRIMARY_KEY + "=" + value
            });
        }

        // 删除一行
        let remove = function (obj) {
            return doRemove(obj.data[PRIMARY_KEY]);
        }

        // 删除多行
        let batchRemove = function (obj) {
            let checkIds = common.checkField(obj, PRIMARY_KEY);
            if (checkIds === "") {
                layui.popup.warning("未选中数据");
                return false;
            }
            doRemove(checkIds.split(","));
        }

        // 执行删除
        let doRemove = function (ids) {
            let data = {};
            data[PRIMARY_KEY] = ids;
            layer.confirm("确定删除?", {
                icon: 3,
                title: "提示"
            }, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: DELETE_API,
                    data: data,
                    dataType: "json",
                    type: "post",
                    success: function (res) {
                        layer.close(loading);
                        if (res.code) {
                            return layui.popup.failure(res.msg);
                        }
                        return layui.popup.success("操作成功", refreshTable);
                    }
                })
            });
        }

        // 刷新表格数据
        window.refreshTable = function () {
            table.reloadData("data-table", {
                scrollPos: "fixed",
                done: function (res, curr) {
                    if (curr > 1 && res.data && !res.data.length) {
                        curr = curr - 1;
                        table.reloadData("data-table", {
                            page: {
                                curr: curr
                            },
                        })
                    }
                }
            });
        }
    })

</script>
</body>
</html>
