<?php

namespace App\Jobs\Company\Custom;

use App\Servers\DB\DbService;
use App\Models\OpenWork\job\Records;
use App\Facades\Servers\Logs\Log;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\Company\Custom\Tag as TagModel;
use App\Models\Company\Corp\AuthCorp as AuthCorpmodel;
use App\Servers\OpenWork\External\TagLogService;
use App\Models\Manager\CustomExternal;
use App\Models\Company\Corp\FollwUser as ScrmFollwUserModel;
use App\Models\Company\Corp\TagRelation as TagRelationModel;
use App\Jobs\OpenWork\External\UserTagCacheJobs;



/**
 * SASS用户标签队列
 * @author 唐远望
 * @version 1.0
 * @date   2025-08-05
 * 
 */
class TagJobs 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 . '_TagJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);
            $operation_type = $this->message_data['operation_type'];
            if ($operation_type == 'add_tag') {
                (new TagModel())->addTag_batch($this->message_data);
            }
            if ($operation_type == 'del_tag') {
                (new TagModel())->removeTag_batch($this->message_data);
            }
            //同步标签更新到SCRM
            $this->removeTag_batch($companyId, $this->message_data, $operation_type);
            //更新用户标签缓存
            $custom_list = $this->message_data['custom_list'];
            foreach ($custom_list as $key => $custom_uid) {
                $message_data = [
                    'corpid' => '',
                    'custom_uid' => $custom_uid,
                    'external_userid' =>'',
                    'company_id' => $companyId,
                ];
                UserTagCacheJobs::dispatch($message_data);
                // UserTagCacheJobs::dispatchSync($message_data);
            }
            //删除任务记录
            $this->Records->delete();
        } catch (\Exception $e) {
            // 失败处理...
            if ($this->Records) {
                $this->Records->delete();
            }
            Log::info('job_error', '更新SASS用户标签信息失败',['error' => $e->getMessage(),'data'=>$this->message_data]);
        }
    }


    /**
     * 同步开关校验
     * @author 唐远望
     * @version 1.0
     * @date 2025-09-26
     */
    public function check_sync_switch($company_id)
    {
        if ($company_id == '') {
            return false;
        }
        $data = [];
        $AuthCorpmodel = new AuthCorpmodel();
        $authcorp = $AuthCorpmodel->where([['company_id', '=', $company_id]])->first();
        if (!$authcorp) {
            return false;
        }
        $data = [
            'company_id' => $authcorp->company_id,
            'corpid' => $authcorp->corpid,
        ];
        return $data;
    }


    /**
     * 批量客户标签操作同步到SCRM
     * @author 唐远望
     * @version 1.0
     * @date   2025-09-27
     * @param array $all_data
     * @return void
     */
    public function removeTag_batch($company_id, $message_data, $operation_type)
    {
        $authcorp = $this->check_sync_switch($company_id);
        if (!$authcorp) return false;
        $company_id = $authcorp['company_id'];
        $corpid = $authcorp['corpid'];
        $custom_list = $message_data['custom_list'];
        $CustomExternal = new CustomExternal();
        $ScrmFollwUserModel = new ScrmFollwUserModel();
        $TagLogService = new TagLogService();
        $TagRelationModel = new TagRelationModel();
        //查询本地是否存在该标签的映射关系ID
        $local_tag_relation_ids = $TagRelationModel->where('company_id', $company_id)->get(['id', 'scrm_tag_id', 'sass_tag_id'])->toarray();
        $local_tag_relation = [];
        if (empty($local_tag_relation_ids)) {
            return true;
        }
        foreach ($local_tag_relation_ids as $key =>  $local_tag_relation_data) {
            $sass_tag_id = $local_tag_relation_data['sass_tag_id'];
            $local_tag_relation[$sass_tag_id] = $local_tag_relation_data['scrm_tag_id'];
        }

        $externalUser_datas =  $CustomExternal->where('corpid', $corpid)->whereIn('custom_uid', $custom_list)->where('status', 1)->pluck('external_userid')->toArray();
        if (empty($externalUser_datas)) {
            Log::info('job_error', '商户批量打标签同步客户标签队列-没有外部联系客服', ['data' => $corpid, 'custom_uid' => $custom_list]);
            return true;
        }
        //查询对应的跟进客服
        $follow_tag_data = $ScrmFollwUserModel->join('openwork_contact_user', function ($join) {
            $join->on('openwork_external_follow.follow_userid', '=', 'openwork_contact_user.userid');
        })->where(['openwork_external_follow.corpid' => $corpid, 'openwork_external_follow.status' => '0', 'openwork_contact_user.status' => '1'])
            ->whereIn('openwork_external_follow.external_userid', $externalUser_datas)
            ->get(['openwork_external_follow.id', 'openwork_external_follow.status', 'openwork_external_follow.external_userid', 'openwork_external_follow.follow_userid']);

        if (empty($follow_tag_data)) {
            Log::info('job_error', '商户批量打标签同步客户标签队列-跟进人获取同步失败', ['data' => $corpid, 'external_userid' => $externalUser_datas]);
            return true;
        }
        $user_list = [];
        foreach ($follow_tag_data as $key => $value) {
            $user_list[$key] = [
                'extid' => $value['external_userid'],
                'userid' => $value['follow_userid'],
            ];
        }
        $add_tag = [];
        $remove_tag = [];
        if ($operation_type == 'del_tag') {
            $remove_tag_data = $message_data['tag_id_list'];
            if (!empty($remove_tag_data)) {
                foreach ($remove_tag_data as $tag_id) {
                    //查询本地是否存在该标签的映射关系ID
                    if (!array_key_exists($tag_id, $local_tag_relation)) {
                        continue;
                    }
                    $remove_tag[] = $local_tag_relation[$tag_id];
                }
            }
        }
        if ($operation_type == 'add_tag') {
            $add_tag_data = $message_data['tag_id_list'];
            if (!empty($add_tag_data)) {
                foreach ($add_tag_data as $tag_id) {
                    //查询本地是否存在该标签的映射关系ID
                    if (!array_key_exists($tag_id, $local_tag_relation)) {
                        continue;
                    }
                    $add_tag[] = $local_tag_relation[$tag_id];
                }
            }
        }
        if ($add_tag || $remove_tag) {
            if (!empty($add_tag)) {
                //将数组转换成字符串
                $add_tag = implode(',', $add_tag);
            } else {
                $add_tag = '';
            }
            if (!empty($remove_tag)) {
                //将数组转换成字符串
                $remove_tag = implode(',', $remove_tag);
            } else {
                $remove_tag = '';
            }
            //查询用户所有跟进人列表
            $TagLogService->batchEdit_user_tags($corpid, $user_list, $add_tag, $remove_tag, false); //同步到SCRM（无需通知SASS）
        }
    }

    public function failed(\Throwable $exception)
    {
        Log::info('job_error', '更新SASS用户标签信息完全失败', ['error' => $exception,'data'=>$this->message_data]);
        // 失败处理...
        if ($this->Records) {
            $this->Records->delete();
        }
    }
}
