<?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;


/**
 * SCRM 编辑渠道活码
 * @author  唐远望
 * @version  1.0
 * @date   2025-08-15
 */
class ChannelActiveCodeEditJobs 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 . '_ChannelActiveCodeEditJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);
            $result = $this->edit($this->message_data);
            if (isset($result['code']) && $result['code'] == 'error') {
                Log::info('job_error', '渠道活码编辑任务失败', ['data' => $this->message_data, '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]);
        // 失败处理...
        if ($this->Records) {
            $this->Records->delete();
        }
    }


    /**	
     * 编辑配置   /openwork/contactway_qrcode/edit
     * 
     * 
     */
    public function edit($message_data)
    {
        $Model = new QrcodeModel();
        $qrcodeUserModel = new QrcodeUser();
        $qrcodeWelcomeModel = new QrcodeWelcome();
        // 接收参数
        $id                            = $message_data['id'];
        $companyId                     = $message_data['company_id'];
        // 获取实例
        $oldData                    = $Model->query()->find($id);
        // 获取失败
        if (!$oldData)            return ['code' => 'error', 'msg' => '查无数据'];
        // 修改
        $data['remark']                = $message_data['remark'];
        $data['logo']                   = empty($message_data['logo']) ? '' : $message_data['logo'];
        //活码分组，有传就修改，没传不修改
        if (array_key_exists('group_id', $message_data)) {
            $data['group_id']            = $message_data['group_id']; // 分组ID
        }
        $old_tags = explode(',', $oldData['tags']);
        $new_tags ='';
        //标签，有传就修改，没传不修改
        // if (array_key_exists('tags', $message_data)) {
        //     $data['tags']                = $message_data['tags'];
        //     $data['tags']                = $data['tags'] ? explode(',', $data['tags']) : [];
        //     // 转字符串
        //     $data['tags']                = implode(',', $data['tags']);
        // }
        if (array_key_exists('del_tags', $message_data) && array_key_exists('add_tags', $message_data)) {
            if ($message_data['del_tags'] != '' && $message_data['add_tags'] != '') {
                //如果删除标签在$old_tags旧标签中，则移除
                $del_tags = explode(',', $message_data['del_tags']);
                $tags_array = array_intersect($old_tags, $del_tags); //交集
                $old_tags = array_diff($old_tags, $tags_array); //差集
                //如果新增标签已经在$old_tags标签中，则不再添加
                $add_tags = explode(',', $message_data['add_tags']);
                //如果删除的标签在新增标签中，则移除
                $tags_array = array_intersect($add_tags, $del_tags); //交集
                $add_tags = array_diff($add_tags, $tags_array); //差集
                $tags_array = array_merge($add_tags, $old_tags); //合并
                $tags_array = array_filter($tags_array); //去除空值
                $new_tags = implode(',', array_unique($tags_array)); //去重
            }
        } else if (array_key_exists('add_tags', $message_data)) { //新增标签业务处理
            if ($message_data['add_tags'] != '') {
                //如果新增标签已经在$old_tags旧标签中，则不再添加
                $add_tags = explode(',', $message_data['add_tags']);
                $tags_array = array_merge($add_tags, $old_tags); //合并
                $tags_array = array_filter($tags_array); //去除空值
                $new_tags = implode(',', array_unique($tags_array)); //去重
            }
        } else if (array_key_exists('del_tags', $message_data)) { //删除标签业务处理
            if ($message_data['del_tags'] != '') {
                //如果删除标签在$old_tags旧标签中，则移除
                $del_tags = explode(',', $message_data['del_tags']);
                $tags_array = array_intersect($old_tags, $del_tags); //交集
                $tags_array = array_filter($tags_array); //去除空值
                $new_tags = implode(',', array_diff($old_tags, $tags_array)); //差集
            }
        }
        if($new_tags != ''){
            $data['tags'] = $new_tags;
        }
        //接待人员，有传就修改，不传不修改
        if (array_key_exists('user', $message_data)) {
            $config['user']                = $message_data['user'];
            $config['user']                = $config['user'] ? explode(',', $config['user']) : [];
        }
        if (array_key_exists('show_name', $message_data)) {
            $data['show_name']            = $message_data['show_name']; // 回显
        }
        if (array_key_exists('show_file_list', $message_data)) {
            $data['show_file_list']            = $message_data['show_file_list']; // 回显
        }
        //是否无需验证，有传就修改，不传不修改
        if (array_key_exists('skip_verify', $message_data)) {
            $config['skip_verify']      = $message_data['skip_verify'] ? true : false;            // 外部客户添加时是否无需验证
        }
        $config['remark']            = $data['remark'];
        // 企业联系方式的配置id
        $configId                    = $oldData['config_id'];
        // 组合附加参数
        //$config['state']			= $message_data['state','t1&'.$oldData['id']);
        $config['state']            = 't1&' . $oldData['id'];
        // 接收参数
        $data['corpid']             = $oldData['corpid'];
        // 开始事务
        DB::connection('company')->beginTransaction();
        // 尝试执行
        try {
            // 实例
            $work                    = OpenWork::getWork($data['corpid']);
            // 获取token
            $result                    = $work->contact_way->update($configId, $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'])];
            }
            // 修改数据
            $result                    = $Model->edit($id, $data);
            // 接口返回失败的话
            if (!$result) {
                // 回滚事务
                DB::connection('company')->rollBack();
                // 提醒
                return  ['code' => 'error', 'msg' => '编辑失败', 'data' => $data];
            }
            $userIds = $qrcodeUserModel->query()->where([['qrcode_id', '=', $id]])->pluck('user_id')->toArray();
            if (array_key_exists('user', $message_data)) {
                $intersectUserIds = array_intersect($config['user'], $userIds);
                foreach ($userIds as $userId) {
                    if (!in_array($userId, $intersectUserIds)) {
                        $qrcodeUserModel->remove($id, $userId); //删除
                    }
                }
                foreach ($config['user'] as $value) {
                    if (!in_array($value, $intersectUserIds)) {
                        $insertQrcodeUserData['qrcode_id'] = $id;
                        $insertQrcodeUserData['user_id'] = $value;
                        $qrcodeUserModel->add($insertQrcodeUserData);
                    }
                }
            }
            $welcomeData['corpid']      = $message_data['corpid'];
            $welcomeData['qrcodeid']    = $id;
            $welcomeData['update_time'] = time();
            //附件内容，有传就修改，不传不修改
            if (array_key_exists('attachments', $message_data)) {
                $attachments            = $message_data['attachments']; //多附件json数组参数，最多9个
                $welcomeData['attachments']        = json_encode($attachments, JSON_UNESCAPED_UNICODE);
            }
            //欢迎语内容，有传就修改，不传不修改
            if (array_key_exists('content', $message_data)) {
                $welcomeData['content']     = $message_data['content']; //欢迎语内容
            }
            $qrcodeWelcomeModel->query()->where('qrcodeid', $id)->update($welcomeData);
            // 提交事务
            DB::connection('company')->commit();
            // 获取二维码保存到本地
            if ($oldData['qr_code'] && $data['logo'] != $oldData['logo'])  $Model->editQrcodeLogo($oldData['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()]];
        }
        // 返回结果
        return         ['code' => 'success', 'msg' => '获取', 'data' => $oldData];
    }
}