<?php

namespace App\Admin\Extensions\ToolBar\Forms;

use App\Common\Util;
use App\Models\Group\GroupMessageRecordModel;
use App\Models\Group\GroupModel;
use App\Service\Alipay\AlipayGroupService;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class SendGroupMsgForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function form()
    {
        $this->textarea('group_ids', '已勾选群组ID')->attribute('id', 'batch-ids')->help('如果未指定群组ID，则发送所有群组！');
        $this->text('title', '消息名称')->default('粉丝福利')->help('只供商家区分消息，消费者看不到~')->required();
        $this->radio('msg_type', '消息类型')
            ->when(GroupMessageRecordModel::MSG_TYPE_TEXT, function (Form $form) {
                $form->textarea('text_content', '消息内容')->rules('required_if:msg_type,1')->setLabelClass(['asterisk']);
            })
            ->when(GroupMessageRecordModel::MSG_TYPE_IMAGE, function (Form $form) {
                $form->image('image_image', '消息图片')->accept('jpg,png')->uniqueName()->autoUpload()->retainable()->removable(false)->rules('required_if:msg_type,2')->setLabelClass(['asterisk'])->help('支持jpg、png格式，大小1Mb以内');
                $form->number('image_width', '图片宽度')->rules('required_if:msg_type,2')->setLabelClass(['asterisk'])->help('图片宽，请必须传图片真实的宽，否则客户端会按照填的宽高进行剪裁');
                $form->number('image_height', '图片高度')->rules('required_if:msg_type,2')->setLabelClass(['asterisk'])->help('图片高度，请必须传图片真实的高度，否则客户端会按照填的宽高进行剪裁');
            })
            ->when(GroupMessageRecordModel::MSG_TYPE_LINK, function (Form $form) {
                $form->text('link_title', '消息标题')->maxLength(23)->rules('required_if:msg_type,3')->setLabelClass(['asterisk'])->help('消息标题，c侧消息展示的标题');
                $form->text('link_desc', '消息描述')->maxLength(64)->rules('required_if:msg_type,3')->setLabelClass(['asterisk']);
                $form->text('link_url', '消息跳转地址')->maxLength(1024)->rules('required_if:msg_type,3')->setLabelClass(['asterisk'])->help('消息跳转地址，输入alipays:// 或者 https://的链接。例如：alipays://platformapi/startapp?appId=xxx&url=xxx');
                $form->image('link_image', '消息图片')->accept('jpg,png')->uniqueName()->autoUpload()->retainable()->removable(false)->rules('required_if:msg_type,3')->setLabelClass(['asterisk'])->help('支持jpg、png格式，图片宽高1:1，大小1Mb以内');
            })
            ->when(GroupMessageRecordModel::MSG_TYPE_APP, function (Form $form) {
                $form->text('app_title', '群消息标题')->maxLength(28)->rules('required_if:msg_type,4')->setLabelClass(['asterisk'])->help('推送的消息文案标题（参考：好物分享来咯！）');
                $form->text('app_desc', '群消息描述')->maxLength(34)->rules('required_if:msg_type,4')->setLabelClass(['asterisk'])->help('对推送商品的简单介绍（参考：美妆好物应有尽有，快戳进来看看呀）');
                $form->text('app_url', '群消息跳转链接')->maxLength(512)->rules('required_if:msg_type,4')->setLabelClass(['asterisk'])->help('自定义链接或小程序页面链接（自定义链接请输入http,https或alipays开头的链接），例如：alipays://platformapi/startapp?appId=2021***&page=pages%2Findex%2Findex');
                $form->text('app_tiny_app_id', '应用id')->maxLength(16)->rules('required_if:msg_type,4')->setLabelClass(['asterisk'])->help('小程序appId。用于入群欢迎语在群里展示');
                $form->image('app_image', '消息图片')->accept('jpg,png')->uniqueName()->autoUpload()->retainable()->removable(false)->rules('required_if:msg_type,4')->setLabelClass(['asterisk'])->help('支持jpg、png格式，图片尺寸：202*160，大小1M以内');
            })
            ->options(GroupMessageRecordModel::MSG_TYPE_MAP)
            ->default(GroupMessageRecordModel::MSG_TYPE_TEXT)
            ->required();
        $this->switch('at_all', '是否@所有人')->help('同一群组每周仅允许发送一条@所有人的消息!请慎重勾选');
    }

    public function handle(array $input)
    {
        $title = $input['title'];
        $msgType = $input['msg_type'];
        $groupIds = $input['group_ids'];
        $atAll = $input['at_all'];
        $groupIdsArray = clean_ids($groupIds, true);
        $qb = GroupModel::query();
        if ($groupIdsArray) {
            $qb->whereIn('id', $groupIdsArray);
        }
        $groups = $qb->get()->toArray();
        foreach ($groups as $v) {
            try {
                $channel = $v['channel'];
                $msgData = [];
                switch ($msgType) {
                    case GroupMessageRecordModel::MSG_TYPE_TEXT:
                        $textContent = $input['text_content'];
                        $msgData = [
                            'msg_type' => 'TEXT',
                            'text_msg_content' => [
                                'content' => $textContent,
                            ],
                        ];
                        break;
                    case GroupMessageRecordModel::MSG_TYPE_IMAGE:
                        $imageWidth = $input['image_width'];
                        $imageHeight = $input['image_height'];
                        $imageImage = $input['image_image'];
                        $imageImageFullUrl = Util::getImgUrl($imageImage);
                        $service = new AlipayGroupService($channel, false);
                        $imageImageId = $service->uploadImage($imageImageFullUrl);
                        $msgData = [
                            'msg_type' => 'IMAGE',
                            'image_msg_content' => [
                                'image_id' => $imageImageId,
                                'width' => $imageWidth,
                                'height' => $imageHeight,
                            ],
                        ];
                        break;
                    case GroupMessageRecordModel::MSG_TYPE_LINK:
                        $linkTitle = $input['link_title'];
                        $linkDesc = $input['link_desc'];
                        $linkUrl = $input['link_url'];
                        $linkImage = $input['link_image'];
                        $linkImageFullUrl = Util::getImgUrl($linkImage);
                        $service = new AlipayGroupService($channel, false);
                        $linkImageId = $service->uploadImage($linkImageFullUrl);
                        $msgData = [
                            'msg_type' => 'LINK',
                            'link_msg_content' => [
                                'title' => $linkTitle,
                                'desc' => $linkDesc,
                                'url' => $linkUrl,
                                'image_id' => $linkImageId,
                            ],
                        ];
                        break;
                    case GroupMessageRecordModel::MSG_TYPE_APP:
                        $appTitle = $input['app_title'];
                        $appDesc = $input['app_desc'];
                        $appUrl = $input['app_url'];
                        $appTinyAppId = $input['app_tiny_app_id'];
                        $appImage = $input['app_image'];
                        $appImageFullUrl = Util::getImgUrl($appImage);
                        $service = new AlipayGroupService($channel, false);
                        $appImageId = $service->uploadImage($appImageFullUrl);
                        $msgData = [
                            'msg_type' => 'APP',
                            'tiny_app_msg_content' => [
                                'title' => $appTitle,
                                'desc' => $appDesc,
                                'url' => $appUrl,
                                'tiny_app_id' => $appTinyAppId,
                                'image_id' => $appImageId,
                            ],
                        ];
                        break;
                }
                // 插入记录
                $groupMsgRecordModel = new GroupMessageRecordModel;
                $groupMsgRecordModel->code_id = $v['code_id'];
                $groupMsgRecordModel->channel = $channel;
                $groupMsgRecordModel->title = $title;
                $groupMsgRecordModel->msg_type = $msgType;
                $groupMsgRecordModel->msg_data = $msgData;
                $groupMsgRecordModel->group_id = $v['id'];
                $groupMsgRecordModel->at_all = $atAll ?? false;
                $groupMsgRecordModel->send_status = GroupMessageRecordModel::SEND_STATUS_WAIT;
                $groupMsgRecordModel->err_msg = '';
                $groupMsgRecordModel->save();
                // 发送消息
                $service = new AlipayGroupService($channel, false);
                $result = $service->groupMsgSend([$v['alipay_group_id']], $title, $msgData, $atAll);
                if ($result) {
                    $groupMsgRecordModel->send_status = GroupMessageRecordModel::SEND_STATUS_SUCCESS;
                    $groupMsgRecordModel->err_msg = '';
                    $groupMsgRecordModel->save();
                }
            } catch (\Exception $e) {
                $groupMsgRecordModel->send_status = GroupMessageRecordModel::SEND_STATUS_FAIL;
                $groupMsgRecordModel->err_msg = $e->getMessage() ? $e->getMessage() : '未知错误';
                $groupMsgRecordModel->save();
            }
        }

        return $this->response()->alert(true)->success('操作完成')->refresh();
    }
}
