<?php
/**
 * +------------------------------------------------------------
 * | 控制器基类 (common/controller/Init.php)
 * +------------------------------------------------------------
 * | @author: zhx (10630650@qq.com)
 * | @create_time: 2018-03-10 11:34:47
 * +------------------------------------------------------------
 * | @copyright: CIM信息聚合系统 (https://cimxx.com)
 * +------------------------------------------------------------
 * | @last_modified_by: zhx
 * | @last_modified_time: 2018-03-10 11:34:47
 * +------------------------------------------------------------
 * | @todo:
 * +------------------------------------------------------------
 */

namespace app\common\controller;

use think\Controller;
use think\facade\Env;

header('X-Powered-By:CIM');

class Init extends Controller
{
    public static $sys;
    public static $cim;
    public static $admin = [];
    public static $user = ['id' => 0, 'group_id' => 0, 'name' => '', 'credit' => 0, 'money' => 0];

    protected function initialize()
    {
        self::$sys = [
            'referer' => (input('server.HTTP_REFERER') ? input('server.HTTP_REFERER') : ''),
            'module' => strtolower($this->request->module()),
            'controller' => strtolower($this->request->controller()),
            'action' => strtolower($this->request->action()),
            'ip' => $this->request->ip(),
            'datetime' => date('Y-m-d H:i:s', time()),
            'is_mobile' => $this->request->isMobile(),
            'method' => strtolower($this->request->method()),
        ];
        $this->assign('sys', self::$sys);
        $this->assign('cim', self::$cim = load_setting('cim'));
        if (isset(self::$cim['mobile'])) {
            if (self::$cim['mobile'] == 2) {
                if (in_array(self::$sys['controller'], ['index']) && in_array(self::$sys['module'], ['index'])) {
                    if (self::$sys['is_mobile'] && !empty(self::$cim['mobile_domain'])) {
                        $url = self::$cim['mobile_domain'];
                        if (input('?param.key')) $url .= '/' . input('param.key');
                        if (input('?param.id')) $url .= '/' . input('param.id');
                        die(header('Location:' . $url));
                    }
                }
            }
        }
        if (isset(self::$cim['close']) && self::$cim['close'] == 0 && self::$sys['controller'] != 'admin') {
            if (self::$sys['module'] != 'admin') return $this->error(self::$cim['close_tips']);
        }
        $this->allow_source();
        $this->check_token();
        $this->check_role();
        $this->assign('param', input('param.'));
    }

    /**
     * 允许跨域
     */
    function allow_source()
    {
        $origin = $_SERVER['HTTP_ORIGIN'] ?? '';
        $allow_origin = config('')['source'];
        $referer = $_SERVER['HTTP_REFERER'] ?? '';
        if (in_array($origin, $allow_origin)) {
            header('Access-Control-Allow-Origin:' . $origin);
        }
        if (self::$sys['controller'] == 'api') {
            if (empty($referer)) die('Access denied.');
            $referer = parse_url($referer);
            $host = [$_SERVER['HTTP_HOST']];
            foreach ($allow_origin as $k => $v) {
                $v = parse_url($v);
                if ($v['host'] ?? '') $host[] = $v['host'];
            }
            if (!in_array($referer['host'], $host)) die('Access denied.');
        }
        if (in_array(self::$sys['controller'], ['admin', 'addons']) || self::$sys['module'] == 'admin' || in_array(self::$sys['module'] . self::$sys['controller'] . self::$sys['action'], ['userapilogout', 'userapilogin', 'userapisend_sms', 'userapiregister', 'indexapimanage', 'messageapimessage', 'userapicheck_name_exists', 'filesapiupload', 'indexapiuser_data', 'wechatindexmenu', 'wechatindexreply', 'wechatindexupload_media', 'wechatindexmaterial', 'cimupgrade.clientcheck'])) {
            header("Access-Control-Allow-Credentials: true");
        }
        header('content-type:application:json;charset=utf8');
        header('Access-Control-Allow-Methods:POST');
        header('Access-Control-Allow-Methods:GET');
        header('Access-Control-Allow-Methods:REQUEST');
        header('Access-Control-Allow-Headers:x-requested-with,content-type,token,key,x-file-name');
        if (self::$sys['method'] == 'options') die(json_encode(['code' => 1, 'msg' => '']));
    }

