<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-06-28
 */

namespace weapp\DedeToEyou\controller;

use think\Page;
use think\Db;
use app\common\controller\Weapp;
use weapp\DedeToEyou\logic\DedeToEyouLogic;

/**
 * 插件的控制器
 */
class DedeToEyou extends Weapp
{
    /**
     * 实例化模型
     */
    private $model;

    /**
     * 实例化对象
     */
    private $db;

    /**
     * 插件基本信息
     */
    private $weappInfo;

    /**
     * 插件基本信息
     */
    private $weappData;
    private $times;

    /**
     * 构造方法
     */
    public function __construct(){
        parent::__construct();
        $this->dedeToEyouLogic = new DedeToEyouLogic;
        $this->db = M('WeappDedeToEyou');
        $this->times = getTime();

        /*插件基本信息*/
        $this->weappInfo = $this->getWeappInfo();
        $this->assign('weappInfo', $this->weappInfo);
        /*--end*/
    }

    public function afterInstall()
    {
        tpSetting('dedetoeyou', ['dedetoeyou_del_all'=>0]);
    }

    public function index(){
        return $this->fetch('doc');
    }

    //模板标签转换
    public function handle_template()
    {
        @ini_set('memory_limit', '-1');
        function_exists('set_time_limit') && set_time_limit(0);
        try{
            $weappData = M('weapp')->where('code','DedeToEyou')->field('data')->find();
            $weappData = json_decode($weappData['data'], true);
            if (!isset($weappData['dede_prefix'])) {
                $this->error('请先配置参数', weapp_url('DedeToEyou/DedeToEyou/conf'));
            } else if (empty($weappData['dede_prefix'])) {
                $this->error('请填写正确的数据库前缀', weapp_url('DedeToEyou/DedeToEyou/conf'));
            }
            // 是否优先转换数据
            $arctypeRow = $this->DeDb('arctype')->field('id')->where(['channeltype'=>['gt', 0]])->order('id asc')->find();
            if (!empty($arctypeRow)) {
                $count = M('arctype')->where('id', $arctypeRow['id'])->count();
                if (empty($count)) {
                    $this->error('请先转换数据', weapp_url('DedeToEyou/DedeToEyou/handle_index'), [], 8);
                }
            }

            // 织梦默认模板路径
            $cfg_df_style = $this->DeDb('sysconfig')->where(['varname'=>'cfg_df_style'])->value('value');
            $cfg_df_style = !empty($cfg_df_style) ? $cfg_df_style : 'default';

            $row = Db::name('weapp')->where(['code'=>'DedeToEyou'])->find();
            if (!empty($row['data'])) {
                $row['data'] = json_decode($row['data'], true);
            }
            $templets_path = !empty($row['data']['templets_path']) ? $row['data']['templets_path'] : 'templets/'.$cfg_df_style;
            $row['data']['templets_path'] = $templets_path;
        }catch (\Exception $e){
            $this->error("请先进行'插件配置'和'数据转换'");
        }
        if (IS_POST) {
            $post = input('param.');

            $saveData = [];
            $data = Db::name('weapp')->where(['code'=>'DedeToEyou'])->value('data');
            $data = json_decode($data, true);
            if (is_array($data)) {
                $saveData = $data;
            }
            $saveData['is_relation'] = !empty($post['is_relation']) ? $post['is_relation'] : 0;
            $templets_path = !empty($post['templets_path']) ? trim($post['templets_path']) : $templets_path;
            $saveData['templets_path'] = trim($templets_path, '/');
            Db::name('weapp')->where(['code'=>'DedeToEyou'])->update([
                'data'  => json_encode($saveData),
                'update_time' => getTime(),
            ]);
            
            $redata = $this->dedeToEyouLogic->DedeToEyouTemplate();
            if (!empty($redata['errfile'])) {
                $this->success('个别模板转换失败，请仔细检查并手工处理少部分模板标签！');
            } else {
                $this->success('大部分标签转换成功。<br/>模板保存在 <font color="red">template/eyou</font> 目录，请仔细检查并手工处理少部分模板标签！');
            }
        }

        $this->assign('row', $row);
        $this->assign('root_dir', $this->root_dir);

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

    public function conf()
    {
        if (IS_POST) {
            $post = input('post.');
            if(!empty($post)){
                $post['dede_prefix'] = trim($post['dede_prefix']);
                try {
                    $this->DeDb('admin', $post['dede_prefix'])->count();
                } catch (\Exception $e) {
                    $this->error('请填写正确的数据库前缀');
                }

                $data = array(
                    'data'  => json_encode($post),
                    'tag_weapp' => 2,
                    'update_time' => $this->times,
                );
                $r = M('weapp')->where('code','DedeToEyou')->update($data);
                if ($r) {
                    adminLog('编辑'.$this->weappInfo['name'].'：插件配置');
                    $this->success("验证成功");
                }
            }
            $this->error("验证失败");
        }

        $data = M('weapp')->where('code','DedeToEyou')->field('data')->find();
        $data = json_decode($data['data'], true);
        $this->assign('data', $data);

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

    private function DeDb($name = '', $prefix = '')
    {
        return $this->dedeToEyouLogic->DeDb($name, $prefix);
    }

    public function handle_index()
    {
        try {
            $this->DeDb('admin')->count();
        } catch (\Exception $e) {
            $weappData = M('weapp')->where('code','DedeToEyou')->field('data')->find();
            $weappData = json_decode($weappData['data'], true);
            $dede_prefix = !empty($weappData['dede_prefix']) ? $weappData['dede_prefix'] : '';
            if (!isset($weappData['dede_prefix'])) {
                $this->error('请先配置参数', weapp_url('DedeToEyou/DedeToEyou/conf'));
            } else if (!empty($weappData['dede_prefix'])) {
                $this->error('请填写正确的数据库前缀', weapp_url('DedeToEyou/DedeToEyou/conf'));
            }
        }

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

    public function handle_del($type = '', $is_jump = true)
    {
        @ini_set('memory_limit', '-1');
        function_exists('set_time_limit') && set_time_limit(0);

        $type = input('param.type/s', $type);
        if (!empty($type)) {
            if (in_array($type, ['arctype','all'])) {
                M('arctype')->where(['id'=>['gt', 0]])->delete();
                M('single_content')->where(['id'=>['gt', 0]])->delete();
                M('archives')->where(['channel'=>['eq', 6]])->delete();
            }
            
            if (in_array($type, ['archives','all'])) {
                $channel = input('param.channel/s');
                $channels = [];
                if (!empty($channel)) {
                    $dede_channels = explode(',', $channel);
                    foreach ($dede_channels as $key => $value) {
                        $channels[$key] = $this->dedeToEyouLogic->DedeChannel($value);
                    }
                }

                $where = " aid > 0 ";
                if (!empty($channels)) {
                    $channels_str = implode(',', $channels);
                    $where .= " AND (channel in ($channels_str)";
                    if (in_array('-2', $channels)) {
                        $where .= " OR channel > 100";
                    }
                    $where .= " ) ";
                } else {
                    $where .= " AND channel <> 6 ";
                }
                $typeid_arr = M('archives')->where($where)->column('typeid');
                M('archives')->where($where)->delete();
                if (empty($channels) || in_array('1', $channels)) {
                    M('article_content')->where(['id'=>['gt', 0]])->delete();
                }
                if (empty($channels) || in_array('2', $channels)) {
                    M('product_content')->where(['id'=>['gt', 0]])->delete();
                    M('product_img')->where(['img_id'=>['gt', 0]])->delete();
                }
                if (empty($channels) || in_array('3', $channels)) {
                    M('images_content')->where(['id'=>['gt', 0]])->delete();
                    M('images_upload')->where(['img_id'=>['gt', 0]])->delete();
                }
                if (empty($channels) || in_array('4', $channels)) {
                    M('download_content')->where(['id'=>['gt', 0]])->delete();
                    M('download_file')->where(['file_id'=>['gt', 0]])->delete();
                }
                if (empty($channels) || in_array('7', $channels)) {
                    M('special_content')->where(['id'=>['gt', 0]])->delete();
                    M('special_node')->where(['node_id'=>['gt', 0]])->delete();
                }
                if (empty($channels) || in_array('-2', $channels)) {
                    $channeltypeRow = Db::name('channeltype')->field('table')->where(['ifsystem'=>0])->select();
                    foreach ($channeltypeRow as $key => $val) {
                        !empty($val['table']) && M($val['table'].'_content')->where(['id'=>['gt', 0]])->delete();
                    }
                }
                if ('all' == $type) {
                    M('tagindex')->where(['id'=>['>', 0]])->delete();
                    M('taglist')->where(['tid'=>['>', 0]])->delete();
                } else if (!empty($typeid_arr)) {
                    M('tagindex')->where(['typeid'=>['in', $typeid_arr]])->delete();
                    M('taglist')->where(['typeid'=>['in', $typeid_arr]])->delete(); 
                }
                try {
                    Db::execute('alter table '.PREFIX.'archives AUTO_INCREMENT 1');
                    Db::execute('alter table '.PREFIX.'article_content AUTO_INCREMENT 1');
                    Db::execute('alter table '.PREFIX.'product_content AUTO_INCREMENT 1');
                    Db::execute('alter table '.PREFIX.'product_img AUTO_INCREMENT 1');
                    Db::execute('alter table '.PREFIX.'images_content AUTO_INCREMENT 1');
                    Db::execute('alter table '.PREFIX.'images_upload AUTO_INCREMENT 1');
                    Db::execute('alter table '.PREFIX.'download_content AUTO_INCREMENT 1');
                    Db::execute('alter table '.PREFIX.'special_content AUTO_INCREMENT 1');
                    Db::execute('alter table '.PREFIX.'special_node AUTO_INCREMENT 1');
                    Db::execute('alter table '.PREFIX.'tagindex AUTO_INCREMENT 1');
                    Db::execute('alter table '.PREFIX.'taglist AUTO_INCREMENT 1');

                    $channeltypeRow = Db::name('channeltype')->field('table')->where(['ifsystem'=>0])->select();
                    foreach ($channeltypeRow as $key => $val) {
                        !empty($val['table']) && Db::execute('alter table '.PREFIX.$val['table'].'_content AUTO_INCREMENT 1');
                    }
                } catch (\Exception $e) {}
            }

            if ('all' == $type) {
                M('users_level')->where('level_id','gt',1)->delete();
                try {
                    Db::execute('alter table '.PREFIX.'users_level AUTO_INCREMENT 1');
                } catch (\Exception $e) {}

                M('links')->where('id','gt',0)->delete();
                M('links_group')->where('id','gt',0)->delete();
                try {
                    Db::execute('alter table '.PREFIX.'links AUTO_INCREMENT 1');
                    Db::execute('alter table '.PREFIX.'links_group AUTO_INCREMENT 1');
                } catch (\Exception $e) {}

                tpSetting('dedetoeyou', ['dedetoeyou_del_all'=>1]);
            }

            $this->dedeToEyouLogic->clear_cache(); // 转完后清理缓存

            if ($is_jump) {
                $this->success('操作成功');
            }
        }

        if ($is_jump) {
            $this->error('操作失败');
        }
    }

    public function handle_web()
    {
        @ini_set('memory_limit', '-1');
        function_exists('set_time_limit') && set_time_limit(0);

        $dede_prefix = '';
        $weappData = M('weapp')->where('code','DedeToEyou')->field('data')->find();
        $weappData = json_decode($weappData['data'], true);
        if (isset($weappData['dede_prefix'])) {
            $dede_prefix = !empty($weappData['dede_prefix']) ? $weappData['dede_prefix'] : '';
        }

        if (IS_POST && !empty($dede_prefix)) {
            $dedetoeyou_del_all = tpSetting('dedetoeyou.dedetoeyou_del_all');
            if (empty($dedetoeyou_del_all)) {
                $this->handle_del('all', false);
            }

            // 数据表结构特殊处理
            $this->dedeToEyouLogic->eyouDatabase();

            $sysconfig = $this->DeDb('sysconfig')->field('varname as name,value')->getAllWithIndex('name');
            $configArr = [];
            $configArr['web'] = [
                'web_name'  => !empty($sysconfig['cfg_webname']['value']) ? $sysconfig['cfg_webname']['value'] : '',
                'web_basehost'  => !empty($sysconfig['cfg_basehost']['value']) ? $sysconfig['cfg_basehost']['value'] : '',
                'web_title'  => !empty($sysconfig['cfg_webname']['value']) ? $sysconfig['cfg_webname']['value'] : '',
                'web_keywords'  => !empty($sysconfig['cfg_keywords']['value']) ? $sysconfig['cfg_keywords']['value'] : '',
                'web_description'  => !empty($sysconfig['cfg_description']['value']) ? $sysconfig['cfg_description']['value'] : '',
                'web_copyright'  => !empty($sysconfig['cfg_powerby']['value']) ? $sysconfig['cfg_powerby']['value'] : '',
                'web_recordnum'  => !empty($sysconfig['cfg_beian']['value']) ? $sysconfig['cfg_beian']['value'] : '',
            ];

            $configArr['basic'] = [
                'basic_indexname'  => !empty($sysconfig['cfg_indexname']['value']) ? $sysconfig['cfg_indexname']['value'] : '',
                'list_symbol'  => !empty($sysconfig['cfg_list_symbol']['value']) ? $sysconfig['cfg_list_symbol']['value'] : '',
                'file_type'  => !empty($sysconfig['cfg_softtype']['value']) ? $sysconfig['cfg_softtype']['value'] : '',
                'media_type'  => !empty($sysconfig['cfg_mediatype']['value']) ? $sysconfig['cfg_mediatype']['value'] : '',
                'file_size' => !empty($sysconfig['cfg_mb_max']['value']) ? $sysconfig['cfg_mb_max']['value'] : '',
                'basic_img_style_wh'    => 0,
            ];

            $configArr['seo'] = [
                'seo_html_arcdir'  => !empty($sysconfig['cfg_arcdir']['value']) ? '/'.trim($sysconfig['cfg_arcdir']['value'], '/') : '',
                'seo_pseudo'  => 1,
                'seo_rewrite_format'    => 1,
                'seo_dynamic_format'    => 1,
                'seo_force_inlet'   => 0,
            ];
            $configArr['sitemap'] = [
                'sitemap_archives_num'  => !empty($sysconfig['cfg_baidunews_limit']['value']) ? $sysconfig['cfg_baidunews_limit']['value'] : 200,
                'sitemap_tags_num'  => 200,
            ];

            $smtp_server = !empty($sysconfig['cfg_smtp_server']['value']) ? $sysconfig['cfg_smtp_server']['value'] : '';
            $smtp_server_arr = parse_url($smtp_server);
            $configArr['smtp'] = [
                'smtp_server'  => !empty($smtp_server_arr['host']) ?$smtp_server_arr['host'] : $smtp_server,
                'smtp_port'  => !empty($sysconfig['cfg_smtp_port']['value']) ? $sysconfig['cfg_smtp_port']['value'] : '',
                'smtp_user'  => !empty($sysconfig['cfg_smtp_usermail']['value']) ? $sysconfig['cfg_smtp_usermail']['value'] : '',
                'smtp_pwd'  => !empty($sysconfig['cfg_smtp_password']['value']) ? $sysconfig['cfg_smtp_password']['value'] : '',
                'smtp_from_eamil'  => !empty($sysconfig['cfg_smtp_usermail']['value']) ? $sysconfig['cfg_smtp_usermail']['value'] : '',
            ];
            foreach ($configArr as $key => $val) {
                tpCache($key, $val);
            }

            $usersConfigArr = [];
            $usersConfigArr['users'] = [
                'users_reg_notallow'  => !empty($sysconfig['cfg_mb_notallow']['value']) ? $sysconfig['cfg_mb_notallow']['value'] : 'www,bbs,ftp,mail,user,users,admin,administrator,eyoucms',
            ];
            foreach ($usersConfigArr as $key => $val) {
                getUsersConfigData($key, $val);
            }
            //幻灯片转广告
            $this->dedeToEyouLogic->DedeToAd($dede_prefix);
            // 友情链接
            $this->dedeToEyouLogic->DedeToFlinktype($dede_prefix);
            // 系统变量
            $this->dedeToEyouLogic->importConfig();
            // 内置模型自定义模型
            $this->dedeToEyouLogic->DedeDiyChannelType();
            // 内置模型自定义字段
            $this->dedeToEyouLogic->DedeDiyChannelfields();
            // 转完后清理缓存
            $this->dedeToEyouLogic->clear_cache();

            $this->success('操作成功');
        }
        $this->error('操作失败');
    }

    public function handle_arctype()
    {
        @ini_set('memory_limit', '-1');
        function_exists('set_time_limit') && set_time_limit(0);

        if (IS_POST) {

            // 会员等级
            $levelList = [];
            $arcrankList = $this->DeDb('arcrank')->field('rank as level_value, membername as level_name')->where('rank','gt',0)->order('rank')->select();
            foreach ($arcrankList as $key => $value) {
                if ($key == 0) {
                    $levelList[] = [
                        'level_id'  => 1,
                        'level_name'    => trim($value['level_name']),
                        'level_value'    => $value['level_value'],
                        'is_system' => 1,
                        'down_count'    => 100,
                        'discount'  => 100,
                        'lang'  => $this->admin_lang,
                        'add_time'  => $this->times,
                        'update_time'  => $this->times,
                    ];
                } else {
                    $levelList[] = [
                        'level_name'    => trim($value['level_name']),
                        'level_value'    => $value['level_value'],
                        'is_system' => 0,
                        'down_count'    => 100,
                        'discount'  => 100,
                        'lang'  => $this->admin_lang,
                        'add_time'  => $this->times,
                        'update_time'  => $this->times,
                    ];
                }
            }
            if (!empty($levelList)) {
                $r = M('users_level')->where('level_id','gt',1)->delete();
                if ($r !== false) {
                    Db::execute('alter table '.PREFIX.'users_level AUTO_INCREMENT 1');
                    $usersLevelModel = new \app\admin\model\UsersLevel;
                    $usersLevelModel->saveAll($levelList);
                }
            }

            // 模型列表
            $channeltypeRow = Db::name('channeltype')->field('id,nid')->where(['ifsystem'=>0])->getAllWithIndex('id');

            // 网站栏目
            $admin_id = session('admin_info.admin_id');
            $admin_id = !empty($admin_id) ? intval($admin_id) : 0;
            $dirnameArr = $arctypeList = $singleList = $archivesList = [];
//            $field = 'id,reid as parent_id,topid,sortrank as sort_order,typename,typedir as dirpath,typedir as diy_dirpath,channeltype as current_channel,ispart as is_part,templist
//                ,temparticle as tempview,description as seo_description,keywords as seo_keywords,seotitle as seo_title,ishidden as is_hidden,issend as is_release,content,namerule2 as rulelist
//                ,namerule as ruleview,typenameen as englist_name,typeimg as litpic';
            $list = $this->DeDb('arctype')
                ->field('*')
                ->where(['channeltype'=>['gt', 0], 'typename'=>['NEQ', '']])->order('reid asc, id asc')->select();
            $arctypeRow = [];
            foreach ($list as $key=>$val){
                $arctype_value = [];
                $arctype_value['id'] = $val['id'];
                $arctype_value['topid'] = $val['topid'];
                $arctype_value['typename'] = $val['typename'];
                $arctype_value['templist'] = $val['templist'];
                $arctype_value['content'] = $val['content'];
                if (isset($val['reid'])){
                    $arctype_value['parent_id'] = $val['reid'];
                }
                if (isset($val['sortrank'])){
                    $arctype_value['sort_order'] = $val['sortrank'];
                }
                if (isset($val['typedir'])){
                    $arctype_value['dirpath'] = $val['typedir'];
                }
                if (isset($val['typedir'])){
                    $arctype_value['diy_dirpath'] = $val['typedir'];
                }
                if (isset($val['channeltype'])){
                    $arctype_value['current_channel'] = $val['channeltype'];
                }
                if (isset($val['ispart'])){
                    $arctype_value['is_part'] = $val['ispart'];
                }
                if (isset($val['temparticle'])){
                    $arctype_value['tempview'] = $val['temparticle'];
                }
                if (isset($val['description'])){
                    $arctype_value['seo_description'] = $val['description'];
                }
                if (isset($val['keywords'])){
                    $arctype_value['seo_keywords'] = $val['keywords'];
                }
                if (isset($val['seotitle'])){
                    $arctype_value['seo_title'] = $val['seotitle'];
                }
                if (isset($val['ishidden'])){
                    $arctype_value['is_hidden'] = $val['ishidden'];
                }
                if (isset($val['issend'])){
                    $arctype_value['is_release'] = $val['issend'];
                }
                if (isset($val['namerule2'])){
                    $arctype_value['rulelist'] = $val['namerule2'];
                }
                if (isset($val['namerule'])){
                    $arctype_value['ruleview'] = $val['namerule'];
                }
                if (isset($val['typenameen'])){
                    $arctype_value['englist_name'] = $val['typenameen'];
                }
                if (isset($val['typeimg'])){
                    $arctype_value['litpic'] = $val['typeimg'];
                }
                $arctypeRow[] = $arctype_value;
            }

            if (empty($arctypeRow)) {
                $this->success('没有找到网站栏目');
            }
            foreach ($arctypeRow as $key => $val) {
                if (empty($val['typename'])) {
                    continue;
                }
                // 栏目当前模型ID/模板文件
                $val['current_channel'] = $this->dedeToEyouLogic->DedeChannel($val['current_channel'], 'add');
                if ($val['current_channel'] == 1) { // 文章
                    $val['templist'] = 'lists_article.htm';
                    $val['tempview'] = 'view_article.htm';
                } else if ($val['current_channel'] == 2) { // 产品
                    $val['templist'] = 'lists_product.htm';
                    $val['tempview'] = 'view_product.htm';
                } else if ($val['current_channel'] == 3) { // 图集
                    $val['templist'] = 'lists_images.htm';
                    $val['tempview'] = 'view_images.htm';
                } else if ($val['current_channel'] == 4) { // 下载
                    $val['templist'] = 'lists_download.htm';
                    $val['tempview'] = 'view_download.htm';
                } else if ($val['current_channel'] == 7) { // 下载
                    $val['templist'] = 'lists_special.htm';
                    $val['tempview'] = 'view_special.htm';
                } else if ($val['current_channel'] > 100) { // 自定义模型的栏目
                    $tpl_nid = !empty($channeltypeRow[$val['current_channel']]) ? $channeltypeRow[$val['current_channel']]['nid'] : 'article';
                    $val['templist'] = 'lists_'.$tpl_nid.'.htm';
                    $val['tempview'] = 'view_'.$tpl_nid.'.htm';
                }

                if (1 <= $val['is_part']) { // 单页模型
                    $val['current_channel'] = 6;
                    $val['templist'] = 'lists_single.htm';
                    $val['tempview'] = '';
                    if (2 == $val['is_part']) {
                        $val['is_part'] = 1;
                        $val['typelink'] = $val['dirpath'];
                    } else {
                        $val['is_part'] = 0;
                        $val['typelink'] = '';
                    }

                    $tmp_content = trim($val['content'], '&nbsp;');
                    $singleList[] = [
                        'typeid'    => $val['id'],
                        'content'   => !empty($tmp_content) ? htmlspecialchars($val['content']) : '',
                        'add_time'  => $this->times,
                        'update_time'   => $this->times,
                    ];
                    $archivesList[] = [
                        'typeid'    => $val['id'],
                        'channel'   => $val['current_channel'],
                        'title' => htmlspecialchars($val['typename']),
                        'seo_description' => '',
                        'sort_order' => 100,
                        'admin_id' => $admin_id,
                        'lang'  => $this->admin_lang,
                        'add_time'  => $this->times,
                        'update_time'   => $this->times,
                    ];
                } else {
                    $val['is_part'] = 0;
                    $val['typelink'] = '';
                }

                // 目录英文名
                $dirname = '';
                if (1 == $val['is_part'] || empty($val['dirpath'])) { // 外部链接
                    $dirname = $this->dedeToEyouLogic->get_dirname($val['typename'], $dirname, $dirnameArr);
                } else {
                    $dirpathArr = explode('/', $val['dirpath']);
                    $dirname = end($dirpathArr);
                    $dirname = $this->dedeToEyouLogic->get_dirname($val['typename'], $dirname, $dirnameArr);
                }
                array_push($dirnameArr, $dirname);
                $val['dirname'] = $dirname;

                // 目录存放HTML路径
                if (empty($val['parent_id'])) { // 顶级栏目
                    $val['dirpath'] = '/'.$val['dirname'];
                    $val['diy_dirpath'] = $val['dirpath'];
                    $val['grade'] = 0;
                    $val['topid'] = 0;
                    $val['channeltype'] = $val['current_channel'];
                } else {
                    $val['dirpath'] = '';
                    $val['diy_dirpath'] = $val['dirpath'];
                    $val['grade'] = 0;
                    $val['topid'] = 0;
                    $val['channeltype'] = 0;
                }

                $val['typename'] = htmlspecialchars($val['typename']);
                $val['seo_title'] = htmlspecialchars($val['seo_title']);
                $val['seo_description'] = !empty($val['seo_description']) ? htmlspecialchars($val['seo_description']) : '';
                $val['admin_id'] = $admin_id;
                $val['lang'] = $this->admin_lang;
                $val['add_time'] = $this->times;
                $val['update_time'] = $this->times;
                $val['is_release'] = !empty($val['is_release']) ? 1 : 0;
                $val['rulelist'] = str_ireplace('{typedir}', '{栏目目录}', $val['rulelist']);
                $val['ruleview'] = str_ireplace('{typedir}', '{栏目目录}', $val['ruleview']);

                unset($val['content']);
                // 重新整理数据
                $arctypeRow[$key] = $val;
                // 分组多维数组
                !empty($val['channeltype']) && $arctypeList[$val['id']] = $val;
            }

            foreach ($arctypeRow as $key => $val) {
                // 目录存放HTML路径
                if (!empty($val['parent_id']) && empty($val['channeltype'])) { // 二、三级栏目
                    if (isset($arctypeList[$val['parent_id']])) {
                        $val['dirpath'] = $arctypeList[$val['parent_id']]['dirpath'].'/'.$val['dirname'];
                        $val['grade'] = $arctypeList[$val['parent_id']]['grade'] + 1;
                        if (1 == $val['grade']) {
                            $val['topid'] = $arctypeList[$val['parent_id']]['id'];
                        } else {
                            $val['topid'] = $arctypeList[$val['parent_id']]['topid'];
                            if (config('global.arctype_max_level') <= $val['grade']) { // 超过三级，充当二级处理
                                $val['grade'] = 1;
                                $val['parent_id'] = $val['topid'];
                                $val['dirpath'] = $arctypeList[$val['topid']]['dirpath'].'/'.$val['dirname'];
                            }
                        }
                        $val['diy_dirpath'] = $val['dirpath'];
                        $val['channeltype'] = $arctypeList[$val['parent_id']]['channeltype'];
                        // 重新整理数据
                        $arctypeRow[$key] = $val;
                        // 分组多维数组
                        $arctypeList[$val['id']] = $val;
                    }
                }
            }

            foreach ($arctypeRow as $key => $val) {
                // 目录存放HTML路径
                if (!empty($val['parent_id']) && empty($val['channeltype'])) { // 三级栏目
                    if (isset($arctypeList[$val['parent_id']])) {
                        $val['dirpath'] = $arctypeList[$val['parent_id']]['dirpath'].'/'.$val['dirname'];
                        $val['grade'] = $arctypeList[$val['parent_id']]['grade'] + 1;
                        $val['topid'] = $arctypeList[$val['parent_id']]['topid'];
                        if (config('global.arctype_max_level') <= $val['grade']) { // 超过三级，充当二级处理
                            $val['grade'] = 1;
                            $val['parent_id'] = $val['topid'];
                            $val['dirpath'] = $arctypeList[$val['topid']]['dirpath'].'/'.$val['dirname'];
                        }
                        $val['diy_dirpath'] = $val['dirpath'];
                        $val['channeltype'] = $arctypeList[$val['parent_id']]['channeltype'];
                        // 重新整理数据
                        $arctypeRow[$key] = $val;
                        // 分组多维数组
                        $arctypeList[$val['id']] = $val;
                    }
                }
            }

            if (!empty($arctypeRow)) {
                $r = M('arctype')->where(['id'=>['gt', 0]])->delete();
                $r1 = M('single_content')->where(['id'=>['gt', 0]])->delete();
                $r11 = M('archives')->where(['channel'=>['eq', 6]])->delete();
                if ($r !== false && $r1 !== false && $r11 !== false) {

                    try {
                        // 重置表ID
                        Db::execute('alter table '.PREFIX.'arctype AUTO_INCREMENT 1');
                        Db::execute('alter table '.PREFIX.'archives AUTO_INCREMENT 1');
                        Db::execute('alter table '.PREFIX.'single_content AUTO_INCREMENT 1');
                    } catch (\Exception $e) {}
                    $r2 = M('arctype')->insertAll($arctypeRow);
                    if ($r2 !== false) {
                        /*频道封面转为单页模型*/
                        if (!empty($archivesList)) {
                            $archivesModel = new \app\admin\model\Archives;
                            $rdata = $archivesModel->saveAll($archivesList);
                            if ($rdata && !empty($singleList)) {
                                foreach ($rdata as $k1 => $v1) {
                                    $aid_new = $v1->getData('aid');
                                    $typeid = $v1->getData('typeid');
                                    foreach ($singleList as $_k2 => $_v2) {
                                        if ($_v2['typeid'] == $typeid) {
                                            $singleList[$_k2]['aid'] = $aid_new;
                                            break;
                                        }
                                    }
                                }
                                M('single_content')->insertAll($singleList);
                            }
                        }
                        /*end*/

                        // 是否存在专题文档
                        $specialCount = $this->DeDb('archives')->where(['channel'=>['eq', -1]])->count();
                        if (!empty($specialCount)) {
                            $dirname_zt = $this->dedeToEyouLogic->get_dirname('默认专题', 'zhaunti', $dirnameArr);
                            $arctypeZtRow = [
                                'channeltype'   => 7,
                                'current_channel'   => 7,
                                'typename' => '默认专题',
                                'dirname'   => $dirname_zt,
                                'dirpath'   => "/{$dirname_zt}",
                                'diy_dirpath'   => "/{$dirname_zt}",
                                'templist'  => 'lists_special.htm',
                                'tempview' => 'view_special.htm',
                                'seo_description'   => '',
                                'is_hidden' => 0,
                                'sort_order'    => 100,
                                'admin_id'  => $admin_id,
                                'lang'  => $this->admin_lang,
                                'add_time'  => $this->times,
                                'update_time'  => $this->times,
                            ];
                            $ztr = M('arctype')->insert($arctypeZtRow);
                            if ($ztr !== false) {
                                if (is_dir('./template/'.TPL_THEME.'pc')) {
                                    if (!file_exists('./template/'.TPL_THEME.'pc/lists_special.htm')) {
                                        @copy(realpath('weapp/DedeToEyou/backup/lists_special.htm'), ROOT_PATH.'template/'.TPL_THEME.'pc/lists_special.htm');
                                    }
                                    if (!file_exists('./template/'.TPL_THEME.'pc/view_special.htm')) {
                                        @copy(realpath('weapp/DedeToEyou/backup/view_special.htm'), ROOT_PATH.'template/'.TPL_THEME.'pc/view_special.htm');
                                    }
                                }
                                if (is_dir('./template/'.TPL_THEME.'mobile')) {
                                    if (!file_exists('./template/'.TPL_THEME.'mobile/lists_special.htm')) {
                                        @copy(realpath('weapp/DedeToEyou/backup/lists_special.htm'), ROOT_PATH.'template/'.TPL_THEME.'mobile/lists_special.htm');
                                    }
                                    if (!file_exists('./template/'.TPL_THEME.'mobile/view_special.htm')) {
                                        @copy(realpath('weapp/DedeToEyou/backup/view_special.htm'), ROOT_PATH.'template/'.TPL_THEME.'mobile/view_special.htm');
                                    }
                                }
                            }
                        }

                        try {
                            // 重置表ID
                            Db::execute('alter table '.PREFIX.'arctype AUTO_INCREMENT 1');
                            Db::execute('alter table '.PREFIX.'archives AUTO_INCREMENT 1');
                            Db::execute('alter table '.PREFIX.'single_content AUTO_INCREMENT 1');
                        } catch (\Exception $e) {}
                        // 转完后清理缓存
                        $this->dedeToEyouLogic->clear_cache();
                        $this->success('操作成功');
                    }
                }
            }
        }
        $this->error('操作失败');
    }

    public function handle_archives()
    {
        @ini_set('memory_limit', '-1');
        function_exists('set_time_limit') && set_time_limit(0);

        $channel = input('param.channel/s');
        $typeid      = input("param.typeid/d", 0);
        if (IS_POST) {
            $achievepage = input("param.achieve/d", 0); // 已完成文档数
            $data = $this->dedeToEyouLogic->handelBuildArticle($typeid, $channel, $achievepage);

            // 删除栏目里没有的频道模型对应的文档
            try {
                if ($data[1]['achievepage'] >= $data[1]['allpagetotal']) {
                    $allow_release_channel = [];
                    $arctypeRow = Db::name('arctype')->field('channeltype,current_channel')->where(['channeltype|current_channel'=>['NOT IN', [8,51]]])->select();
                    foreach ($arctypeRow as $key => $val) {
                        $allow_release_channel[] = $val['channeltype'];
                        $allow_release_channel[] = $val['current_channel'];
                    }
                    $allow_release_channel = array_unique($allow_release_channel);
                    if (!empty($allow_release_channel)) {
                        Db::name('archives')->where(['channel'=>['NOT IN', $allow_release_channel]])->update([
                            'is_del'    => 1,
                            'update_time'   => getTime(),
                        ]);
                    }
                }
            } catch (\Exception $e) {}
            
            $this->success($data[0], null, $data[1]);
        }

        // 是否优先转换网站栏目
        $arctypeRow = $this->DeDb('arctype')->field('id')->where(['channeltype'=>['gt', 0]])->order('id asc')->find();
        if (!empty($arctypeRow)) {
            $count = M('arctype')->where('id', $arctypeRow['id'])->count();
            if (empty($count)) {
                $this->error('请先转换网站栏目', null, [], 8);
            }
        }

        $this->assign('typeid', $typeid);
        $this->assign('channel', $channel);

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

    public function handle_tag()
    {
        @ini_set('memory_limit', '-1');
        function_exists('set_time_limit') && set_time_limit(0);

        $weappData = M('weapp')->where('code','DedeToEyou')->field('data')->find();
        $weappData = json_decode($weappData['data'], true);
        if (isset($weappData['dede_prefix'])) {
            $dede_prefix = !empty($weappData['dede_prefix']) ? $weappData['dede_prefix'] : '';
            $r = M('tagindex')->where('id','>',0)->delete();
            $r2 = M('taglist')->where('tid','>',0)->delete();
            if ($r !== false && $r2 !== false) {
                Db::execute("INSERT INTO ".PREFIX."tagindex (id,tag,typeid,seo_description,count,total,weekcc,monthcc,weekup,monthup,add_time,lang) SELECT id,tag,typeid,'' as seo_description,count,total,weekcc,monthcc,weekup,monthup,addtime as add_time,'{$this->admin_lang}' as lang FROM ".$dede_prefix."tagindex");
                Db::execute("INSERT INTO ".PREFIX."taglist (tid,aid,arcrank,typeid,tag,lang,add_time) SELECT tid,aid,arcrank,typeid,tag,'{$this->admin_lang}' as lang,'{$this->times}' as add_time FROM ".$dede_prefix."taglist");
                \think\Cache::clear('tagindex');
                \think\Cache::clear('taglist');
            }
            // 转完后清理缓存
            $this->dedeToEyouLogic->clear_cache();
            $this->success('操作成功');
        }
        $this->error('操作失败');
    }

    public function handle_all()
    {
        @ini_set('memory_limit', '-1');
        function_exists('set_time_limit') && set_time_limit(0);

        $channel = input('param.channel/s');
        if (IS_POST) {
            $this->handle_del('all', false);

            $channels = [];
            if (!empty($channel)) {
                $channels = explode(',', $channel);
            }
            $archivesData = $this->dedeToEyouLogic->getArticleData(0, $channels);
            $archivesTotal  = !empty($archivesData['pagetotal']) ? intval($archivesData['pagetotal']) : 0;
            $allpagetotal = 1 + 1 + 1 + $archivesTotal + 1;

            $this->success('', null, ["achievepage" => 1, "articlepagetotal" => $archivesTotal, "allpagetotal" => $allpagetotal]);
        }

        $this->assign('channel', $channel);
        return $this->fetch('handle_all');
    }

    /**
     * 清空全部缓存和数据表缓存文件生成
     */
    public function clear_cache()
    {
        $this->dedeToEyouLogic->clear_cache();
        $this->success('清除缓存成功');
    }
}