<?php

namespace App\Jobs\OpenWork\Statistics;

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\Servers\DB\DbService;
use App\Models\OpenWork\job\Records;
use App\Facades\Servers\Logs\Log;
use App\Models\OpenWork\CustomerForm\CustomerFormSubmit as CustomerFormSubmitModel;
use App\Models\OpenWork\CustomerForm\CustomerFormClickStatistics as CustomerFormClickStatisticsModel;
use Illuminate\Support\Facades\Cache;


/**
 * SCRM 自定义表单数据总览
 * @author  唐远望
 * @version  1.0
 * @date   2025-08-20
 */
class CustomFormOverviewJobs 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 {
            $corpId = $this->message_data['corpid'];
            (new DbService())->getConnectionNameByCorpId($corpId);
            // 创建任务记录
            $this->Records = Records::create([
                'job_id' => $corpId . '_CustomFormOverviewJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);
            $corpid = $this->message_data['corpid'];
            $id = $this->message_data['form_id'];
            $start_time = $this->message_data['start_time'];
            $end_time = $this->message_data['end_time'];
            $CustomerFormSubmitModel = new CustomerFormSubmitModel();
            $CustomerFormClickStatisticsModel = new CustomerFormClickStatisticsModel();
            //查询今日提交次数
            $today_submit_num          = $CustomerFormSubmitModel->where(['form_id' => $id])->where('insert_time', '>=', $start_time)->where('insert_time', '<=', $end_time)->count();
            //查询今日点击人数
            $today_click_num           = $CustomerFormClickStatisticsModel->where(['form_id' => $id])->where('insert_time', '>=', $start_time)->where('insert_time', '<=', $end_time)->distinct('external_userid')->count();
            //查询今日填写人数
            $today_fill_num            = $CustomerFormSubmitModel->where(['form_id' => $id])->where('insert_time', '>=', $start_time)->where('insert_time', '<=', $end_time)->distinct('external_userid')->count();
            //查询今日提交人数
            $today_submit_user_num     = $CustomerFormSubmitModel->where(['form_id' => $id])->where('insert_time', '>=', $start_time)->where('insert_time', '<=', $end_time)->distinct('external_userid')->count();
            //查询总提交次数
            $total_submit_num          = $CustomerFormSubmitModel->where(['form_id' => $id])->count();
            //查询总点击人数
            $total_click_num           = $CustomerFormClickStatisticsModel->where(['form_id' => $id])->distinct('external_userid')->count();
            //查询总填写人数
            $total_fill_num            = $CustomerFormSubmitModel->where(['form_id' => $id])->distinct('external_userid')->count();
            //查询总提交人数
            $total_submit_user_num     = $CustomerFormSubmitModel->where(['form_id' => $id])->distinct('external_userid')->count();
            //计算总填写率
            $total_fill_rate           = $total_fill_num > 0 && $total_click_num > 0 ? round($total_fill_num / $total_click_num * 100, 2) : 0;
            //计算总提交率
            $total_submit_rate         = $total_submit_num > 0 && $total_click_num > 0 ? round($total_submit_num / $total_click_num * 100, 2) : 0;

            $data = [
                'today_submit_num'         => $today_submit_num, //今日提交次数
                'today_click_num'          => $today_click_num, //今日点击人数
                'today_fill_num'           => $today_fill_num, //今日填写人数
                'today_submit_user_num'    => $today_submit_user_num, //今日提交人数
                'total_submit_num'         => $total_submit_num, //总提交次数
                'total_click_num'          => $total_click_num, //总点击人数
                'total_fill_num'           => $total_fill_num, //总填写人数
                'total_submit_user_num'    => $total_submit_user_num, //总提交人数
                'total_fill_rate'          => $total_fill_rate, //总填写率
                'total_submit_rate'        => $total_submit_rate, //总提交率
            ];
            //写入缓存
            Cache::forever('custom_form_statistics_overview_'. $id. '_'. $corpid, $data);//每次查询完毕后覆盖缓存

            //删除任务记录
            $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();
        }
    }
}
