<?php
/**
 * Created by PhpStorm.
 * User: eyou
 * Date: 2024/4/9
 * Time: 8:55
 */

namespace app\admin\controller;

use think\Page;
use think\Db;

class Gzh extends Base
{
    public $errcode;
    public $data = [];

    public function __construct()
    {
        parent::__construct();
        $this->data = get_gzh_config();
    }

    public function getClassObj($className, $data)
    {
        if (empty($data)) {
            $this->data = get_gzh_config();
        }
        vendor('wechat.wechat');

        $class = '\\' . $className; //
        return new $class($data); //实例化对应的类
    }

    /**
     * 首页
     */
    public function index()
    {
        return $this->fetch('index');
    }

    /**
     * 公众号设置
     */
    public function config()
    {
        $data = $this->data;

        if (IS_AJAX_POST) {
            $post = input('post.');
            if (empty($data) || $data['appid'] !== $post['data']['appid']) {
                $w_token = get_rand_str(32, 0, 1);
                $post['data']['w_token'] = $w_token;
                $post['data']['token'] = getTime();
            }
            // 服务器地址(URL)
            $apiurl = $this->request->domain() . ROOT_DIR . "/index.php?s=/api/Gzh/valid/ctl/Basis/appid/{$post['data']['appid']}";
            $post['data']['apiurl'] = $apiurl;
            set_gzh_config($post['data']);

            $this->success("操作成功!");
        }

        if (!empty($data['appid'])) {
            $access_token = get_wechat_access_token(true);
            /*验证IP是否加入白名单中*/
            $ipTips = '';
            if (!empty($access_token['errcode'])) {
                if ($access_token['errcode'] == 40164) {
                    preg_match_all('#(\d{1,3}\.){3}\d{1,3}#i', $access_token['errmsg'], $matches);
                    $ip = !empty($matches[0][0]) ? $matches[0][0] : '';
                    $ipTips = "<font color='red'>请将IP：{$ip} 加入微信公众号的IP白名单里（预计3-5分钟生效），具体点击<a href=\"JavaScript:void(0);\" onclick=\"click_to_eyou_1575506523('https://www.eyoucms.com/plus/view.php?aid=9432','IP白名单配置教程')\">查看教程</a>！</font>";
                } else {
                    $ipTips = "<font color='red'>{$access_token['errmsg']}</font>";
                }
            } else {
                // 公众号是否认证
                $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token={$access_token['access_token']}";
                $res = json_decode(httpRequest($url), true);
                if (!isset($res['total'])) {
                    $data['type'] = 1;
                } else {
                    $data['type'] = 2;
                }
            }
            $this->assign('ipTips', $ipTips);
            /*--end*/
        }

        // 服务器地址(URL)
        $data['apiurl'] = $this->request->domain() . ROOT_DIR . "/index.php?s=/api/Gzh/valid/ctl/Basis/appid/{$data['appid']}";
        $this->assign('field', $data);
        return $this->fetch('config');
    }

    /**
     * 插件后台管理 - 菜单管理
     */
    public function menu_index()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');

            foreach ($post['data'] as $k => $v) {
                if (empty($v['value']['title'])) $this->error('菜单名称不能为空!', '', ['first_cur' => $k, 'second' => 0]);
                if (empty($v['child'])) {
                    if ('sendmsg' == $v['value']['menu'] && empty($v['value']['material_id'])) {
                        $this->error('请选择素材!', '', ['first_cur' => $k, 'second' => 0]);
                    } elseif ('view' == $v['value']['menu'] && empty($v['value']['jump_url'])) {
                        $this->error('请填写跳转链接!', '', ['first_cur' => $k, 'second' => 0]);
                    } elseif ('click' == $v['value']['menu'] && empty($v['value']['key'])) {
                        $this->error('请填写关键字!', '', ['first_cur' => $k, 'second' => 0]);
                    } elseif ('edit_miniprogram' == $v['value']['menu']) {
                        if (empty($v['value']['url'])){
                            $this->error('请填写网页链接!', '', ['first_cur' => $k, 'second' => 0]);
                        }elseif (empty($v['value']['appid'])){
                            $this->error('请填写小程序appid!', '', ['first_cur' => $k, 'second' => 0]);
                        }elseif (empty($v['value']['path'])){
                            $this->error('请填写小程序页面路径!', '', ['first_cur' => $k, 'second' => 0]);
                        }
                    }
                } else {
                    foreach ($v['child'] as $m => $n) {
                        if (empty($n['title'])) $this->error('菜单名称不能为空!', '', ['first_cur' => $k, 'second' => $m]);
                        if ('sendmsg' == $n['menu'] && empty($n['material_id'])) {
                            $this->error('请选择素材!', '', ['first_cur' => $k, 'second' => $m]);
                        } elseif ('view' == $n['value']['menu'] && empty($n['value']['jump_url'])) {
                            $this->error('请填写跳转链接!', '', ['first_cur' => $k, 'second' => $m]);
                        } elseif ('click' == $n['value']['menu'] && empty($n['value']['key'])) {
                            $this->error('请填写关键字!', '', ['first_cur' => $k, 'second' => $m]);
                        } elseif ('edit_miniprogram' == $n['value']['menu']) {
                            if (empty($n['value']['url'])){
                                $this->error('请填写网页链接!', '', ['first_cur' => $k, 'second' => $m]);
                            }elseif (empty($n['value']['appid'])){
                                $this->error('请填写小程序appid!', '', ['first_cur' => $k, 'second' => $m]);
                            }elseif (empty($n['value']['path'])){
                                $this->error('请填写小程序页面路径!', '', ['first_cur' => $k, 'second' => $m]);
                            }
                        }
                    }
                }
            }

