<?php
/**
 * +------------------------------------------------------------
 * | 管理中心 index/controller/Admin.php
 * +------------------------------------------------------------
 * | @author: zhx (10630650@qq.com)
 * | @create_time: 2018-03-09 11:32:24
 * +------------------------------------------------------------
 * | @copyright: CIM信息聚合系统 (https://cimxx.com)
 * +------------------------------------------------------------
 * | @last_modified_by: zhx
 * | @last_modified_time: 2018-03-09 11:32:24
 * +------------------------------------------------------------
 * | @todo:
 * +------------------------------------------------------------
 */

namespace app\cim\controller;

use app\common\controller\Init;
use app\index\model\Area;
use app\index\model\Words;
use think\facade\Cache;

class Admin extends Init
{

    /**
     * 模块设置
     */
    public function setting($id = '')
    {
        if (!$id) $id = self::$sys['module'];
        if (request()->isPost()) {
            $data = input('post.');
            if (!empty($data)) {
                $where = ['id' => $id];
                $data = ['value' => json_encode($data), 'update_time' => time()];
                if (db('setting')->where($where)->count()) {
                    db('setting')->where($where)->update($data);
                } else {
                    $data['id'] = $id;
                    db('setting')->insert($data);
                }
                load_setting($id, 1);
            }
            return json(['code' => 1, 'msg' => '模块设置已更新']);
        } else {
            $data = load_setting($id);
            return json(['code' => 1, 'data' => $data]);
        }
    }


    /**
     * 缓存
     */
    public function cache($id = [], $tag = [], $remove = '')
    {
        if (!empty($id)) {
            if (is_string($id)) $id = [$id];
            if (in_array('temp', $id)) clear_file(\Env::get('runtime_path') . 'temp/');
            //if (in_array('log', $id)) clear_file(\Env::get('runtime_path') . 'log/');
            if (in_array('columns', $id)) {
                \load_columns(0, 1);
                Cache::clear('columns');
            }
            action('user/Api/log', ['清理缓存', join(',', $id)]);
            return json(['code' => 1, 'msg' => '所选缓存已刷新']);
        }
        if (!empty($tag)) {
            foreach ($tag as $k => $v) Cache::clear($v);
        }
        if ($remove) {
            action('user/Api/log', ['清理缓存', '全部清除']);
            clear_file(\Env::get('runtime_path') . 'temp/');
            //clear_file(\Env::get('runtime_path') . 'log/');
            clear_file(\Env::get('runtime_path') . 'cache/');
            Cache::clear();
            return json(['code' => 1, 'msg' => '全部缓存项已清理。']);
        }
    }

    /**
     * 词库
     */
    public function words($keyword = '', $limit = 20, $column_id = '')
    {
        if (input('param.cache')) {
            load_words(1);
            action('user/Api/log', ['清理词库缓存']);
            return json(['code' => 1, 'msg' => '词库缓存已刷新']);
        }
        $where = [];
        if ($keyword) {
            $where [] = ['name', 'like', '%' . $keyword . '%'];
        }
        if ($column_id !== '') $where[] = ['column_id', '=', $column_id];
        $data = Words::where($where)->paginate($limit)->toArray();
        return json(['code' => 1, 'data' => $data]);
    }

    /**
     * 返回配置项
     */
    function configs()
    {
        return json(['code' => 1, 'data' => [
            'words' => config('app.words'),
            'cim' => config('')['cim']
        ]]);
    }

    /**
     * 词库表单
     * @return \think\response\Json
     */
    function words_form($id = 0)
    {
        if (request()->isPost()) {
            $data = input('post.');
            $validate = validate('Words');
            if (!$validate->check($data)) return json(['code' => 85001, 'msg' => $validate->getError()]);
            $_model = new Words();
            if ($id) {
                $_model->allowField(true)->save($data, ['id' => $id]);
            } else {
                action('user/Api/log', ['添加关键词']);
                $_model->data($data)->allowField(true)->save();
            }
            load_words(1);
            return json(['code' => 1, 'msg' => '词库已更新']);
        }
        if ($id) {
            $rs = Words::where('id', '=', $id)->find();
            return json(['code' => 1, 'data' => $rs]);
        }
    }

    /**
     * 更新词库状态
     * @param array $name
     * @param int $status
     */
    public function words_status($id = [], $status = 0)
    {
        if (!empty($id)) {
            db('words')->where('id', 'in', (array)$id)->update(['status' => $status]);
            load_words(1);
            return json(['code' => 1, 'msg' => '更新成功']);
        }
        return json(['code' => 85002, 'msg' => '参数错误']);
    }

