<?php namespace Phpcmf\Admin;

/**
  * http://www.diyuncms.com
 * 本文件是框架系统文件，二次开发时不可以修改本文件，可以通过继承类方法来重写此文件
 **/

// 评论操作类 基于 Ftable
class Form extends \Phpcmf\Table
{
    public $cid; // 内容id
    public $fid; // fid
    public $form; // 模块信息
    public $module; // 模块信息
    public $form_menu; // 是否显示模块菜单
    public $is_verify; // 来自审核

    // 上级公共类
    public function __construct(...$params) {
        parent::__construct(...$params);
        $this->_Extend_Init();
    }

    // 继承类初始化
    protected function _Extend_Init() {
        $this->fid = $fid = str_replace(['_comment_verify', '_comment'], '', \Phpcmf\Service::L('Router')->class);
        $cache = \Phpcmf\Service::L('cache')->get('form-'.SITE_ID);
        $this->form = $cache[$fid];
        if (!$this->form) {
            $this->_msg(0, dr_lang('网站表单【%s】不存在', $fid));
            exit;
        }

        $cache = \Phpcmf\Service::L('cache')->get('app-comment-'.SITE_ID, 'form', $fid);
        $this->cname = dr_comment_cname($cache['cname']);
        if (!$cache) {
            $this->_admin_msg(0, dr_lang('网站表单【%s】没有安装%s', $fid, $this->cname));
        } elseif (!$cache['use']) {
            $this->_admin_msg(0, dr_lang('网站表单【%s】没有启用%s', $fid, $this->cname));
        }
        $cache['name'] = $this->cname;
        $this->form['comment'] = $cache;
        $this->module = $this->form;
        $this->comment_model = \Phpcmf\Service::M('form', 'comment')->_init($this->form, $fid, SITE_ID, $cache);
        // 指定后台模板路径
        $this->admin_tpl_path = dr_get_app_dir('comment').'Views/';
        // 支持附表存储
        $this->is_data = 0;
        // 模板前缀(避免混淆)
        $this->tpl_prefix = 'share_comment_';
        // 单独模板命名
        $this->tpl_name = 'comment_'.$fid;
        // 模块显示名称
        $this->name = dr_lang('网站表单[%s]%s', $this->form['name'], $this->cname);
        // 获取父级内容
        $this->cid = intval(\Phpcmf\Service::L('input')->get('cid'));
        $this->cid && $this->index = $this->comment_model->get_row($this->cid);
        // 自定义字段
        if (!$this->form['comment']['comment_list_field']) {
            $this->form['comment']['comment_list_field'] = [
                'content' => [
                    'use' => 1,
                    'name' => dr_lang('内容'),
                    'func' => 'comment',
                    'width' => 0,
                ],
            ];
        }
        $this->form['comment']['field'] = dr_array22array(
            [
                'content' => [
                    'name' => dr_lang('内容'),
                    'ismain' => 1,
                    'fieldtype' => 'Ueditor',
                    'fieldname' => 'content',
                    'setting' => array(
                        'option' => array(
                            'height' => 250,
                            'mode' => 1,
                            'width' => '100%'
                        )
                    ),
                ]
            ],
            $this->form['comment']['field']
        );
        // 判断是否来自审核控制器
        $this->is_verify = strpos(\Phpcmf\Service::L('Router')->class, '_verify') !== false;
        // 自定义条件
        $where = $this->is_verify ? 'status<>1' : 'status=1';
        $this->cid && $where.= ' and cid='. $this->cid;
        $sysfield = ['inputtime', 'inputip', 'author'];
        $this->is_verify && $sysfield[] = 'status';
        // 初始化数据表
        $this->_init([
            'table' => SITE_ID.'_form_'.$fid.'_comment',
            'field' => $this->form['comment']['field'],
            'sys_field' => $sysfield,
            'date_field' => 'inputtime',
            'show_field' => 'id',
            'list_field' => $this->form['comment']['comment_list_field'],
            'order_by' => 'inputtime desc',
            'where_list' => $where,
        ]);

        // 控制菜单
        if ($this->is_verify) {
            $menu = [
                '审核管理' => [APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/index', 'fa fa-edit'],
            ];
        } else {
            $menu = [
                dr_lang('%s管理', $this->cname) => [APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/index{cid='.$this->cid.'}', 'fa fa-comments'],
                dr_lang('返回%s管理', $this->form['name']) => [APP_DIR.'/'.$this->form['table'].'/index', dr_icon($this->form['setting']['icon'])],
            ];
            if ($this->cid) {
                $menu['发布'] = [APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/add{cid='.$this->cid.'}', 'fa fa-plus'];
            }
            if ($this->form['comment']['review'] &&  $this->cid) {
                $menu['查看评分'] = [APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/review_index{cid='.$this->cid.'}', 'fa fa-thumbs-o-up'];
            }
        }
        // 写入模板
        \Phpcmf\Service::V()->assign([
            'menu' => \Phpcmf\Service::M('auth')->_admin_menu($menu),
            'field' => $this->init['field'],
            'index' => $this->index,
            'is_verify' => $this->is_verify,
            'comment_url' => dr_url_prefix(\Phpcmf\Service::L('Router')->form_show_url($fid, $this->cid)),
        ]);
    }

    // ========================

    // 后台查看列表
    protected function _Admin_List() {

        list($tpl) = $this->_List(['cid' => $this->cid]);

        \Phpcmf\Service::V()->assign([
            'p' => ['cid' =>  $this->cid],
        ]);
        \Phpcmf\Service::V()->display($tpl);
    }

    // 后台添加内容
    protected function _Admin_Add() {

        if (!$this->cid) {
            $this->_admin_msg(0, dr_lang('缺少cid参数'));
        }

        list($tpl, $data) = $this->_Post();
        \Phpcmf\Service::V()->assign([
            'data' => $data,
            'form' => dr_form_hidden(),
            'review' => $this->form['comment']['review'],
        ]);
        \Phpcmf\Service::V()->display($tpl);
    }

    // 后台修改内容
    protected function _Admin_Edit() {

        if (!$this->cid) {
            $this->_admin_msg(0, dr_lang('缺少cid参数'));
        }

        $id = intval(\Phpcmf\Service::L('input')->get('id'));
        list($tpl, $data) = $this->_Post($id);

        if (!$data) {
            $this->_admin_msg(0, dr_lang('数据不存在: '.$id));
        } elseif ($this->cid != $data['cid']) {
            $this->_admin_msg(0, dr_lang('cid不匹配'));
        } elseif ($this->is_verify && $data['status'] == 1) {
            $this->_admin_msg(0, dr_lang('已经通过了审核'));
        }

        \Phpcmf\Service::V()->assign([
            'data' => $data,
            'form' => dr_form_hidden(),
            'review' => $this->form['comment']['review'],
        ]);
        \Phpcmf\Service::V()->display($tpl);
    }

    // 后台查看评分信息
    protected function _Admin_Review() {
        \Phpcmf\Service::V()->assign([
            'review' => $this->form['comment']['review'],
            'comment' => $this->comment_model->get_comment_index($this->cid, $this->index['catid']),
        ]);
        \Phpcmf\Service::V()->admin($this->admin_tpl_path);
        \Phpcmf\Service::V()->display('share_comment_review.html');exit;
    }

    // 后台查看内容
    protected function _Admin_Show() {

        if (!$this->cid) {
            $this->_admin_msg(0, dr_lang('缺少cid参数'));
        }

        $id = intval(\Phpcmf\Service::L('input')->get('id'));
        list($tpl, $data) = $this->_Show($id);

        if (!$data) {
            $this->_admin_msg(0, dr_lang('数据不存在: '.$id));
        } elseif ($this->cid != $data['cid']) {
            $this->_admin_msg(0, dr_lang('cid不匹配'));
        }

        \Phpcmf\Service::V()->display($tpl);
    }

    // 后台批量审核
    protected function _Admin_Status() {

        $tid = intval(\Phpcmf\Service::L('input')->get('tid'));
        $ids = \Phpcmf\Service::L('input')->get_post_ids();
        if (!$ids) {
            $this->_json(0, dr_lang('所选数据不存在'));
        }

        // 格式化
        $in = [];
        foreach ($ids as $i) {
            $i && $in[] = intval($i);
        }
        if (!$in) {
            $this->_json(0, dr_lang('所选数据不存在'));
        }

        $rows = \Phpcmf\Service::M()->init($this->init)->where_in('id', $in)->getAll();
        if (!$rows) {
            $this->_json(0, dr_lang('所选数据不存在'));
        }

        foreach ($rows as $row) {

            if ($row['status'] != 1) {
                if ($tid) {
                    // 拒绝
                    \Phpcmf\Service::M()->db->table($this->init['table'])->where('id', $row['id'])->update(['status' => 2]);

                    \Phpcmf\Service::M('member')->delete_admin_notice(APP_DIR.'/'.$this->fid.'_comment_verify/edit:cid/'.$row['cid'].'/id/'.$row['id'], SITE_ID);
                    // 提醒
                    \Phpcmf\Service::M('member')->notice($row['uid'], 3, dr_lang('%s审核被拒绝',  $this->cname));
                    // 挂钩点 被拒绝
                    \Phpcmf\Hooks::trigger('form_comment_verify_0', $row);
                } else {
                    // 通过
                    $this->comment_model->verify_comment($row);
                }
            }
        }

        $this->_json(1, dr_lang('操作成功'));
    }

    // 后台删除内容
    protected function _Admin_Del() {
        $this->_Del(
            \Phpcmf\Service::L('input')->get_post_ids(),
            null,
            function ($rows) {
                // 对应删除提醒
                foreach ($rows as $t) {
                    \Phpcmf\Service::M('member')->delete_admin_notice(APP_DIR.'/'.$this->fid.'_comment_verify/edit:cid/'.$t['cid'].'/id/'.$t['id'], SITE_ID);
                    // 重新统计评论数
                    $this->comment_model->comment_update_total($t);
                    $this->comment_model->comment_update_review($t);
                }

            },
            \Phpcmf\Service::M()->dbprefix($this->init['table'])
        );
    }

    // 容错处理
    public function edit_order() {
        $this->_Admin_Order();
    }

    // ===========================

    /**
     * 获取内容
     * $id      内容id,新增为0
     * */
    protected function _Data($id = 0) {

        $row = $this->comment_model->table($this->comment_model->mytable.'_comment')->get($id);
        if (!$row) {
            return [];
        }

        return $row;
    }

    // 格式化保存数据 保存之前
    protected function _Format_Data($id, $data, $old) {

        // 验证父数据
        if (!$this->index) {
            $this->_json(0, dr_lang('关联内容不存在'));
        }

        // 默认数据
        $data[1]['cid'] =  $this->cid;

        // 添加评论
        if (!$id) {
            $data[1]['status'] = 1;
            $data[1]['cuid'] = $this->index['uid'];
        }

        $review = \Phpcmf\Service::L('input')->post('review');
        if ($review) {
            foreach ($review as $i => $v) {
                $data[1]['sort'.$i] = $v;
            }
        }

        return $data;
    }

    /**
     * 保存内容
     * $id      内容id,新增为0
     * $data    提交内容数组,留空为自动获取
     * $func    格式化提交的数据
     * */
    protected function _Save($id = 0, $data = [], $old = [], $func = null, $func2 = null) {

        return parent::_Save($id, $data, $old, null,
            function ($id, $data, $old) {
                // 保存之后
                if ($this->is_verify && $data[1]['status'] == 1) {
                    //审核通知
                    $this->comment_model->verify_comment($old);
                } elseif (!$old) {
                    // 后台新增
                    $this->comment_model->verify_comment($data[1]);
                } else {
                    // 修改数据
                    $this->comment_model->comment_update_total($data[1]);
                    $this->comment_model->comment_update_review($data[1]);
                }

            }
        );
    }

}