            //先清除数据,再重新写入
            Db::name('gzh_menu')->where('id', '>', 0)->delete();

            $insertAll = [];
            foreach ($post['data'] as $k => $v) {
                $insert = [
                    'add_time' => getTime(),
                    'update_time' => getTime(),
                    'title' => $v['value']['title'],
                    'type' => $v['value']['menu'],
                    'material_id' => !empty($v['value']['material_id']) ? $v['value']['material_id'] : 0,
                    'jump_url' => !empty($v['value']['jump_url']) ? $v['value']['jump_url'] : '',
                    'url' => !empty($v['value']['url']) ? $v['value']['url'] : '',
                    'key' => !empty($v['value']['key']) ? $v['value']['key'] : '',
                    'appid' => !empty($v['value']['appid']) ? $v['value']['appid'] : '',
                    'path' => !empty($v['value']['path']) ? $v['value']['path'] : '',
                ];
                $id = Db::name('gzh_menu')->insertGetId($insert);
                if (false != $id) {
                    if (!empty($v['child'])) {
                        foreach ($v['child'] as $m => $n) {
                            $insertAll[] = [
                                'level' => 2,
                                'pid' => $id,
                                'add_time' => getTime(),
                                'update_time' => getTime(),
                                'title' => $n['title'],
                                'type' => $n['menu'],
                                'material_id' => !empty($n['material_id']) ? $n['material_id'] : 0,
                                'jump_url' => !empty($n['jump_url']) ? $n['jump_url'] : '',
                                'url' => !empty($n['url']) ? $n['url'] : '',
                                'key' => !empty($n['key']) ? $n['key'] : '',
                                'appid' => !empty($n['appid']) ? $n['appid'] : '',
                                'path' => !empty($n['path']) ? $n['path'] : '',
                            ];
                        }
                    }
                }
            }
            if (!empty($insertAll)) {
                Db::name('gzh_menu')->insertAll($insertAll);
            }
            $this->menu_pub();
            $this->success('保存成功!');
        }
        $list = Db::name('gzh_menu')->order('level asc,id asc')->getAllWithIndex('id');
        $material_ids = get_arr_column($list,'material_id');
        $material_ids = array_filter($material_ids);
        if (!empty($material_ids)){
            $material_list = Db::name('gzh_material')->where('id','in',$material_ids)->field('title,litpic,intro,type,id')->getAllWithIndex('id');
        }
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                if (!empty($v['material_id'])) $v['material'] = $list[$k]['material'] = $material_list[$v['material_id']];

                    if (2 == $v['level']) {
                    $list[$v['pid']]['child'][] = $v;
                    unset($list[$k]);
                }
            }
            $list = array_merge($list);
        }
        $this->assign('list', $list);
        return $this->fetch('menu_index');
    }

    /*
     * 生成微信菜单
     */
    public function menu_pub(){
        //获取父级菜单
        $p_menus = Db::name('gzh_menu')->where(array('level'=>1))->order('id asc')->select();

        if(empty($p_menus)){
            $this->error('没有菜单可发布');
        }
        // 菜单转换
        $menuArr = $this->menu_convert($p_menus);

        /*自定义菜单创建*/
        vendor('wechat.wechat');
        $menuObj = new \menu($this->data);
        $params = $menuObj->createMenu($menuArr);
        /*--end*/
        if($params['errcode'] == 0){
            $this->success('菜单已成功发布');
        }else{
            $this->error("菜单发布失败,错误代码[".$params['errcode']."]：".$params['errmsg']);
        }
    }

    //菜单转换
    private function menu_convert($p_menus){
        $new_arr = array();
        $count = 0;
        foreach($p_menus as $k => $v){
            $new_arr[$count]['name'] = $v['title'];

            //获取子菜单
            $c_menus = Db::name('gzh_menu')->where(['level'=>2,'pid'=>$v['id']])->order('id asc')->select();

            if(!empty($c_menus)){
                foreach($c_menus as $kk => $vv){
                    $add = array();
                    $add['name'] = $vv['title'];
                    $add['type'] = $vv['type'];

                    if ('sendmsg' == $add['type']){
                        $add['type'] = 'article_id';
                        $article_id = Db::name('gzh_material')->where('id',$vv['material_id'])->value('article_id');
                        $add['article_id'] = $article_id;
                    }elseif ('view' == $add['type']){
                        $add['url'] = $vv['jump_url'];
                    }elseif ('click' == $add['type']){
                        $add['key'] = $vv['key'];
                    }elseif ('miniprogram' == $add['type']){
                        $add['url'] = $vv['url'];
                        $add['appid'] = $vv['appid'];
                        $add['path'] = $vv['path'];
                    }

                    if($add['name']){
                        $new_arr[$count]['sub_button'][] = $add;
                    }
                }
            }else{
                $new_arr[$count]['type'] = $v['type'];
                if($new_arr[$count]['type'] == 'sendmsg'){
                    $new_arr[$count]['type'] = 'article_id';
                    $article_id = Db::name('gzh_material')->where('id',$v['material_id'])->value('article_id');
                    $new_arr[$count]['article_id'] = $article_id;
                }elseif ('view' == $new_arr[$count]['type']){
                    $new_arr[$count]['url'] = $v['jump_url'];
                }elseif ('click' == $new_arr[$count]['type']){
                    $new_arr[$count]['key'] = $v['url'];
                }elseif ('miniprogram' == $new_arr[$count]['type']){
                    $new_arr[$count]['url'] = $v['url'];
                    $new_arr[$count]['appid'] = $v['appid'];
                    $new_arr[$count]['path'] = $v['path'];
                }
            }
            $count++;
        }

        return $new_arr;
    }

    // 图文素材 - 列表
    public function material_list_pictext()
    {
        //先轮询发布状态
        $publish_list = Db::name('gzh_material')->where('publish_id','>',0)->where('publish_status',1)->select();
        if (!empty($publish_list)){
            vendor('wechat.wechat');
            $materialObj = new \material($this->data);
            foreach ($publish_list as $k => $v){
                $materialObj->publishGet($v['publish_id']);
            }
        }
        $condition['type'] = 2;
        $condition['parent_id'] = 0; //只查第一条

        $keywords = input('keywords/s');
        if (!empty($keywords)) $condition['title'] = ['like', "%{$keywords}%"];

        $count = Db::name('gzh_material')->where($condition)->count('id');
        $Page = $pager = new Page($count, config('paginate.list_rows'));
        $list = Db::name('gzh_material')->where($condition)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();

        $publish_status_arr = [
            '成功','发布中','原创失败','常规失败','平台审核不通过','成功后用户删除所有文章','成功后系统封禁所有文章'
        ];
        foreach ($list as $k=> $v){
            $list[$k]['publish_status_name'] = $publish_status_arr[$v['publish_status']];
        }

        $show = $Page->show();
        $this->assign('page', $show);
        $this->assign('list', $list);
        $this->assign('pager', $pager);
        return $this->fetch('material_list_pictext');
    }

    /**
     * 插件后台管理 - 新增图文素材
     */
    public function material_pictext_add()
    {
        if (IS_POST) {
            $post = input('post.');
            foreach ($post['data'] as $k => $v) {
                if (empty($v['title'])) $this->error('标题不能为空');
                if (empty($v['litpic'])) $this->error('缩略图不能为空');
                $v['type'] = 2;
                $v['add_time'] = getTime();
                $v['update_time'] = getTime();
                $post['data'][$k] = $v;
            }
            $first_aid = Db::name('gzh_material')->insertGetId($post['data'][0]);
            if (false !== $first_aid) {
                unset($post['data'][0]);
                if (count($post['data']) > 0) {
                    foreach ($post['data'] as $k => $v) {
                        $post['data'][$k]['parent_id'] = $first_aid;
                    }
                    Db::name('gzh_material')->insertAll($post['data']);
                }
                $update_arr = [];
                $articles_arr = [];
                vendor('wechat.wechat');
                $materialObj = new \material($this->data);
                //新增素材
                $list = Db::name('gzh_material')->where('id|parent_id', $first_aid)->order('parent_id asc,id asc')->select();
                if (!empty($list)) {
                    foreach ($list as $k => $v) {
                        $v['intro'] = htmlspecialchars_decode($v['intro']);
                        $params = $materialObj->addMaterial(ROOT_PATH . ltrim($v['litpic'], '/'), 'image');
                        $update['thumb_media_id'] = $params['media_id'];
                        $update['wx_img_url'] = $params['url'];
                        $update['id'] = $v['id'];
                        $update_arr[] = $update;
                        $articles = [
                            "title" => $v['title'],
                            "thumb_media_id" => $params['media_id'],
                            "content" => $v['intro'],
                        ];
                        if (!empty($v['author'])) $articles['author'] = $v['author'];
                        if (!empty($v['original_url'])) $articles['content_source_url'] = $v['original_url'];
                        if (1 == count($list)) {
                            $digest = @msubstr(checkStrHtml($v['intro']), 0, 50, false);
                            $articles['digest'] = $digest;
                        }
                        $articles_arr[] = $articles;
                    }

                    if (!empty($update_arr)) model('GzhMaterial')->saveAll($update_arr);

                    if (!empty($articles_arr)) {
                        $params = $materialObj->addNews($articles_arr);
                        if (!empty($params['media_id'])) {
                            Db::name('gzh_material')->where('id', $first_aid)->update(['media_id' => $params['media_id'], 'update_time' => getTime()]);
                            $materialObj->submitDraff($params['media_id']);
                        }
                    }
                }
                $this->success('新增成功!');
            }
            $this->error('新增失败!');
        }
        return $this->fetch('material_pictext_add');
    }

    /**
     * 插件后台管理 - 编辑图文素材
     */
    public function material_pictext_edit()
    {
        if (IS_POST) {
            $post = input('post.');
            $id = !empty($post['data'][0]['id']) ? $post['data'][0]['id'] : 0;
            if (empty($id)) $this->error('缺少必要参数');
            $ids = [];
            //修改前的素材列表
            $origin_list = Db::name('gzh_material')->where('id|parent_id', $id)->order('parent_id asc,id asc')->getAllWithIndex('id');
            $media_id = $origin_list[0]['media_id'];
            foreach ($post['data'] as $k => $v) {
                if (empty($v['title'])) $this->error('标题不能为空');
                if (empty($v['litpic'])) $this->error('缩略图不能为空');
                if (empty($v['id'])) {
                    $v['add_time'] = getTime();
                } else {
                    $ids[] = $v['id'];
                }
                $v['update_time'] = getTime();
                $post['data'][$k] = $v;
            }
            $articles_arr = [];
            //筛选出改变的缩略图 或者新的缩略图 重新上传
            vendor('wechat.wechat');
            $materialObj = new \material($this->data);
            foreach ($post['data'] as $k => $v) {
                if ( (!empty($v['id']) && $v['litpic'] != $origin_list[$v['id']]['litpic']) || empty($v['id'])) {
                    //上传缩略图素材
                    $params = $materialObj->addMaterial(ROOT_PATH . ltrim($v['litpic'], '/'), 'image');
                    $v['thumb_media_id'] = $params['media_id'];
                    $v['wx_img_url'] = $params['url'];
                    //删除原先的素材
                    if (!empty($origin_list[$v['id']]['thumb_media_id'])) $materialObj->delMaterial($origin_list[$v['id']]['thumb_media_id']);
                }
                $articles = [
                    "title" => $v['title'],
                    "thumb_media_id" => $v['thumb_media_id'],
                    "content" => $v['intro'],
                ];
                if (!empty($v['author'])) $articles['author'] = $v['author'];
                if (!empty($v['original_url'])) $articles['content_source_url'] = $v['original_url'];
                if (1 == count($post['data'])) {
                    $digest = @msubstr(checkStrHtml($v['intro']), 0, 50, false);
                    $articles['digest'] = $digest;
                }

                $articles_arr[] = $articles;
                $post['data'][$k] = $v;
            }

            unset($post['data'][0]['id']);
            $res = Db::name('gzh_material')->where('id', $id)->update($post['data'][0]);
            if (false !== $res) {
                unset($post['data'][0]);

                if (!empty($ids)) {//删除编辑中删除的素材
                    $where['parent_id'] = $id;
                    $where['type'] = 2;
                    $delete_list = Db::name('gzh_material')->where('id', 'not in', $ids)->where($where)->select();
                    $res = Db::name('gzh_material')->where('id', 'not in', $ids)->where($where)->delete();
                    if (false != $res) {
                        foreach ($delete_list as $k => $v) {
                            $materialObj->delMaterial($v['thumb_media_id']);//删除永久素材
                        }
                    }
                }

                if (count($post['data']) > 0) {
                    $insert = [];
                    foreach ($post['data'] as $k => $v) {
                        if (empty($v['id'])) {
                            $v['type'] = 2;
                            $v['parent_id'] = $id;
                            $insert[] = $v;
                        } else {
                            Db::name('gzh_material')->where('id', $v['id'])->update($v);
                        }
                    }
                    if (!empty($insert)) {
                        Db::name('gzh_material')->insertAll($insert);
                    }
                }

                //重新上传素材
                if (!empty($articles)) {
                    //删除原先的素材
                    if (!empty($media_id)) $materialObj->delNews($media_id);
                    //新建素材
                    $params = $materialObj->addNews($articles_arr);
                    if (!empty($params['media_id'])) {
                        Db::name('gzh_material')->where('id', $id)->update(['media_id' => $params['media_id'], 'update_time' => getTime()]);
                        $materialObj->submitDraff($params['media_id']);
                    }
                }
                $this->success('编辑成功!');
            }
            $this->error('编辑失败!');
        }
        $id = input('id/d');
        $list = Db::name('gzh_material')->where('id|parent_id', $id)->order('parent_id asc,id asc')->select();
        if (empty($list)) $this->error('数据不存在');
        $this->assign('info', $list);
        return $this->fetch('material_pictext_edit');
    }

    //文本素材 - 列表
    public function material_list_text()
    {
        $condition['type'] = 1;

        $keywords = input('keywords/s');
        if (!empty($keywords)) $condition['intro'] = ['like', "%{$keywords}%"];

        $count = Db::name('gzh_material')->where($condition)->count('id');
        $Page = $pager = new Page($count, config('paginate.list_rows'));
        $list = Db::name('gzh_material')->where($condition)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();

        $show = $Page->show();
        $this->assign('page', $show);
        $this->assign('list', $list);
        $this->assign('pager', $pager);
        return $this->fetch('material_list_text');
    }

    //文字素材 - 新增
    public function material_text_add()
    {
        if (IS_POST) {
            $post = input('post.');
            if (empty($post['intro'])) $this->error('内容不能为空');
            $insert = [
                'type' => 1,
                'intro' => $post['intro'],
                'appid' => !empty($this->data['appid']) ? $this->data['appid'] : '',
                'add_time' => getTime(),
                'update_time' => getTime(),
            ];
            $res = Db::name('gzh_material')->insert($insert);
            if (false !== $res) {
                $this->success('新增成功!');
            }
            $this->error('新增失败');
        }
        return $this->fetch('material_text_add');
    }

    //文字素材 - 编辑
    public function material_text_edit()
    {
        if (IS_POST) {
            $post = input('post.');
            if (empty($post['id'])) $this->error('缺少必要参数');
            if (empty($post['intro'])) $this->error('内容不能为空');
            $post['update_time'] = getTime();
            $id = $post['id'];
            unset($post['id']);
            $res = Db::name('gzh_material')->where('id', $id)->update($post);
            if (false !== $res) {
                $this->success('编辑成功!');
            }
            $this->error('编辑失败');
        }
        $id = input('id/d');
        $info = Db::name('gzh_material')->where('id', $id)->find();
        if (empty($info)) $this->error('数据不存在');
        $this->assign('info', $info);
        return $this->fetch('material_text_edit');
    }

    //素材 - 删除
    public function material_del()
    {
        $id_arr = input('del_id/a');
        $id_arr = eyIntval($id_arr);
        if (IS_POST && !empty($id_arr)) {
            $material_list = Db::name("gzh_material")->where(['id|parent_id' => ['in', $id_arr]])->field('media_id,thumb_media_id')->select();
            $r = Db::name("gzh_material")->where(['id|parent_id' => ['in', $id_arr]])->delete();
            if ($r !== false) {
                adminLog('删除消息素材');
                vendor('wechat.wechat');
                $materialObj = new \material($this->data);
                foreach ($material_list as $k => $v){
                    if (!empty($v['media_id'])) $materialObj->delNews($v['media_id']);
                    if (!empty($v['thumb_media_id'])) $materialObj->delMaterial($v['thumb_media_id']);
                }

                $this->success('删除成功');
            }
        }
        $this->error('删除失败');
    }

    /**
     * 插件后台管理 - 弹窗图文列表
     */
    public function selcet_material_list()
    {
        $type = input('type/d');
        if (empty($type)) $type = 1;
        $condition['type'] = $type;
        if (2 == $type) {
            $condition['parent_id'] = 0;//只查第一条
            $condition['publish_status'] = 0;//只能选发布成功的素材
        }

        $keywords = input('keywords/s');
        if (!empty($keywords)) {
            if (1 == $type) {
                $condition['intro'] = ['like', "%{$keywords}%"];
            } else {
                $condition['title'] = ['like', "%{$keywords}%"];
            }
        }

        $count = Db::name('gzh_material')->where($condition)->count('id');
        $Page = $pager = new Page($count, config('paginate.list_rows'));
        $list = Db::name('gzh_material')->where($condition)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->getAllWithIndex('id');
        if (!empty($list) && 2 == $type) {
            $mid = get_arr_column($list, 'id');
            $child_list = Db::name('gzh_material')->where('parent_id', 'in', $mid)->select();
            if (!empty($child_list)) {
                foreach ($child_list as $k => $v) {
                    $list[$v['parent_id']]['child'][] = $v;
                }
            }
        }

        $show = $Page->show();
        $this->assign('page', $show);
        $this->assign('list', $list);
        $this->assign('pager', $pager);

        return $this->fetch();
    }

    /**
     * 关键字选择
     */
    public function selcet_keyword_list()
    {
        $keyword = input('param.keyword/s');
        $where = [];
        if (!empty($keyword)) $where['keywords'] = ['LIKE',"%{$keyword}%"];

        $count = Db::name('gzh_keyword')->where($where)->count('id');

        $Page = $pager = new Page($count, config('paginate.list_rows'));
        $list = Db::name('gzh_keyword')->where($where)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->getAllWithIndex('id');
        if (!empty($list)){
            foreach ($list as $k => $v) {
                $list[$k]['keywords'] = explode(',',$v['keywords']);
                foreach ($list[$k]['keywords'] as $k => $v){

                }
            }
        }
        $show = $Page->show();
        $this->assign('page', $show);
        $this->assign('list', $list);
        $this->assign('pager', $pager);

        return $this->fetch();
    }

    // 插件后台管理 - 弹窗文档列表
    public function selcet_arc_list()
    {
        $assign_data = array();
        $condition = array();
        $param = I('param.');
        $typeid = I('typeid/d', 0);

        foreach (['keywords', 'typeid'] as $key) {
            if (isset($param[$key]) && $param[$key] !== '') {
                if ($key == 'keywords') {
                    $condition['a.title'] = array('LIKE', "%{$param[$key]}%");
                } else if ($key == 'typeid') {
                    $result = model('Arctype')->getHasChildren($param[$key]);
                    $condition['a.typeid'] = array('IN', array_keys($result));
                } else {
                    $condition['a.' . $key] = array('eq', $param[$key]);
                }
            }
        }

        $condition['a.arcrank'] = 0;
        $condition['a.status'] = 1;

        $count = Db::name('archives')->alias('a')->where($condition)->count('aid');
        $pageObj = new Page($count, config('paginate.list_rows'));
        $list = Db::name('archives')
            ->field("a.aid")
            ->alias('a')
            ->where($condition)
            ->order('a.aid desc')
            ->limit($pageObj->firstRow . ',' . $pageObj->listRows)
            ->getAllWithIndex('aid');

        if ($list) {
            $aids = array_keys($list);
            $fields = "b.*, a.*, a.aid as aid, c.ctl_name";
            $row = Db::name('archives')
                ->field($fields)
                ->alias('a')
                ->join('__ARCTYPE__ b', 'a.typeid = b.id', 'LEFT')
                ->join('channeltype c', 'c.id=a.channel', 'left')
                ->where('a.aid', 'in', $aids)
                ->getAllWithIndex('aid');
            $seo_config = tpCache('seo');
            foreach ($list as $key => $val) {
                $arcurl = arcurl("home/{$val['ctl_name']}/view", $row[$val['aid']], true, true, $seo_config['seo_pseudo'], $seo_config['seo_rewrite_format']);
                $row[$val['aid']]['arcurl'] = $arcurl;
                $litpic = $row[$val['aid']]['litpic'];
                if (!empty($litpic) && !is_http_url($litpic)) {
                    $row[$val['aid']]['litpic'] = request()->domain() . $litpic;
                }
                $list[$key] = $row[$val['aid']];
            }
        }
        $pageStr = $pageObj->show();
        $assign_data['pageStr'] = $pageStr;
        $assign_data['list'] = $list;
        $assign_data['pageObj'] = $pageObj;

        $select_html = allow_release_arctype($typeid);//允许发布文档列表的栏目
        $this->assign('select_html', $select_html);

        $this->assign($assign_data);

        return $this->fetch('selcet_arc_list');
    }

    /**
     * 插件后台管理 - 关键词自动回复
     */
    public function reply_index()
    {
        $where = '';
        $keyword = input('keywords/s');
        if (!empty($keyword)) $where = ['LIKE',"%{$keyword}%"];

        $count = Db::name('gzh_keyword')->where($where)->count('id');
        $pageObj = new Page($count, config('paginate.list_rows'));
        $list = Db::name('gzh_keyword')
            ->where($where)
            ->order('id desc')
            ->limit($pageObj->firstRow . ',' . $pageObj->listRows)
            ->select();

        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $list[$k]['material_id'] = explode(',', $v['material_id']);
            }
        }

        $pageStr = $pageObj->show();
        $assign_data['pageStr'] = $pageStr;
        $assign_data['list'] = $list;
        $assign_data['pageObj'] = $pageObj;
        $this->assign($assign_data);

        return $this->fetch('reply_index');
    }

    /**
     * 插件后台管理 - 默认回复
     */
    public function reply_default()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');
            if (empty($post['keyword'])) $this->error('缺少必要参数');
            if (empty($post['type'])) $this->error('请选择回复类型');
            if ('LINK' == $post['type']) {
                $post['text'] = '';
                $post['material_id'] = 0;
                $post['aid'] = 0;
            } elseif ('TEXT' == $post['type']) {
                $post['link'] = '';
                $post['material_id'] = 0;
                $post['aid'] = 0;
            } elseif ('PIC' == $post['type']) {
                $post['text'] = '';
                $post['link'] = '';
                $post['aid'] = 0;
            } elseif ('ARC' == $post['type']) {
                $post['text'] = '';
                $post['link'] = '';
                $post['material_id'] = 0;
            }
            $is_have = Db::name('gzh_subscribe')->where('keyword', $post['keyword'])->find();
            if (!empty($is_have)) {
                $post['update_time'] = getTime();
                $res = Db::name('gzh_subscribe')->where('keyword', $post['keyword'])->update($post);
            } else {
                $post['add_time'] = getTime();
                $post['update_time'] = getTime();
                $res = Db::name('gzh_subscribe')->where('keyword', $post['keyword'])->insert($post);
            }
            if (false !== $res) {
                $this->success('保存成功');
            }
            $this->error('保存失败');
        }
        $info = Db::name('gzh_subscribe')->where('keyword', 'default')->find();
        if ('PIC' == $info['type']){
            $material = Db::name('gzh_material')->where('id',$info['material_id'])->field('title,litpic')->find();
            $info['title'] = $material['title'];
            $info['litpic'] = $material['litpic'];
        }else if('ARC' == $info['type']){
            $material = Db::name('archives')->where('aid',$info['aid'])->field('title,litpic')->find();
            $info['title'] = $material['title'];
            $info['litpic'] = $material['litpic'];
        }
        $this->assign('info', $info);

        return $this->fetch('reply_default');
    }

    /**
     * 插件后台管理 - 关注后自动回复
     */
    public function reply_follow()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');
            if (empty($post['keyword'])) $this->error('缺少必要参数');
            if (empty($post['type'])) $this->error('请选择回复类型');
            if ('LINK' == $post['type']) {
                $post['text'] = '';
                $post['material_id'] = 0;
                $post['aid'] = 0;
            } elseif ('TEXT' == $post['type']) {
                $post['link'] = '';
                $post['material_id'] = 0;
                $post['aid'] = 0;
            } elseif ('PIC' == $post['type']) {
                $post['text'] = '';
                $post['link'] = '';
                $post['aid'] = 0;
            } elseif ('ARC' == $post['type']) {
                $post['text'] = '';
                $post['link'] = '';
                $post['material_id'] = 0;
            }
            $is_have = Db::name('gzh_subscribe')->where('keyword', $post['keyword'])->find();
            if (!empty($is_have)) {
                $post['update_time'] = getTime();
                $res = Db::name('gzh_subscribe')->where('keyword', $post['keyword'])->update($post);
            } else {
                $post['add_time'] = getTime();
                $post['update_time'] = getTime();
                $res = Db::name('gzh_subscribe')->where('keyword', $post['keyword'])->insert($post);
            }
            if (false !== $res) {
                $this->success('保存成功');
            }
            $this->error('保存失败');
        }
        $info = Db::name('gzh_subscribe')->where('keyword', 'follow')->find();
        if ('PIC' == $info['type']){
            $material = Db::name('gzh_material')->where('id',$info['material_id'])->field('title,litpic')->find();
            $info['title'] = $material['title'];
            $info['litpic'] = $material['litpic'];
        }else if('ARC' == $info['type']){
            $material = Db::name('archives')->where('aid',$info['aid'])->field('title,litpic')->find();
            $info['title'] = $material['title'];
            $info['litpic'] = $material['litpic'];
        }
        $this->assign('info', $info);

        return $this->fetch('reply_follow');
    }

    /**
     * 插件后台管理 - 关键词新增
     */
    public function reply_keyword_add()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');
            if (empty($post['rule'])) {
                $this->error('规则名称不能为空');
            }
            if (empty($post['keywords'])) {
                $this->error('请至少填写一个关键词');
            }
            foreach ($post['keywords'] as $key => $value) {
                if ($value === '') {
                    unset($post['keywords'][$key]);
                }
            }
            if (empty($post['material_id'])) {
                $this->error('请至少添加一个回复内容');
            }
            $post['keywords'] = array_unique($post['keywords']);
            $post['keywords'] = implode(',', $post['keywords']);
            $post['text_count'] = Db::name('gzh_material')->where('id', 'in', $post['material_id'])->where('type', 1)->count();
            $post['pic_count'] = count($post['material_id']) - $post['text_count'];
            $post['material_id'] = array_unique($post['material_id']);
            $post['material_id'] = implode(',', $post['material_id']);
            $post['add_time'] = getTime();
            $post['update_time'] = getTime();
            $res = Db::name('gzh_keyword')->insert($post);
            if (false !== $res) {
                $this->success('新增成功!');
            }
            $this->error('请求失败!');
        }
        return $this->fetch('reply_keyword_add');
    }

    /**
     * 插件后台管理 - 关键词编辑
     */
    public function reply_keyword_edit()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');
            if (empty($post['id'])) $this->error('缺少必要参数');
            $id = $post['id'];
            unset($post['id']);
            if (empty($post['rule'])) $this->error('规则名称不能为空');
            if (empty($post['keywords'])) {
                $this->error('请至少填写一个关键词');
            }
            foreach ($post['keywords'] as $key => $value) {
                if ($value === '') {
                    unset($post['keywords'][$key]);
                }
            }
            if (empty($post['material_id'])) {
                $this->error('请至少添加一个回复内容');
            }
            $post['keywords'] = implode(',', $post['keywords']);
            $post['text_count'] = Db::name('gzh_material')->where('id', 'in', $post['material_id'])->where('type', 1)->count();
            $post['pic_count'] = count($post['material_id']) - $post['text_count'];
            $post['material_id'] = implode(',', $post['material_id']);
            $post['add_time'] = getTime();
            $post['update_time'] = getTime();
            $res = Db::name('gzh_keyword')->where('id', $id)->update($post);
            if (false !== $res) {
                $this->success('编辑成功!');
            }
            $this->error('请求失败!');
        }
        $id = input('id/d');
        $info = Db::name('gzh_keyword')->where('id', $id)->find();
        if (empty($info)) $this->error('数据不存在');
        $info['keywords'] = explode(',', $info['keywords']);
        $info['material'] = Db::name('gzh_material')->where('id', 'in', $info['material_id'])->field('id,title,intro,type')->select();

        $this->assign('info', $info);

        return $this->fetch('reply_keyword_edit');
    }

    public function reply_keyword_del()
    {
        $id_arr = input('del_id/a');
        $id_arr = eyIntval($id_arr);
        if (IS_POST && !empty($id_arr)) {
            $r = Db::name("gzh_keyword")->where(['id' => ['in', $id_arr]])->delete();
            if ($r !== false) {
                adminLog('删除关键字');
                $this->success('删除成功');
            }
        }
        $this->error('删除失败');
    }
}