<?php

namespace App\Jobs\OpenWork\Contactway;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Servers\DB\DbService;
use App\Models\OpenWork\job\Records;
use App\Facades\Servers\Logs\Log;
use App\Models\OpenWork\Contactway\Qrcode as QrcodeModel;
use App\Models\OpenWork\Contactway\QrcodeUser;
use App\Models\OpenWork\Contactway\QrcodeWelcome;
use App\Facades\Servers\Wechat\OpenWork;
use Illuminate\Support\Facades\DB;
use App\Models\OpenWork\External\Tag;


/**
 * SCRM 创建渠道活码
 * @author  唐远望
 * @version  1.0
 * @date   2025-08-15
 */
class ChannelActiveCodeCreateJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $message_data;
    protected $Records;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(array $message_data)
    {
        $this->message_data = $message_data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            $companyId = $this->message_data['company_id'];
            (new DbService())->getConnectionNameByCompanyId($companyId);
            // 创建任务记录
            $this->Records = Records::create([
                'job_id' => $companyId . '_ChannelActiveCodeCreateJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);
            $result = $this->add($this->message_data);
            if (isset($result['code']) && $result['code'] == 'error') {
                Log::info('job_error', '渠道活码创建任务失败', ['error' => $result]);
            }
            //删除任务记录
            $this->Records->delete();
        } catch (\Exception $e) {
            // 失败处理...
            if ($this->Records) {
                $this->Records->delete();
            }
            Log::info('job_error', '渠道活码创建任务失败', ['data' => $this->message_data, 'error' => $e->getMessage()]);
        }
    }


    public function failed(\Throwable $exception)
    {
        Log::info('job_error', '渠道活码创建任务完全失败', ['data' => $this->message_data, 'error' => $exception]);

        $this->Records->delete();
    }

    /**	
     * 新增配置   /openwork/contactway_qrcode/add
     * 
     * 
     */
    public function add($message_data)
    {

        $Model = new QrcodeModel();
        $qrcodeUserModel = new QrcodeUser();
        $qrcodeWelcomeModel = new QrcodeWelcome();
        // 接收参数
        $companyId                  = $message_data['company_id'];
        $data['corpid']             = $message_data['corpid'];
        $data['remark']                = $message_data['remark'];
        $data['logo']                   = empty($message_data['logo']) ? '' : $message_data['logo'];
        $data['group_id']            = $message_data['group_id'];                    // 分组ID
        $data['tags']                = $message_data['tags'];
        $data['show_file_list']        = $message_data['show_file_list']; // 回显
        $data['tags']                = $data['tags'] ? explode(',', $data['tags']) : [];
        $data['is_exclusive']            = $message_data['is_exclusive'];

        // 组装联系我数据
        $type                        = $message_data['type'];                            // 联系方式类型,1-单人, 2-多人
        $scene                        = $message_data['scene'];                            // 场景，1-在小程序中联系，2-通过二维码联系

        $data['type']              = $type;  // 联系方式类型,1-单人, 2-多人  写入本地数据表

        $config['user']                = $message_data['user'];
        $config['user']                = $config['user'] ? explode(',', $config['user']) : [];
        $config['skip_verify']      = $message_data['skip_verify'] ? true : false;            // 外部客户添加时是否无需验证
        $config['is_exclusive']      = $message_data['is_exclusive'] ? true : false;            // 是否开启同一外部企业客户只能添加同一个员工
        $config['remark']            = $data['remark'];
        // 如果用户超过100个
        if (count($config['user']) > 100) return ['code' => 'error', 'msg' => '每个联系方式最多配置100个使用成员'];
        // 标签超过100个
        if (count($data['tags']) > 100) return ['code' => 'error', 'msg' => '标签超过100个，请减少标签数量'];
        // 转字符串
        $data['tags']                = implode(',', $data['tags']);


        //标签id如果不在标签表则报错提示

        if (!empty($data['tags'])) {
            $tempTagIds = explode(',', $data['tags']);
            foreach ($tempTagIds as $tempTagId) {
                if (! (new Tag())->query()->where('tag_id', $tempTagId)->exists()) {
                    return ['code' => 'error', 'msg' => '标签id=' . $tempTagId . '不存在，请检查！'];
                }
            }
        }


        //$data['user']				= implode(',',$config['user']); //这个数据放到openwork_contactway_qrcode_user表中处理 2025-03-31 modify by zengwei

        //渠道活码欢迎语
        $attachments            = $message_data['attachments']; //多附件json数组参数，最多9个

        if (!empty($attachments)) {
            //$attachments = json_decode($attachments,true);
            //如果attachments 不为空则需要判断attachments的内容和数量(不超过9个)
            $attachmentsCount = count($attachments);

            if ($attachmentsCount > 9) {
                return ['code' => 'error', 'msg' => '欢迎附件超过了9个，请减少数量'];
            }

            $returnMsg = $this->verifyAttachmentsData($attachments);

            if (!empty($returnMsg)) {
                return ['code' => 'error', 'msg' => $returnMsg];
            }
        }

        // 开始事务
        DB::connection('company')->beginTransaction();
        // 尝试执行
        try {
            // 获取实例
            $data['id']                = $Model->add($data);
            // 获取失败
            if (!$data['id'])        return ['code' => 'error', 'msg' => '创建失败'];

            //增加一个Qrcode和user的一对多的表
            if (!empty($config['user'])) {
                foreach ($config['user'] as $item) {

                    $qrcodeUserData = [
                        'qrcode_id' => $data['id'],
                        'user_id' => $item,
                    ];
                    $insertQrcodeUserData[] = $qrcodeUserData;
                }

                if (!empty($insertQrcodeUserData)) {
                    $qrcodeUserModel->batchCreate($insertQrcodeUserData);
                }
            }

            //欢迎语的数据组装
            $welcomeData['content'] = $message_data['content'];
            $welcomeData['corpid'] = $message_data['corpid'];
            $welcomeData['qrcodeid'] = $data['id'];
            //dd($welcomeData['content']);

            $welcomeData['attachments']        = json_encode($attachments, JSON_UNESCAPED_UNICODE);


            $qrcodeWelcomeModel->add($welcomeData);


            // 组合附加参数
            //$config['state']		= $message_data['state','t1='.$data['id']);
            $config['state']        = 't1&' . $data['id']; // 最多30个字符
            // 实例
            $work                    = OpenWork::getWork($data['corpid']);
            // 获取token
            $result                    = $work->contact_way->create($type, $scene, $config);
            // 接口返回失败的话
            if (!$result) {
                // 回滚事务
                DB::connection('company')->rollBack();
                // 提醒
                return                 ['code' => 'error', 'msg' => '企微接口返回失败'];
            }
            // 接口返回失败的话
            if ($result['errcode']) {
                // 回滚事务
                DB::connection('company')->rollBack();
                // 提醒
                return ['code' => 'error', 'msg' => OpenWork::getErrmsg($result['errcode'])];
            }
            // 二维码信息
            $data['qr_code']        = $result['qr_code'];
            // 返回结果
            $data['config_id']         = $result['config_id'];
            // 修改数据
            $result                    = $Model->edit($data['id'], $data);
            // 接口返回失败的话
            if (!$result) {
                // 回滚事务
                DB::connection('company')->rollBack();
                // 提醒
                return                 ['code' => 'error', 'msg' => '创建失败', 'data' => $data];
            }
            // 提交事务
            DB::connection('company')->commit();
            // 获取二维码保存到本地
			if ($data['qr_code'])  $Model->editQrcodeLogo($data['qr_code'], $companyId, $data['logo']);
            // 表单令牌
            return                    ['code' => 'success', 'msg' => '创建成功', 'data' => $data];
        } catch (\Throwable $th) {
            // 回滚事务
            DB::connection('company')->rollBack();
            // 提醒
            return                    ['code' => 'error', 'msg' => '创建异常，请重试', 'data' => ['error' => $th->getMessage()]];
        }
    }



    public function verifyAttachmentsData($attachments)
    {

        $msgTypes = ['image', 'link', 'miniprogram', 'video', 'file']; //msgType数组
        foreach ($attachments as $attachment) {
            if (isset($attachment['msgtype'])) {
                if (!in_array($attachment['msgtype'], $msgTypes)) {
                    return '消息类型不正确，请检查！';
                }

                if ($attachment['msgtype'] == 'image') {
                    if (empty($attachment['image']['media_id']) && empty($attachment['image']['pic_url'])) {
                        return '图片类型的附件，media_id和pic_url参数的值不能同时为空！';
                    }
                } elseif ($attachment['msgtype'] == 'link') {
                    if (empty($attachment['link']['title']) || empty($attachment['link']['url'])) {
                        return '图文消息类型的附件，title和url参数的值不能为空！';
                    }
                } elseif ($attachment['msgtype'] == 'miniprogram') {
                    if (
                        empty($attachment['miniprogram']['title']) || empty($attachment['miniprogram']['pic_media_id']) ||
                        empty($attachment['miniprogram']['appid']) || empty($attachment['miniprogram']['page'])
                    ) {
                        return '小程序类型的附件，title、pic_media_id、appid和page参数的值不能为空！';
                    }
                } elseif ($attachment['msgtype'] == 'video') {
                    if (empty($attachment['video']['media_id'])) {
                        return '视频类型的附件，media_id参数的值不能为空！';
                    }
                } elseif ($attachment['msgtype'] == 'file') {
                    if (empty($attachment['file']['media_id'])) {
                        return '文件类型的附件，media_id参数的值不能为空！';
                    }
                }
            }
        }
    }
}
