<?php namespace Phpcmf\Controllers\Admin;

class More extends \Phpcmf\Table
{

    public function __construct() {
        parent::__construct();

        if (IS_ADMIN && SITE_ID > 1) {
            $this->_admin_msg(0, '请登录主站账号管理微信插件');
        }

        \Phpcmf\Service::V()->assign('menu', \Phpcmf\Service::M('auth')->_admin_menu(
            [
                '多公众号管理' => [APP_DIR.'/more/index', 'fa fa-user'],
                '添加' => ['add:'.APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/add', 'fa fa-plus', null, '200px'],
            ]
        ));
        // 支持附表存储
        $this->is_data = 0;
        // 表单显示名称
        $this->name = dr_lang('多公众号');
        // 初始化数据表
        $this->_init([
            'table' => 'app_weixin',
            'order_by' => 'id asc',
        ]);
    }

    public function index() {
        $this->_list([], -1);
        \Phpcmf\Service::V()->display('more_list.html');
    }

    public function add() {
        $this->_Post();
        \Phpcmf\Service::V()->display('more_post.html');exit;
    }

    public function edit() {
        $this->_Post(intval(\Phpcmf\Service::L('Input')->get('id')));
        \Phpcmf\Service::V()->display('more_post.html');exit;
    }

    public function go_index() {
        $id = intval(\Phpcmf\Service::L('Input')->get('id'));
        $data = \Phpcmf\Service::M()->table('app_weixin')->get($id);
        if (!$data) {
            $this->_msg(0, '公众号不存在');
        }
        \Phpcmf\Service::L('cache')->set_auth_data('more_weixin', $id, 1);
        $this->_msg(1, '切换到公众号：'.$data['name'], dr_url('weixin/account/index'));
    }

    protected function _Save($id = 0, $data = [], $old = [], $func = null, $func2 = null) {
        return parent::_Save($id, $data, $old, function($id, $data, $old){
            // 保存之前执行的函数，并返回新的数据
            return dr_return_data(1, null, $data);
        }, function ($id, $data, $old) {
            // 保存之后执行的动作
            if (!$old) {
                // 生成新表
                $this->_create_table($id);
            }
        });
    }

    private function _create_table($id) {

        $sql = file_get_contents(APPPATH.'Config/Install.sql');

        $sql = str_replace('{dbprefix}', \Phpcmf\Service::M()->dbprefix('more_'.$id.'_'), $sql);
        $sql_data = explode(';SQL_FINECMS_EOL', trim(str_replace(array(PHP_EOL, chr(13), chr(10)), 'SQL_FINECMS_EOL', $sql)));

        foreach($sql_data as $query){
            if (!$query) {
                continue;
            }
            $ret = '';
            $queries = explode('SQL_FINECMS_EOL', trim($query));
            foreach($queries as $query) {
                $ret.= $query[0] == '#' || $query[0].$query[1] == '--' ? '' : $query;
            }
            if (!$ret) {
                continue;
            }
            if (!\Phpcmf\Service::M()->db->simpleQuery(dr_format_create_sql($ret))) {
                $rt = \Phpcmf\Service::M()->db->error();
                return $ret.': '.$rt['message'];
            }
        }

        return 0;
    }

    private function _delete_table($id) {

        $sql = file_get_contents(APPPATH.'Config/Install.sql');

        $sql = str_replace('{dbprefix}', \Phpcmf\Service::M()->dbprefix('more_'.$id.'_'), $sql);
        $sql_data = explode(';SQL_FINECMS_EOL', trim(str_replace(array(PHP_EOL, chr(13), chr(10)), 'SQL_FINECMS_EOL', $sql)));

        foreach($sql_data as $query){
            if (!$query) {
                continue;
            }
            $ret = '';
            $queries = explode('SQL_FINECMS_EOL', trim($query));
            foreach($queries as $query) {
                $ret.= $query[0] == '#' || $query[0].$query[1] == '--' ? '' : $query;
            }
            if (!$ret) {
                continue;
            } elseif (strpos($ret, 'DROP TABLE') === false) {
                continue;
            }

            if (!\Phpcmf\Service::M()->db->simpleQuery(($ret))) {
                $rt = \Phpcmf\Service::M()->db->error();
                return $ret.': '.$rt['message'];
            }
        }

        return 0;
    }

    // 后台删除表单内容
    public function del() {
        $this->_Del(
            \Phpcmf\Service::L('Input')->get_post_ids(),
            function ($rows) {
                foreach ($rows as $t) {
                    if ($t['id'] == 1) {
                        $this->_json(0, '默认公众号不能删除');
                    }
                    $this->_delete_table($t['id']);
                }
                return dr_return_data(1, 'ok');
            },
            null,
            \Phpcmf\Service::M()->dbprefix($this->init['table'])
        );
    }


}
