<?php

namespace app\controller\manager;


use app\exception\RepositoryException;
use app\exception\TraitException;
use app\model\Log;
use app\model\Message as MessageModel;
use app\model\ScriptManagement as ScriptManagementModel;
use app\repository\AccountRepository;
use app\service\ali\Sms;
use app\service\wx\WechatApplets;
use GuzzleHttp\Exception\GuzzleException;
use think\facade\Db;

class Push extends Base
{

    public function index()
    {
        $repo = AccountRepository::getInstance();

        if ($this->request->isPost()) {
            $page = $this->request->param('page/d', 1);
            $size = $this->request->param('size/d', 30);

            $whereMap   = [];
            $orders     = ['send_at' => 'desc', 'id' => 'desc'];
            $whereMap[] = ['type', '<>', MessageModel::TYPE_REMINDERS];
            $whereMap[] = ['is_push', '=', MessageModel::COMMON_ON];
            $res        = $repo->messageList($whereMap, [], $page, $size, null, $orders);
            $list       = $res['list'];

            $msgTypeTextList   = $repo->messageTypeTextList();
            $msgTargetTextList = $repo->messageTargetTextList();
            foreach ($list as $item) {
                $item['type_text']   = $msgTypeTextList[$item['type']] ?? '';
                $item['target_text'] = $msgTargetTextList[$item['target']] ?? '';
            }
            $res['list'] = $list;

            return $this->json(0, 'success', $res);
        }

        return $this->view();
    }

    public function add()
    {
        $repo = AccountRepository::getInstance();
        if ($this->request->isPost()) {
            $item          = $this->request->param('item/a', []);
            $targetListStr = $this->request->param('target_list_str/s', '');

            Db::startTrans();
            try {
                $targetList = empty($targetListStr) ? [] : explode(',', $targetListStr);
                $repo->createMessage($item, $targetList);
                Db::commit();
                return $this->json();
            } catch (RepositoryException | TraitException $e) {
                Db::rollback();
                return $this->json(4001, $e->getMessage());
            } catch (\Exception $e) {
                Db::rollback();
                \think\facade\Log::error('[添加推送失败]'.$e->getMessage());
                return $this->json(5001, '添加推送失败');
            }
        }

        $this->data['subscribeTempList']   = WechatApplets::msgTemplateList();
        $this->data['subscribeTempParams'] = json_encode(WechatApplets::msgTemplateParams(), JSON_UNESCAPED_UNICODE);

        $this->data['smsTempList']   = Sms::templateList();
        $this->data['smsTempParams'] = json_encode(Sms::templateParams(), JSON_UNESCAPED_UNICODE);


        $this->data['targetList'] = $repo->messageTargetTextList();

        return $this->view();
    }

    public function edit()
    {
        $repo = AccountRepository::getInstance();
        $id   = $this->request->param('id/d', 0);
        $msg  = $repo->messageInfo($id);
        if (empty($msg)) {
            return $this->json(4000, '没有相关的消息记录');
        }

        if ($this->request->isPost()) {
            $item          = $this->request->param('item/a', []);
            $targetListStr = $this->request->param('target_list_str/s', '');

            try {
                $type       = $item['type'] ?? '';
                $target     = $item['target'] ?? '';
                $targetList = empty($targetListStr) ? [] : explode(',', $targetListStr);

                $repo->editMessage($id, $type, $target, $targetList, $item);

            } catch (TraitException $e) {
                return $this->json(4001, $e->getMessage());
            }

            return $this->json();
        }

        $targetAids = empty($msg['target_list'] ?? '') ? [] : explode(',', $msg['target_list']);
        $whereMap[] = ['id', 'in', $targetAids];
        $targetList = $repo->findList($whereMap)['list']->toArray();
        foreach ($targetList as &$item) {
            $item['account_desc2'] = $item['nickname'].'【姓名:'.$item['real_name'].'】';
            $item['selected']      = true;
        }

        $this->data['id']                     = $id;
        $this->data['item']                   = $msg;
        $this->data['targetListJson']         = json_encode($targetList, JSON_UNESCAPED_UNICODE);
        $this->data['typeList']               = $repo->messageTypeTextList();
        $this->data['targetList']             = $repo->messageTargetTextList();
        $scriptManagement                     = ScriptManagementModel::getAll();
        $this->data["script_management"]      = $scriptManagement;
        $this->data["script_management_json"] = json_encode($scriptManagement);
        return $this->view();
    }


    public function del()
    {
        if (!$this->request->isPost()) {
            return $this->json(4000, '非法请求');
        }

        $ids = $this->request->param('ids/a', []);
        if (empty($ids)) {
            $ids[] = $this->request->param('id/d', 0);
            $ids   = array_filter($ids);
        }

        if (count($ids)) {
            AccountRepository::getInstance()->deleteMessages($ids);
            Log::write(get_class(), 'del', '删除了message,涉及到的ID为:'.implode(',', $ids));
        }
        return $this->json();
    }

}