<?php
/**
 * +------------------------------------------------------------
 * | 区块-管理 (block/controller/Admin.php)
 * +------------------------------------------------------------
 * | @author: zhx (10630650@qq.com)
 * | @create_time: 2018-04-19 17:14:25
 * +------------------------------------------------------------
 * | @copyright: CIM信息聚合系统 (https://cimxx.com)
 * +------------------------------------------------------------
 * | @last_modified_by: zhx
 * | @last_modified_time: 2018-07-14 18:06:48
 * +------------------------------------------------------------
 * | @todo:
 * +------------------------------------------------------------
 */

namespace app\Block\controller;

use app\common\controller\Init;
use app\block\model\Data;
use think\facade\Cache;
use app\common\controller\Fields;

class Admin extends Init
{

    private static $fields;

    protected function initialize()
    {
        parent::initialize();
        if (in_array(self::$sys['action'], ['fields', 'fields_form', 'fields_forbid', 'fields_delete', 'fields_status'])) self::$fields = new Fields();
    }

    /*
     * 列表
     */
    public function index($keyword = '')
    {
        $where = [];
        if ($keyword) $where[] = ['name', 'like', '%' . $keyword . '%'];
        $rs = db('block')->where($where)->paginate(20)->toArray();
        if (!empty($rs['data'])) {
            $types = config('types');
            foreach ($rs['data'] as $k => &$v) {
                $v['fields'] = load_fields([
                    'relation_id' => $v['id'],
                    'model' => 'block'
                ]);
                $v['type_name'] = $types[$v['type']];
            }
        }
        return json(['code' => 1, 'msg' => $rs]);
    }

    /*
     * 区块创建/修改
     */
    public function block_form($id = 0)
    {
        if (request()->isPost()) {
            $data = input('post.');
            if (isset($data['id'])) $id = $data['id'];
            $validate = validate('Add');
            if (!$validate) return json(['code' => 25001, 'msg' => $validate->getError()]);
            if ($data['type'] == 0) $data['setting'] = htmlspecialchars(($id ? $data['setting'] : $data['setting']));
            if ($data['type'] > 0) $data['setting'] = json_encode($data['setting']);
            if ($id) {
                model('block')->allowField(true)->save($data, ['id' => $id]);
                Cache::clear('block_id_' . $id);
                Cache::clear('block_id_' . $data['key']);
            } else {
                model('block')->allowField(true)->save($data);
            }
            action('user/Api/log', [($id ? '修改' : '添加') . '区块【' . $data['name'] . '】']);
            return json(['code' => 1, 'msg' => '区块《' . $data['name'] . '》已' . ($id ? '更新' : '创建') . '完成。']);
        }
        if ($id) {
            $rs = db('block')->find($id);
            if ($rs['type'] > 0) $rs['setting'] = json_decode($rs['setting'], true);
            if ($rs['type'] == 1) {
                $rs['fields'] = [];
                if (isset($rs['setting']['fields'])) $rs['fields'] = array_merge($rs['fields'], $rs['setting']['fields']);
                if (isset($rs['setting']['extend_fields'])) $rs['fields'] = array_merge($rs['fields'], $rs['setting']['extend_fields']);
                if (isset($rs['setting']['link_fields'])) $rs['fields'] = array_merge($rs['fields'], $rs['setting']['link_fields']);
            }
            if ($rs['type'] == 0) $rs['setting'] = html_entity_decode(htmlspecialchars_decode($rs['setting']));
            return json(['code' => 1, 'data' => $rs]);
        }
    }

    /**
     * 返回配置项
     * @return \think\response\Json
     */
    function configs()
    {
        return json(['code' => 1, 'data' => [
            'modules' => get_block_map(),
            'fields' => config('optional_fields'),
            'types' => config('types')
        ]]);
    }