    /**
     * 检测权限
     */
    private function check_role()
    {
        $roles = ['user', 'admin'];
        foreach ($roles as $v) {
            if (!empty(session($v))) {
                self::$$v = session($v);
            }
            $this->assign($v, self::$$v);
        }
        if (!in_array(self::$sys['controller'], $roles)) return;
        $_controller = self::$sys['controller'];
        if (empty(session($_controller))) {
            if ($_controller == 'admin') die(json_encode(['code' => 1000, 'msg' => '请登录...']));
            $this->redirect($_controller . '/index/login');
        }
        //检测角色权限
        if (session($_controller . '.role_id')) {
            $role_power = array();
            if (session($_controller . '.power')) $role_power = explode(',', session($_controller . '.power'));
            $action_key = self::$sys['module'] . '_' . $_controller . '_' . self::$sys['action'];
            if (!in_array($action_key, $role_power)) die(json_encode(['code' => 1001, 'msg' => '您没有此项管理权限']));
        }
    }

    public function _404()
    {
        return response($this->fetch(config('app.http_exception_template.404')), 404);
    }

    /**
     * 初始化分页器
     */
    protected function init_pager($count, $listRows = 20, $parameter = [])
    {
        include_once(Env::get('extend_path') . 'Pager.php');
        $_obj = new \Pager($count, $listRows, $parameter);
        $pager = $_obj->result();
        $this->assign('count', $count);
        $this->assign('pager', $pager);
        return $pager;
    }

    /**
     * 导入excel文件
     * @param $path
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    protected function load_excel($path)
    {
        if (!is_file($path)) return [];
        include(Env::get('extend_path') . 'PHPExcel.php');
        $obj = new \PHPExcel();
        $reader = new \PHPExcel_Reader_Excel2007();
        if (!$reader->canRead($path)) {
            $reader = new \PHPExcel_Reader_Excel5();
            if (!$reader->canRead($path)) {
                $this->error('未找到导入文件');
            }
        }
        $obj = $reader->load($path);
        //读取excel文件中的第一个工作表
        $current_sheet = $obj->getSheet(0);
        //取得最大列号
        $all_column = $current_sheet->getHighestColumn();
        //取得总行数
        $all_row = $current_sheet->getHighestRow();
        $all_value = array();
        //从第二行开始输出，因为excel表中第一行为列名
        for ($current_row = 2; $current_row <= $all_row; $current_row++) {
            //从第A列开始输出
            for ($current_column = 'A'; $current_column <= $all_column; $current_column++) {
                $val = (string)$current_sheet->getCell($current_column . $current_row)->getValue();
                $all_value[$current_row][$current_column] = $val;
            }
        }
        return $all_value;
    }

    /**
     * 导出EXCEL文件
     * @param $filename
     * @param $head_arr
     * @param $data
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    protected function save_excel($filename, $head_arr, $data)
    {
        $filename .= '.xls';
        include(Env::get('extend_path') . 'PHPExcel.php');
        //创建PHPExcel对象，注意，不能少了\
        $obj = new \PHPExcel();
        $objProps = $obj->getProperties();
        //设置表头
        $key = ord("A");

        foreach ($head_arr as $v) {
            $colum = chr($key);
            $obj->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
            $obj->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
            $key += 1;
        }

        $column = 2;
        $objActSheet = $obj->getActiveSheet();

        foreach ($data as $key => $rows) { //行写入
            $span = ord("A");
            foreach ($rows as $keyName => $value) {// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j . $column, $value);
                $span++;
            }
            $column++;
        }

        $filename = iconv("utf-8", "gb2312", $filename);
        //重命名表
        //$obj->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $obj->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$filename\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }

    /**
     * 筛选
     * @param array $ops
     * @return array|void
     */
    protected function init_filters($ops = [])
    {
        if (empty($ops)) return;
        $rs = [];
        $url = self::$sys['module'] . '/' . self::$sys['controller'] . '/' . self::$sys['action'];
        $params = input('param.');
        foreach ($ops as $val) {
            list($key, $name, $param) = $val;
            $option = [
                'all' => [
                    'url' => url($url, array_merge(input('param.'), [$key => '', 'page' => ''])),
                    'name' => '全部',
                    'on' => (!isset($params[$key]) || $params[$key] == '' ? 1 : 0)
                ]
            ];
            foreach ($param as $k => $v) {
                //if (is_array($v)) $v = $v['name'];
                $option[$k] = [
                    'url' => url($url, array_merge(input('param.'), [$key => $k, 'page' => ''])),
                    'name' => is_array($v) ? $v['name'] : $v,
                    'on' => (isset($params[$key]) && $params[$key] == $k ? 1 : 0)
                ];
                if (is_array($v)) $option[$k] = array_merge($option[$k], $v);
                if ($option[$k]['on'] == 1) $rs['selected'][$key] = ['name' => $name, 'value' => is_array($v) ? $v['name'] : $v, 'url' => $option['all']['url']];
            }
            $rs[$key] = ['name' => $name, 'value' => empty($rs['selected'][$key]['value']) ? $name : $rs['selected'][$key]['value'], 'option' => $option];
        }
        return $rs;
    }