    /**
     * 批量设置词行为
     * @param array $id
     * @param array $action
     * @param int $set 0：替换，1：增加，2：减少
     */
    public function words_action($id = [], $fields = [], $set = 0)
    {
        if (!empty($id)) {
            if ($set == 0) {
                db('words')->where('id', 'in', (array)$id)->setField('fields', join(',', $fields));
            } else {
                $words = model('app\index\model\Words')->where('id', 'in', (array)$id)->select()->toArray();
                if (!empty($words)) {
                    foreach ($words as $k => $v) {
                        $data[] = [
                            'id' => $v['id'],
                            'fields' => $set == 1 ? (array_unique(array_merge($v['fields'], $fields))) : (array_diff($v['fields'], $fields))
                        ];
                    }
                    model('app\index\model\Words')->allowField(true)->saveAll($data);
                }
            }
            action('user/api/log', ['批量设置敏感词行为', 'ID:' . join(',', (array)$id) . ',' . ($set == 0 ? '' : ($set == 1 ? '增加' : '移除')) . '行为:' . join(',', $fields)]);
            return json(['code' => 1, 'msg' => '批量设置成功']);
        }
        return json(['code' => 85002, 'msg' => '参数错误']);
    }

    /**
     * 删除敏感词
     */
    function words_delete($id = [])
    {
        model('app\index\model\Words')->where('id', 'in', (array)$id)->delete();
        action('user/Api/log', ['删除敏感词【' . join(',', (array)$id) . '】']);
        load_words(1);
        return json(['code' => 1, 'msg' => '敏感词删除成功']);
    }

    /**
     * 地区管理
     */
    public function area()
    {
        if (input('param.cache')) {
            load_areas(1, 1);
            return json(['code' => 1, 'msg' => '地区缓存已刷新']);
        }
        $data = model('app\index\model\Area')->order('parent_id asc')->select();
        if (!empty($data)) {
            $data = array_values(array_to_tree(array_column($data->toArray(), null, 'id')));
            foreach ($data as $k => $v) {
                if (!empty($v['child'])) $data[$k]['child'] = array_values($v['child']);
            }
        }
        return json(['code' => 1, 'data' => $data]);
    }

    /**
     * 地区
     */
    function area_form($id = 0)
    {
        if (request()->isPost()) {
            $data = input('post.');
            $validate = validate('Area');
            if (!$validate->check($data)) return json(['code' => 85003, 'msg' => $validate->getError()]);
            $area = new Area();
            if ($id) {
                $area->allowField(true)->save($data, ['id' => $id]);
            } else {
                $area->data($data)->allowField(true)->save();
            }
            load_areas(1, 1);
            return json(['code' => 1, 'msg' => '地区信息已更新']);
        } else {
            if ($id) {
                return json(['code' => 1, 'data' => db('area')->where('id', '=', $id)->find()]);
            }
        }
    }

    /**
     *  地区状态
     * @param int $id
     * @return int
     */
    public function area_status($id = [], $status = 0)
    {
        if (!empty($id)) {
            db('area')->where('id', 'in', (array)$id)->update(['status' => $status]);
            load_areas(1, 1);
            return json(['code' => 1, 'msg' => '更新成功']);
        }
        return json(['code' => 0, 'msg' => '参数错误']);
    }

    /**
     * 删除地区
     */
    public function area_delete($id = [])
    {
        if (!empty($id)) {
            $count = db('area')->where('parent_id', 'in', (array)$id)->count();
            if (!$count) {
                $count = db('data')->where('area_id', 'in', (array)$id)->count();
                if ($count) return json(['code' => 85004, 'msg' => $count . '条数据在使用该地区']);
                $area = db('area')->where('id', 'in', (array)$id)->select();
                action('user/Api/log', ['删除地区【' . join(',', array_column($area, 'name')) . '】']);
                db('area')->where('id', 'in', $id)->delete();
                load_areas(1, 1);
                return json(['code' => 1, 'msg' => '地区删除成功']);
            }
            return json(['code' => 85005, 'msg' => '请先删除子级地区后重试...']);
        }
        return json(['code' => 85002, 'msg' => '参数错误']);
    }

    /**
     * 导出词库
     */
    function export()
    {
        $file_name = '词库配置' . date('Y-m-d');
        $words = db('words')->select();
        if (!empty($words)) {
            $data = [];
            foreach ($words as $k => $v) {
                $data[$k] = [
                    'name' => $v['name'],
                    'fields' => $v['fields'] ?: ' ',
                    'status' => $v['status'],
                    'url' => $v['url'] ?: ' '
                ];
            }
            action('user/Api/log', ['导出词库']);
            $this->save_excel($file_name, ['词', '操作行为', '状态（1：启用，0：禁用）', '链接地址'], $data);
        }
        return json(['code' => 0, 'msg' => '数据为空']);
    }