    /*
     * 区块数据推送
     */
    public function push($id = 0)
    {
        if (request()->isPost()) {
            $data = input('post.');
            $validate = validate('Push');
            if (!$validate->check($data)) return json(['code' => 25002, 'msg' => $validate->getError()]);
            if (isset($data['extend_fields'])) $data['extend_fields'] = json_encode($data['extend_fields']);
            $where[] = ['block_id', '=', $data['block_id']];
            $where[] = ['data_id', '=', $data['data_id']];
            $where[] = ['column_id', '=', $data['column_id']];
            !isset($data['status']) && $data['status'] = 1;
            $_model = new Data;
            $source = [];
            if (Data::where($where)->count()) {
                $block_data = $_model->where($where)->find();
                if (!empty($block_data['thumb'])) {
                    $source[] = [
                        'data_id' => $id,
                        'path' => $block_data['thumb']['value'],
                        'fields' => 'block_data|thumb'
                    ];
                }
                $_model->allowField(true)->save($data, $where);
                $id = $_model->id;
            } else {
                $res = Data::create($data, true);
                $id = $res->id;
            }
            action('user/Api/log', ['添加区块数据【' . $data['name'] . '】']);
            if (!empty($data['thumb'])) {
                $update = [
                    ['path' => $data['thumb'], 'data_id' => $id, 'fields' => 'block_data|thumb', 'title' => $data['name']]
                ];
                //更新附件信息
                action('files/api/update_file_info', [$update, $source]);
            }
            $cache_id = 'block_data_' . $data['block_id'];
            cache($cache_id, null);
            return json(['code' => 1, 'msg' => '数据已推送成功。']);
        }
    }

    /**
     * 发布/修改 数据
     */
    public function form($id = 0)
    {
        if (request()->isPost()) {
            if (!input('?post.block_id')) return json(['code' => 25003, 'msg' => '推送位置错误']);
            $data = input('post.');
            $block = db('block')->where('id', '=', $data['block_id'])->find();
            if (isset($data['extend_fields'])) $data['extend_fields'] = json_encode($data['extend_fields']);
            !isset($data['status']) && $data['status'] = 1;
            $_model = new Data;
            $source = [];
            action('user/Api/log', [($id ? '修改' : '添加') . '区块【' . $block['name'] . '】数据', '数据：' . $data['name']]);
            if ($id) {
                $where[] = ['id', '=', $data['id']];
                $where[] = ['block_id', '=', $data['block_id']];
                $block_data = $_model->where($where)->find();
                if (!empty($block_data['thumb'])) {
                    $source[] = [
                        'data_id' => $id,
                        'path' => $block_data['thumb']['value'],
                        'fields' => 'block_data|thumb'
                    ];
                }
                $_model->allowField(true)->save($data, $where);
            } else {
                unset($data['id']);
                $res = Data::create($data, true);
                $id = $res->id;
            }
            if (!empty($data['thumb'])) {
                $update = [
                    ['data_id' => $id, 'path' => $data['thumb'], 'fields' => 'block_data|thumb', 'title' => $data['name']]
                ];
                //更新附件信息
                action('files/api/update_file_info', [$update, $source]);
            }
            $cache_id = 'block_data_' . $data['block_id'];
            cache($cache_id, null);
            return json(['code' => 1, 'msg' => '数据已推送成功。']);
        }
    }

    public function get_data($id, $block_id)
    {
        $rs = model('data')->where('block_id', $block_id)->where('id', $id)->find();
        return json(['code' => 1, 'data' => $rs]);
    }

    /**
     * 获取可推送区块
     */
    public function get_blocks($type = 1)
    {
        $rs = db('block')->field('id,name')->where('type', $type)->select();
        if (!empty($rs)) {
            foreach ($rs as $k => $v) {
                $rs[$k]['fields'] = load_fields([
                    'relation_id' => $v['id'],
                    'model' => 'block'
                ]);
            }
        }
        return json(['code' => 1, 'data' => $rs]);
    }

    /*
     * 区块获取显示字段
     */
    function get_display_fields()
    {
        $rs = ['fields' => config('optional_fields')];
        if (input('?param.module')) {
            $module = get_block_map(input('param.module'));
            if (isset($module['block']['extend_fields']) && !empty($module['block']['extend_fields'])) $rs['extend_fields'] = $module['block']['extend_fields'];
            if (isset($module['block']['link_fields']) && !empty($module['block']['link_fields'])) $rs['link_fields'] = $module['block']['link_fields'];
        }
        $rss = [];
        foreach ($rs as $k => $v) {
            foreach ($v as $kk => $vv)
                $rss[$k][] = ['key' => $kk, 'name' => $vv];
        }
        return json(['code' => 1, 'data' => $rss]);
    }

