<?php

namespace addons\vbot;

use addons\vbot\library\VbotLib;
use app\common\library\Menu;
use think\Addons;
use think\Db;

/**
 * 微信通知机器人
 */
class Vbot extends Addons
{

    /**
     * 通过模板发送通知消息
     * @param  string $template 消息模板Id或Code
     * @param  array $tpl_data 要覆盖的模板数据 (参见:\application\admin\controller\dinghorn\Example.php 的 example2 方法)
     * @param  array $tpl_variable 模板变量键值对,若模板变量已预先定义,则会自动获取值,无需在此传递
     * @return array                 发送结果
     */
    public function vbotSendMsg($template, $tpl_data = array(), $tpl_variable = array())
    {
        $now_time = time();

        // 查询对应模板
        $template = Db::name('vbot_template')
            ->where('id = :tpl OR code = :tpl_code', ['tpl' => $template, 'tpl_code' => $template])
            ->where('deletetime', null)
            ->find();

        if (!$template || !$template['openswitch']) {

            $log_arr = [
                'robot_id'      => 0,
                'template_id'   => 0,
                'template_data' => 0,
                'errmsg'        => '消息模板未找到或已禁用!(-2)',
                'status'        => '0',
                'createtime'    => $now_time
            ];

            Db::name('vbot_msglog')->insert($log_arr);
            return array('errcode' => -2, 'errmsg' => '消息模板未找到或已禁用!');
        }

        $VbotLib = new VbotLib($template, $tpl_data, $tpl_variable);

        // 获取模板内的机器人
        $robot_ids = isset($tpl_data['robot_ids']) ? $tpl_data['robot_ids'] : $template['robot_ids'];
        $robots    = Db::name('vbot_robot')
            ->whereIn('id', $robot_ids)
            ->where('openswitch', 1)
            ->where('deletetime', null)
            ->select();

        // 组装消息数据
        $msg_data = $VbotLib->deal_with_msg();

        $log_arr     = [];//要插入的日志
        $vbot_config = get_addon_config('vbot');
        $is_err      = false;//是否有错误,用于判定本次操作的返回值

        // 循环所有要发送的机器人
        foreach ($robots as $key => $value) {
            $res = $VbotLib->msgSend($value['webhook'], $msg_data);

            if ($res['errcode'] == 0 && $vbot_config['success_log']) {
                $log_arr[] = array(
                    'robot_id'      => $value['id'],
                    'template_id'   => $template['id'],
                    'template_data' => json_encode($msg_data),
                    'errmsg'        => '',
                    'status'        => '1',
                    'createtime'    => $now_time
                );
            } elseif ($res['errcode'] != 0) {
                $is_err = true;

                if ($vbot_config['error_log']) {
                    $log_arr[] = array(
                        'robot_id'      => $value['id'],
                        'template_id'   => $template['id'],
                        'template_data' => json_encode($msg_data),
                        'errmsg'        => $res['errmsg'] . '(' . $res['errcode'] . ')',
                        'status'        => '0',
                        'createtime'    => $now_time
                    );
                }
            }
        }

        if ($log_arr) {
            Db::startTrans();
            try {
                Db::name('vbot_msglog')->insertAll($log_arr);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
            }
        }

        return !$is_err ? ['errcode' => 0] : ['errcode' => -3, 'errmsg' => '消息发送失败,请查看日志'];
    }

    /**
     * 插件安装方法
     * @return bool
     */
    public function install()
    {
        $menu = [
            [
                'name'    => 'vbot',
                'title'   => '微信通知机器人',
                'icon'    => 'fa fa-volume-up',
                'sublist' => [
                    [
                        'name'    => 'vbot/robot',
                        'title'   => '机器人管理',
                        'icon'    => 'fa fa-circle-o',
                        'sublist' => [
                            ['name' => 'vbot/robot/index', 'title' => '查看'],
                            ['name' => 'vbot/robot/add', 'title' => '添加'],
                            ['name' => 'vbot/robot/edit', 'title' => '编辑'],
                            ['name' => 'vbot/robot/del', 'title' => '删除'],
                            ['name' => 'vbot/robot/multi', 'title' => '批量更新'],
                            ['name' => 'vbot/robot/recyclebin', 'title' => '回收站'],
                            ['name' => 'vbot/robot/destroy', 'title' => '真实删除'],
                            ['name' => 'vbot/robot/restore', 'title' => '还原'],
                        ]
                    ],
                    [
                        'name'    => 'vbot/variable',
                        'title'   => '模板变量管理',
                        'icon'    => 'fa fa-circle-o',
                        'remark'  => '在此处设置变量,随后可在模板通知内使用变量,变量值可来源于方法返回值或SQL查询结果',
                        'sublist' => [
                            ['name' => 'vbot/variable/index', 'title' => '查看'],
                            ['name' => 'vbot/variable/add', 'title' => '添加'],
                            ['name' => 'vbot/variable/edit', 'title' => '编辑'],
                            ['name' => 'vbot/variable/del', 'title' => '删除'],
                            ['name' => 'vbot/variable/multi', 'title' => '批量更新'],
                            ['name' => 'vbot/variable/recyclebin', 'title' => '回收站'],
                            ['name' => 'vbot/variable/destroy', 'title' => '真实删除'],
                            ['name' => 'vbot/variable/restore', 'title' => '还原'],
                            ['name' => 'vbot/variable/view_variable', 'title' => '计算变量值'],
                        ]
                    ],
                    [
                        'name'    => 'vbot/template',
                        'title'   => '通知模板管理',
                        'icon'    => 'fa fa-circle-o',
                        'sublist' => [
                            ['name' => 'vbot/template/index', 'title' => '查看'],
                            ['name' => 'vbot/template/add', 'title' => '添加'],
                            ['name' => 'vbot/template/edit', 'title' => '编辑'],
                            ['name' => 'vbot/template/del', 'title' => '删除'],
                            ['name' => 'vbot/template/multi', 'title' => '批量更新'],
                            ['name' => 'vbot/template/recyclebin', 'title' => '回收站'],
                            ['name' => 'vbot/template/destroy', 'title' => '真实删除'],
                            ['name' => 'vbot/template/restore', 'title' => '还原'],
                        ]
                    ],
                    [
                        'name'    => 'vbot/msglog',
                        'title'   => '通知发送日志管理',
                        'icon'    => 'fa fa-circle-o',
                        'sublist' => [
                            ['name' => 'vbot/msglog/index', 'title' => '查看'],
                            ['name' => 'vbot/msglog/edit', 'title' => '编辑'],
                            ['name' => 'vbot/msglog/del', 'title' => '删除'],
                            ['name' => 'vbot/msglog/multi', 'title' => '批量更新'],
                            ['name' => 'vbot/msglog/recyclebin', 'title' => '回收站'],
                            ['name' => 'vbot/msglog/destroy', 'title' => '真实删除'],
                            ['name' => 'vbot/msglog/restore', 'title' => '还原'],
                        ]
                    ],
                ]
            ]
        ];
        Menu::create($menu);
        return true;
    }

    /**
     * 插件卸载方法
     * @return bool
     */
    public function uninstall()
    {
        Menu::delete('vbot');
        return true;
    }

    /**
     * 插件启用方法
     * @return bool
     */
    public function enable()
    {
        Menu::enable('vbot');
        return true;
    }

    /**
     * 插件禁用方法
     * @return bool
     */
    public function disable()
    {
        Menu::disable('vbot');
        return true;
    }
}