    /**
     * 导入词库
     */
    function import()
    {
        $files = request()->file();
        if (!empty($files)) {
            $fileinfo = $files['file']->getInfo();
            $result = $this->load_excel($fileinfo['tmp_name']);
            if (!empty($result)) {
                try {
                    $field = ['name', 'fields', 'status', 'url'];
                    foreach ($result as $k => $v) $words[array_values($v)[0]] = array_combine(array_slice($field, 0, count($v)), array_values($v));
                    if (!empty($words)) {
                        $words = array_values($words);
                        $name = array_column($words, 'name');
                        $exists = model('app\index\model\Words')->where('name', 'in', $name)->column('name');
                        if (!empty($exists)) {
                            foreach ($words as $k => $v) {
                                if (in_array($v['name'], $exists)) unset($words[$k]);
                            }
                        }
                        model('app\index\model\Words')->insertAll($words);
                        \load_words(1);
                    }
                } catch (\Exception $e) {
                    return json(['code' => 85006, 'msg' => '文件格式错误，请检查后重试...']);
                }
                return json(['code' => 1, 'msg' => '词库导入成功']);
            }
        }
        return json(['code' => 85007, 'msg' => '词库导入失败']);
    }

    /**
     * 配置项
     */
    public function conf($name = '', $status = 0)
    {
        if ($name) {
            if (!in_array($name, ['mail', 'sms', 'user', 'wechat', 'finance'])) return json(['code' => 85008, 'msg' => '参数非法']);
            $path = \think\facade\Env::get('root_path') . 'config' . DIRECTORY_SEPARATOR . $name . '.php';
            $conf = include($path);
            if (request()->isPost()) {
                switch ($name) {
                    case 'mail':
                        $data = input('post.');
                        break;
                    case 'sms':
                        $data['default']['gateways'][] = input('post.gateways', '');
                        if (!isset($conf['gateways'][input('post.gateways', '')])) return json(['code' => 85009, 'msg' => '所选的短信平台不存在']);
                        foreach ($conf['gateways'][input('post.gateways', '')] as $k => $v) $data['gateways'][input('post.gateways', '')][$k] = input('post.' . $k, '');
                        if (input('post.gateways', '') == 'qcloud') $data['gateways']['qcloud']['sign_name'] = '';
                        $data['SMS'][input('post.gateways', '')] = input('post.sms', '');
                        $data['PWD'][input('post.gateways', '')] = input('post.pwd', '');
                        $data['status'] = input('post.status', 0);
                        break;
                    case 'user':
                        $data = [
                            'qq' => [
                                'appid' => input('post.qq_appid', ''),
                                'secret' => input('post.qq_secret', '')
                            ],
                            'open_weixin' => [
                                'appid' => input('post.weixin_appid'),
                                'secret' => input('post.weixin_secret')
                            ],
                            'status' => input('post.status', 0)
                        ];
                        break;
                    case 'wechat':
                        $data = [];
                        if (isset(input('post.')['apps_appid'])) {
                            $data['apps'] = [
                                'app_id' => input('post.apps_appid', ''),
                                'secret' => input('post.apps_secret'),
                                'apps_status' => input('post.apps_status', 0)
                            ];
                        }
                        if (isset(input('post.')['mp_appid'])) {
                            $data['OfficialAccount'] = [
                                'app_id' => input('post.mp_appid', ''),
                                'secret' => input('post.mp_secret'),
                                'mp_status' => input('post.mp_status', 0)
                            ];
                        }
                        break;
                    case 'finance':
                        $data = [];
                        if (isset(input('post.')['alipay_appid'])) {
                            $data['alipay'] = [
                                'app_id' => input('post.alipay_appid', ''),
                                'private_key' => input('post.private_key', ''),
                                'ali_public_key' => input('post.pulic_key', ''),
                                'alipay_status' => input('post.alipay_status', 0)
                            ];
                        }
                        if (isset(input('post.')['wechat_appid'])) {
                            $data['wechat'] = [
                                'app_id' => input('post.wechat_appid', ''),
                                'miniapp_id' => input('post.wechat_appsid', ''),
                                'mch_id' => input('post.mch_id', ''),
                                'key' => input('post.key', ''),
                                'wechat_status' => input('post.wechat_status', 0)
                            ];
                        }
                        break;
                }
                if (empty($data)) return json(['code' => 85010, 'msg' => '保存失败，请检查内容是否填写完成']);
                if (count($conf) == count($conf, 1)) {
                    $conf = array_replace($conf, $data);
                } else {
                    foreach ($data as $k => $v) {
                        if (is_array($v) && isset($conf[$k])) {
                            $conf[$k] = array_replace($conf[$k], $v);
                        } else {
                            $conf[$k] = $v;
                        }
                    }
                }
            } else {
                if ($status && in_array($status, [1, 2])) {
                    $conf['status'] = $status;
                } else {
                    $data = [];
                    switch ($name) {
                        case 'mail':
                            if (!isset($conf['status']) || $conf['status'] != 2) $data = $conf;
                            $data['status'] = isset($conf['status']) ? $conf['status'] : 0;
                            break;
                        case 'sms':
                            if (!empty($conf['default']['gateways'][0]) && isset($conf['gateways'][$conf['default']['gateways'][0]])) {
                                $data['status'] = isset($conf['status']) ? $conf['status'] : 0;
                                if ($data['status'] != 2) {
                                    $data['gateways'] = $conf['default']['gateways'][0];
                                    $data['sms'] = $conf['SMS'][$data['gateways']];
                                    $data['pwd'] = isset($conf['PWD']) ? $conf['PWD'][$data['gateways']] : '';
                                    $data = array_merge($data, $conf['gateways'][$data['gateways']]);
                                }
                            }
                            break;
                        case 'user':
                            if (!isset($conf['status']) || $conf['status'] != 2) {
                                $data = [
                                    'qq_appid' => $conf['qq']['appid'],
                                    'qq_secret' => $conf['qq']['secret'],
                                    'weixin_appid' => $conf['open_weixin']['appid'],
                                    'weixin_secret' => $conf['open_weixin']['secret']
                                ];
                            }
                            $data['status'] = isset($conf['status']) ? $conf['status'] : 0;
                            break;
                        case 'wechat':
                            $data['apps_status'] = isset($conf['apps']['apps_status']) ? $conf['apps']['apps_status'] : 0;
                            $data['mp_status'] = isset($conf['OfficialAccount']['mp_status']) ? $conf['OfficialAccount']['mp_status'] : 0;
                            if ($data['apps_status'] != 2) {
                                $data['apps_appid'] = $conf['apps']['app_id'];
                                $data['apps_secret'] = $conf['apps']['secret'];
                            }
                            if ($data['mp_status'] != 2) {
                                $data['mp_appid'] = $conf['OfficialAccount']['app_id'];
                                $data['mp_secret'] = $conf['OfficialAccount']['secret'];
                            }
                            break;
                        case 'finance':
                            $data['alipay_status'] = isset($conf['alipay']['alipay_status']) ? $conf['alipay']['alipay_status'] : 0;
                            $data['wechat_status'] = isset($conf['wechat']['wechat_status']) ? $conf['wechat']['wechat_status'] : 0;
                            if ($data['alipay_status'] != 2) {
                                $data['alipay_appid'] = $conf['alipay']['app_id'];
                                $data['private_key'] = $conf['alipay']['private_key'];
                                $data['pulic_key'] = $conf['alipay']['ali_public_key'];
                            }
                            if ($data['wechat_status'] != 2) {
                                $data['wechat_appsid'] = $conf['wechat']['miniapp_id'];
                                $data['wechat_appid'] = $conf['wechat']['app_id'];
                                $data['mch_id'] = $conf['wechat']['mch_id'];
                                $data['key'] = $conf['wechat']['key'];
                            }
                            break;
                    }
                    $data['path'] = '/config/' . $name . '.php';
                    $result = ['code' => 1, 'msg' => '加载成功', 'data' => $data];
                    if ($name == 'sms') {
                        $gateways = config('app.gateways');
                        foreach ($gateways as $k => $v) $gateways[$k]['param'] = array_keys($conf['gateways'][$k]);
                        $result['sms'] = $gateways;
                    }
                    return json($result);
                }
            }
            $text = 'return ' . var_export($conf, true) . ';';
            @file_put_contents($path, preg_replace('/return[\s\S]*;/', $text, file_get_contents($path)));
            return json(['code' => 1, 'msg' => '设置成功']);
        }
        return '';
    }

    /**
     * 空方法解析
     */
    public function _empty($name)
    {
        if (in_array($name, array('area_add', 'area_edit'))) {
            return $this->area_form(input('param.id'));
        }
        if (in_array($name, array('words_add', 'workds_edit'))) {
            return $this->words_form();
        }
        return parent::_empty($name);
    }

}