    /**
     * 数据管理
     */
    function data($id, $keywords = '')
    {
        $where[] = ['block_id', '=', $id];
        if ($keywords) $where[] = ['name', 'like', '%' . $keywords . '%'];
        $rs = Data::where($where)->order('create_time desc')->paginate(20)->toArray();
        if (!empty($rs['data'])) {
            $columns = load_columns(0, 0, 'id', '', '');
            foreach ($rs['data'] as $k => &$v) {
                if (!empty($v['column_id'])) $v['column_name'] = $columns[$v['column_id']]['name'];
            }
        }
        $block = db('block')->find($id);
        $fields = load_fields([
            'relation_id' => $id,
            'model' => 'block'
        ]);
        return json(['code' => 1, 'data' => $rs['data'], 'column' => $block, 'fields' => $fields]);
    }

    /**
     * 删除数据
     */
    public function remove($id = [])
    {
        if (empty($id)) return json(['code' => 25004, 'msg' => '请选择要删除的数据']);
        $data = db('block_data')->where('id', 'in', (array)$id)->select();
        if (!empty($data)) {
            Data::where('id', 'in', (array)$id)->delete();
            $attr = [];
            foreach ($data as $k => $v) {
                if (!empty($v['thumb'])) {
                    $attr[] = [
                        'data_id' => $v['id'],
                        'path' => $v['thumb'],
                        'fields' => 'block_data|thumb'
                    ];
                }
            }
            if (!empty($attr)) action('files/api/update_file_info', [[], $attr]);
            action('user/Api/log', ['删除区块数据', '数据id:' . join(',', $id)]);
            return json(['code' => 1, 'msg' => '数据删除成功']);
        } else {
            return json(['code' => 25005, 'msg' => '数据删除失败']);
        }
    }

    /*
     * 删除区块
     */
    public function delete($id = [])
    {
        $count = Data::where('block_id', 'in', (array)$id)->count();
        if ($count) return json(['code' => 25006, 'msg' => '数据块下仍有数据，清空数据后才能删除...']);
        $block = db('block')->where('id', 'in', (array)$id)->select();
        model('block')->where('id', 'in', (array)$id)->delete();
        action('user/Api/log', ['删除区块', join(array_column($block, 'name'))]);
        return json(['code' => 1, 'msg' => '区块删除成功']);
    }

    /*
     * 刷新缓存
     */
    public function refresh($id)
    {
        if (is_numeric($id)) {
            $where[] = ['id', '=', $id];
        } else {
            $where[] = ['key', '=', $id];
        }
        $block = db('block')->where($where)->find();
        Cache::clear('block_id_' . $block['id']);
        action('user/Api/log', ['刷新区块【' . $block['name'] . '】缓存']);
        return json(['code' => 1, 'msg' => '缓存已刷新']);
    }

    /**
     * 修改区块数据
     */
    function change_status($id = [], $status = '', $time = 0)
    {
        //批量修改状态
        if ($status !== '' && in_array($status, [0, 1])) {
            db('block_data')->where('id', 'in', $id)->setField('status', $status);
            action('user/Api/log', ['批量设置区块数据状态为' . $status, '数据ID:' . join(',', $id)]);
        }
        //批量延期
        if (is_numeric($time)) {
            db('block_data')->where('id', 'in', $id)->setInc('end_time', $time * 86400);
            action('user/Api/log', ['批量设置区块数据显示截止时间', '数据ID:' . join(',', $id) . ',' . '延长' . $time . '天']);
        }
        return json(['code' => 1, 'msg' => '操作成功']);
    }

    /**
     * 扩展字段
     */
    public function fields($relation_id = 0)
    {
        return self::$fields->fields($relation_id, 'block');
    }

    /**
     * 继承自定义字段禁用
     */
    function fields_forbid($fields_id = 0, $relation_id = 0)
    {
        return self::$fields->forbid($fields_id, $relation_id, 'block');
    }

    /**
     * 扩展字段 添加 / 修改
     */
    function fields_form($id = 0)
    {
        return self::$fields->form($id, 'block');
    }

    /**
     * 扩展字段 删除
     */
    public function fields_delete($id = [])
    {
        return self::$fields->delete($id, 'block');
    }

    /**
     * 批量改变字段状态
     */
    function fields_status($id = [], $status = '', $relation_id = 0)
    {
        return self::$fields->status($id, $status, $relation_id);
    }

    /**
     * 空方法解析
     */
    public function _empty($name)
    {
        if (in_array($name, array('block_add', 'block_edit'))) {
            return $this->block_form(input('param . id', 0));
        }
        if (in_array($name, array('add', 'edit'))) {
            return $this->form(input('param . id', 0), input('param . block_id', 0));
        }
    }

}
