<?php
/**
 * 账号系统入口文件
 */

use think\facade\Session;

error_reporting(E_ERROR);
date_default_timezone_set("Asia/Shanghai");
defined('BASE_ROOT') or define('BASE_ROOT', str_replace('/public/php', '', str_replace('\\', '/', realpath(dirname(__FILE__) . '/')) . "/"));
defined('SITE_PATH') or define('SITE_PATH', BASE_ROOT);
defined('PUBLIC_PATH') or define('PUBLIC_PATH', SITE_PATH . 'public/');
$processor = empty($GLOBALS['processor_param']) ? $_GET['processor'] : $GLOBALS['processor_param'];
$prefix = $processor['prefix'];
require_once 'yb.config.php';
defined('SQL_TABLE_PREFIX') or define('SQL_TABLE_PREFIX', $prefix . $ybConfig['table_prefix'] . '_');
//处理招商系统和应用交互
$do = empty($processor['do']) ? '' : $processor['do'];
if ($do == 'init_staff') {
    Session::delete('admin' . $ybConfig['session_key']);
    $mch_id = $processor['mch_id'];
    $account = $processor['account'];
    $admin_type = $processor['admin_type'] ?? 'admin';
    $is_custom_config = isset($processor['is_custom_config']) ? $processor['is_custom_config'] : 0;
    $app_equity = isset($processor['app_equity']) ? $processor['app_equity'] : [];

    $admin = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin')->where(['mch_id' => $mch_id, 'shop_id' => 0, 'account' => $account])->find();
    if (empty($admin)) {
        $admin = [
            'account' => $account,
            'password' => password_hash('123456', PASSWORD_DEFAULT),
            'user_name' => $account,
            'avatar' => '',
            'admin_type' => $admin_type,
            'shop_id' => 0,
            'mch_id' => $mch_id,
            'create_time' => time(),
        ];
        $admin_id = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin')->insertGetId($admin);
        $admin = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin')->where(['id' => $admin_id])->find();
    } else {
        $admin_id = $admin['id'];
        //处理管理员老数据
        $platform_admin = \think\facade\Db::name('sys_admin')->order('id asc')->find();
        if ($platform_admin['account'] == $admin['account'] && $admin['admin_type'] == 'admin') {
            \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin')->where(['id' => $admin_id])->update(['admin_type' => 'super']);
            $admin['admin_type'] = 'super';
        }
        if ($admin['admin_type'] == 'staff') {
            \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin')->where(['id' => $admin_id])->update(['admin_type' => 'admin']);
            $admin['admin_type'] = 'admin';
        }
    }
    $GLOBALS['processor_param']['admin_id'] = $admin_id;
    //写入默认权限组
    $menu_ids = isset($processor['menu_ids']) ? $processor['menu_ids'] : '';
    if (empty($menu_ids)) {
        $sys_menus = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_menus')->column('id');
        $menu_ids = implode(',', $sys_menus);
    } else {
        $sys_menus = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_menus')->whereIn('id', $menu_ids)->column('id');
        $menu_ids = $menu_ids . ',' . implode(',', $sys_menus);
    }
    //权限组id是否存在
    $info = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group')->where(["pid" => 0, "mch_id" => $mch_id, "shop_id" => 0, "is_default" => 1])->find();
    if (empty($info)) {
        $admin_group_id = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group')->insertGetId(["pid" => 0, "name" => '管理员组', "status" => 1,
            "menu_ids" => $menu_ids, "create_time" => time(), "mch_id" => $mch_id, "shop_id" => 0, "is_default" => 1]);
        $default_group_id = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group')->insertGetId(["pid" => $admin_group_id, "name" => '默认权限组', "status" => 1,
            "menu_ids" => $menu_ids, "create_time" => time(), "mch_id" => $mch_id, "shop_id" => 0, "is_default" => 0]);
    } else {
        $group_ids = [];
        //把之前的多个默认权限组  修改权限组
        \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group')->where(["id" => $info['id']])->update(['menu_ids' => $menu_ids]);
        $admin_group_id = $info['id'];
        $group_ids[] = $admin_group_id;
        $default_info = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group')
            ->where(["pid" => $admin_group_id, "mch_id" => $mch_id, "shop_id" => 0, "is_default" => 1])
            ->order('id asc')
            ->find();
        $default_group_id = $default_info['id'];
        if ($default_info['menu_ids'] != $menu_ids) {
            \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group')->where(["id" => $default_info['id']])->update(['menu_ids' => $menu_ids]);
            $group_ids[] = $default_group_id;
            //更新其它权限组
            $admin_group_arr = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group')->where(["pid" => 0, "mch_id" => $mch_id, "shop_id" => 0])->whereNotIn('id', $group_ids)->select()->toArray();
            $default_menu_ids_arr = explode(',', $menu_ids);
            if ($default_menu_ids_arr) {
                $default_menu_ids_arr = array_unique($default_menu_ids_arr);
                foreach ($admin_group_arr as $item) {
                    $menu_ids_arr = explode(',', $item['menu_ids']);
                    $menu_ids_arr = array_unique($menu_ids_arr);
                    $intersect_arr = array_intersect($menu_ids_arr, $default_menu_ids_arr);
                    if ($intersect_arr) {
                        \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group')->where(["id" => $default_info['id']])->update(['menu_ids' => implode(',', $intersect_arr)]);
                    } else {
                        \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group')->where(["id" => $default_info['id']])->update(['menu_ids' => '']);
                    }
                }
            }
        }
    }
    //分配权限
    $relation_info = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group_relation')->where(["mch_id" => $mch_id, "admin_id" => $admin_id])->where('group_id', '<>', 0)->find();
    if (empty($relation_info)) {
        $group_id = $admin['admin_type'] == 'admin' ? $admin_group_id : $default_group_id;
        \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group_relation')->insertGetId(["group_id" => $group_id, "admin_id" => $admin_id,
            "create_time" => time(), "mch_id" => $mch_id, "shop_id" => 0]);
    }
    //登录
    Session::set('admin' . $ybConfig['session_key'], $admin);
    // 确保 Session 数据被保存，解决重定向后 Session 丢失问题
    Session::save();
    //初始化应用权益
    if (!empty($app_equity)) {
        $sys_config_obj = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_config')->where(["mch_id" => $mch_id, 'config_key' => 'application_equity'])->find();
        if (empty($sys_config_obj)) {
            $sys_config['config_key'] = 'application_equity';
            $sys_config['config_value'] = json_encode($app_equity, true);
            $sys_config['description'] = '应用权益';
            $sys_config['mch_id'] = $mch_id;
            $sys_config['shop_id'] = 0;
            $sys_config['create_time'] = time();
            \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_config')->insert($sys_config);
        } else {
            $config_value = !empty($sys_config_obj['config_value']) ? json_decode($sys_config_obj['config_value'], true) : [];
            $config_value = array_merge($config_value, $app_equity);
            $sys_config['config_value'] = !empty($config_value) ? json_encode($config_value, true) : '';
            $sys_config['update_time'] = time();
            \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_config')->where(["id" => $sys_config_obj['id']])->update($sys_config);
        }
    }

    \think\facade\Log::write('调用成功:' . json_encode($processor));
} elseif ($do == 'sys_module_tree') {
    function getMenuChildrenTree($data, $pid)
    {
        $tree = [];
        foreach ($data as $row) {
            if ($row['pid'] == $pid) {
                $children = getMenuChildrenTree($data, $row['id']);
                $row['children'] = $children;
                $tree[] = $row;
            }
        }
        return $tree;

    }

    $list = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_menus')
        ->where(['is_menu' => 1, 'mch_id' => 0])
        ->field('id,pid,name')
        ->order('sort asc,id asc')
        ->select()
        ->toArray();
    //返回树形结构
    $list_new = [];
    foreach ($list as $item) {
        $data_obj = [];
        $data_obj['value'] = $item['id'] . '';
        $data_obj['label'] = $item['name'];
        $data_obj['pid'] = $item['pid'];
        $data_obj['id'] = $item['id'];
        $list_new[] = $data_obj;
    }
    $tree = getMenuChildrenTree($list_new, 0);
    $result_data['tree'] = $tree;
    $result_data['list'] = $list;
    $GLOBALS['processor_param']['result_data'] = $result_data;
} elseif ($do == 'sys_module_ids') {
    $menu_ids = $processor['menu_ids'];
    $list = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_menus')
        ->where(['is_menu' => 1, 'mch_id' => 0])
        ->field('id,pid')
        ->order('sort asc,id asc')
        ->select()
        ->toArray();

    if (!empty($menu_ids)) {
        function getMenuChildrenIds($data, $pid)
        {
            $children_ids[] = $pid;
            foreach ($data as $row) {
                if ($row['pid'] == $pid) {
                    $children_ids[] = $row['id'];
                    $children_ids_arr = getMenuChildrenIds($data, $row['id']);
                    if (!empty($children_ids_arr)) {
                        $children_ids = array_merge($children_ids, $children_ids_arr);
                    }
                }
            }
            return array_unique($children_ids);
        }

        $menu_ids_arr = [];
        foreach ($menu_ids as $item) {
            $children_ids_arr = getMenuChildrenIds($list, $item);
            if (!empty($children_ids_arr)) {
                $menu_ids_arr = array_merge($menu_ids_arr, $children_ids_arr);
            }
        }
        $menu_ids_arr = array_unique($menu_ids_arr);
        //取数据value值做为新的数组加排序
        $menu_ids_arr = array_values($menu_ids_arr);
    } else {
        $menu_ids_arr = array_merge($menu_ids, array_column($list, 'id'));
    }
    $GLOBALS['processor_param']['result_data'] = $menu_ids_arr;
} elseif ($do == 'update_sys_user_role') {
    $mch_ids = $processor['mch_ids'];
    $is_custom_config = isset($processor['is_custom_config']) ? $processor['is_custom_config'] : -1;
    //写入默认权限组
    $menu_ids = isset($processor['menu_ids']) ? $processor['menu_ids'] : '';
    $sys_menus = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_menus')->whereIn('pid', $menu_ids)->column('id');
    $menu_ids = $menu_ids . ',' . implode(',', $sys_menus);
    $default_menu_ids_arr = explode(',', $menu_ids);
    $default_menu_ids_arr = array_unique($default_menu_ids_arr);
    foreach ($mch_ids as $mch_id) {
        //权限组id是否存在
        $info = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group')->where(["pid" => 0, "mch_id" => $mch_id, "shop_id" => 0, "is_default" => 1])->find();
        if (empty($info)) {
            $admin_group_id = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group')->insertGetId(["pid" => 0, "name" => '管理员组', "status" => 1,
                "menu_ids" => $menu_ids, "create_time" => time(), "mch_id" => $mch_id, "shop_id" => 0, "is_default" => 1]);
            $default_group_id = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group')->insertGetId(["pid" => $admin_group_id, "name" => '默认权限组', "status" => 1,
                "menu_ids" => $menu_ids, "create_time" => time(), "mch_id" => $mch_id, "shop_id" => 0, "is_default" => 0]);
        } else {
            $group_ids = [];
            //把之前的多个默认权限组  修改权限组
            \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group')->where(["id" => $info['id']])->update(['menu_ids' => $menu_ids]);
            $admin_group_id = $info['id'];
            $group_ids[] = $admin_group_id;
            $default_info = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group')
                ->where(["pid" => $admin_group_id, "mch_id" => $mch_id, "shop_id" => 0, "is_default" => 0])
                ->order('id asc')
                ->find();
            if ($default_info['menu_ids'] != $menu_ids) {
                \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group')->where(["id" => $default_info['id']])->update(['menu_ids' => $menu_ids]);
                $default_group_id = $default_info['id'];
                $group_ids[] = $default_group_id;
                if ($menu_ids) {
                    //更新其它权限组
                    $admin_group_arr = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group')->where(["mch_id" => $mch_id, "shop_id" => 0])->whereNotIn('id', $group_ids)->select()->toArray();
                    foreach ($admin_group_arr as $item) {
                        $menu_ids_arr = explode(',', $item['menu_ids']);
                        $menu_ids_arr = array_unique($menu_ids_arr);
                        $intersect_arr = array_intersect($menu_ids_arr, $default_menu_ids_arr);
                        if ($intersect_arr) {
                            \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group')->where(["id" => $item['id']])->update(['menu_ids' => implode(',', $intersect_arr)]);
                        } else {
                            \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_admin_group')->where(["id" => $item['id']])->update(['menu_ids' => '']);
                        }
                    }
                }
            }
        }

        $sys_config_obj = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_config')->where(["mch_id" => $mch_id, 'config_key' => 'application_equity'])->find();
        if (empty($sys_config_obj)) {
            $app_equity['is_custom_config'] = $is_custom_config;
            $sys_config['config_key'] = 'application_equity';
            $sys_config['config_value'] = json_encode($app_equity, true);
            $sys_config['description'] = '应用权益';
            $sys_config['mch_id'] = $mch_id;
            $sys_config['shop_id'] = 0;
            $sys_config['create_time'] = time();
            \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_config')->insert($sys_config);
        } else {
            $config_value = !empty($sys_config_obj['config_value']) ? json_decode($sys_config_obj['config_value'], true) : [];
            $app_equity['is_custom_config'] = $is_custom_config;
            $config_value = array_merge($config_value, $app_equity);
            $sys_config['config_value'] = !empty($config_value) ? json_encode($config_value, true) : '';
            $sys_config['update_time'] = time();
            \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_config')->where(["id" => $sys_config_obj['id']])->update($sys_config);
        }
    }
} elseif ($do == 'yb_version') {
    require_once PUBLIC_PATH . '/php/yb.version.php';
    $result_data['yb_table_prefix'] = $ybConfig['table_prefix'];
    $result_data['session_key'] = $ybConfig['session_key'];
    $result_data['url'] = $processor['domain'] . 'addons/' . APPLICATION_FLAG . '/index.php';
    $GLOBALS['processor_param']['result_data'] = $result_data;
} elseif ($do == 'install') {
    require_once 'yb.sql.php';
    $namespace_file_name = $ybConfig['namespace_file_name'];
    $site_path = SITE_PATH . 'addons/' . $ybConfig['application_flag'] . '/';
    install($site_path, $namespace_file_name);
    //复制.env install.lock文件 到$site_path目录
    copy(SITE_PATH . '.env', $site_path . '.env');
    copy(SITE_PATH . 'install.lock', $site_path . 'install.lock');
} elseif ($do == 'update') {
    require_once 'yb.sql.php';
    $namespace_file_name = $ybConfig['namespace_file_name'];
    $site_path = SITE_PATH . 'addons/' . $ybConfig['application_flag'] . '/';
    update($site_path, $namespace_file_name);
} elseif ($do == 'init_sys_site_base') {
    //初始化站点设置 - 迁移到sys_config
    $mch_id = $processor['mch_id'];
    $name = isset($processor['name']) ? $processor['name'] : '';
    $icon = isset($processor['icon']) ? $processor['icon'] : '';
    $copyright = isset($processor['copyright']) ? $processor['copyright'] : '';
    $sys_config = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_config')->where(['mch_id' => $mch_id, 'config_key' => 'site_config'])->find();
    if (empty($sys_config)) {
        $sys_config_default = \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_config')->where(['mch_id' => 0, 'config_key' => 'site_config'])->find();
        $config_value = !empty($sys_config_default['config_value']) ? json_decode($sys_config_default['config_value'], true) : [];
        if ($icon) {
            $config_value['icon'] = $icon;
        }
        if ($name) {
            $config_value['site_name'] = $name;
        }
        if ($copyright) {
            $config_value['copyright'] = $copyright;
        }
        \think\facade\Db::table(SQL_TABLE_PREFIX . 'sys_config')->insert([
            'config_key' => 'site_config',
            'config_value' => json_encode($config_value, JSON_UNESCAPED_UNICODE),
            'description' => '站点设置',
            'mch_id' => $mch_id,
            'shop_id' => 0,
            'create_time' => time(),
        ]);
    }
} elseif ($do == 'delete_addons') {
    /*$mch_id = $processor['mch_id'];
    \think\facade\Db::table(SQL_TABLE_PREFIX . 'application')->where(['mch_id' => $mch_id])->update(['delete_time' => time()]);*/
} elseif ($do == 'edit_addons') {
    /*$mch_id = $processor['mch_id'];
    $name = $processor['name'];
    $logo = $processor['icon'];
    $application['name'] = $name;
    $application['logo'] = $logo;
    $application['update_time'] = time();
    \think\facade\Db::table(SQL_TABLE_PREFIX . 'application')->where(['mch_id' => $mch_id])->update($application);*/
}