    /**
     * 排序
     * @param array $ops
     * @return array|void
     */
    protected function init_orders($ops = [])
    {
        if (empty($ops)) return;
        $params = input('param.');
        $url = self::$sys['module'] . '/' . self::$sys['controller'] . '/' . self::$sys['action'];
        $option = [
            'default' => [
                'url' => url($url, array_merge($params, ['order' => ''])),
                'name' => '默认排序',
                'on' => (!isset($params['order']) || $params['order'] == '' ? 1 : 0)
            ]
        ];
        foreach ($ops as $k => $v) {
            $option[$k] = [
                'url' => url($url, array_merge($params, ['order' => $k])),
                'name' => $v,
                'on' => (isset($params['order']) && $params['order'] == $k ? 1 : 0)
            ];
            if ($option[$k]['on']) $value = $option[$k]['name'];
        }
        $option['select'] = ['name' => empty($value) ? $option['default']['name'] : $value];
        return $option;
    }

    /**
     * 空方法
     * @param $name
     */
    public function _empty($name)
    {
        if (in_array($name, ['add', 'edit'])) {
            return $this->form(input('param.id'), $name);
        }
    }

    public function check_token()
    {
        $param = input('param.');
        if (!empty($param['attr'])) {
            if (is_string($param['attr'])) $param['attr'] = json_decode($param['attr'], 1);
            if (!empty($param['attr']['token'])) {
                $token = $param['attr']['token'];
                if (!empty(cache($token))) {
                    session('user', cache($token));
                    self::$user = cache($token);
                    //移动端管理员管理信息未登陆
                    if (!empty(input('server.Access-Control-Allow-Credentials')) && cache($token)['admin'] == 1 && empty(session('admin'))) action('user/api/login', [3]);
                } else {
                    die(json_encode(['code' => 1000, 'msg' => '请登录']));
                }
            }
        }
    }

    /**
     * 重写错误方法
     */
    public function error($msg = '', $url = NULL, $data = '', $wait = 3, array $header = [], $code = 0)
    {
        if (is_array($msg)) {
            $url = $msg['url'] ?? NULL;
            $data = $msg['data'] ?? '';
            $wait = $msg['wait'] ?? 3;
            $header = $msg['header'] ?? [];
            $errcode = $msg['errcode'] ?? 0;
            $msg = $msg['msg'] ?? '';
        }
        if (file_exists(load_template_path() . 'message' . DIRECTORY_SEPARATOR . 'alert' . DIRECTORY_SEPARATOR . $code . '.html')) {
            config('app.dispatch_error_tmpl', load_template_path() . 'message' . DIRECTORY_SEPARATOR . 'alert' . DIRECTORY_SEPARATOR . $code . '.html');
        }
        parent::error($msg, $url, $data, $wait, $header);
    }

}
