<?php

namespace App\Modules\WechatMaterial\Services;


use App\Http\Controllers\WechatController;
use App\Modules\WechatMaterial\Models\BatchWechatMaterial;
use App\Modules\WechatMaterial\Models\WechatMaterial;
use App\Modules\WechatMaterial\Models\WechatMaterialSendMsg;
use App\Modules\WechatMaterial\Models\WechatOfficialAccountMaterialSendStatistics;
use DB;

class WechatMaterialSendMsgService
{

    public static function get_batch_send_wechat_material_list($params, $orderBy = [])
    {
        $res = WechatMaterial::leftJoin('batch_wechat_materials', 'batch_wechat_materials.id', 'wechat_materials.batch_id')
            ->leftJoin('wechat_material_send_msgs', 'batch_wechat_materials.id', 'wechat_material_send_msgs.batch_id')
            ->select(
                'wechat_material_send_msgs.distribution_channel_id',
                'wechat_material_send_msgs.appid',
                'wechat_material_send_msgs.name',
                'wechat_material_send_msgs.status',
                'wechat_material_send_msgs.send_user_num',
                'wechat_material_send_msgs.receive_user_num',
                'wechat_material_send_msgs.first_day_material_uv',
                'wechat_material_send_msgs.first_day_url_uv',
                'wechat_material_send_msgs.batch_id',
                'wechat_material_send_msgs.id',
                'wechat_material_send_msgs.created_at as msg_created_at',
                'wechat_material_send_msgs.updated_at as msg_updated_at',
                'batch_wechat_materials.subscribe_time',
                'batch_wechat_materials.balance',
                'batch_wechat_materials.content',
                'batch_wechat_materials.sex',
                'batch_wechat_materials.send_time',
                'batch_wechat_materials.pay_type',
                'batch_wechat_materials.interaction_time',
                'batch_wechat_materials.is_all_user',
                'batch_wechat_materials.created_at as batch_created_at',
                'batch_wechat_materials.updated_at as batch_updated_at',
                'wechat_materials.title',
                'wechat_materials.book_name'
            )
            ->where('wechat_material_send_msgs.del_flag', 0);
        if (isset($params['name']) && $params['name']) {
            $res->where('wechat_material_send_msgs.name', $params['name']);
        }
        if (isset($params['distribution_channel_id']) && $params['distribution_channel_id']) {
            $res->where('wechat_material_send_msgs.distribution_channel_id', $params['distribution_channel_id']);
        }
        if (isset($params['status']) && $params['status']) {
            $res->where('wechat_material_send_msgs.status', $params['status']);
        }
        if (isset($params['begin_time']) && $params['begin_time']) {

        }
        if (isset($params['end_time']) && $params['end_time']) {

        }
        if ($orderBy) {
            $res->orderBy($orderBy['field'], $orderBy['rule']);
        } else {
            $res->orderBy('batch_wechat_materials.send_time', 'desc');

        }
        return $res->paginate();
    }

    public static function preview_wechat_material($batch_id, $user_id)
    {
        try {

            $queue_param = [
                'batch_id' => $batch_id,
                'user_id'  => $user_id,
            ];
            ActionService::PushActionToQueue($queue_param);
        } catch (\exception $e) {
            \Log::info('preview_wechat_material:' . $e->getMessage());
        }
        return 1;
    }


    /**
     * @return mixed
     */
    public static function update_wechat_material_send_msg_info($param)
    {
        try {
            if(isset($param->MsgID) && !empty($param->MsgID)){
                \Log::info('update_wechat_material_send_msg_info:'.$param->MsgID.' incre:'.$param->SentCount);
                DB::connection('api_mysql')
                ->table('wechat_material_send_msgs')->where('wechat_msg_id',$param->MsgID)->increment('receive_user_num',$param->SentCount);
            }
        } catch (\exception $e) {
            \Log::info('update_wechat_material_send_msg_info_ept:' . $e->getMessage());
        }
        return true;
    }
    
    /**
     * @return mixed
     */
    public static function getUnCollectedList()
    {
        try {
            $result = WechatMaterialSendMsg::getUnCollectedList();
        } catch (\exception $e) {
            \Log::info('preview_wechat_material:' . $e->getMessage());
        }
        return $result;
    }

    /**
     * 更新首日图文阅读 跨度为1天
     * @param $queryDay 查询起始时间 2014-12-08
     */
    public static function updateFirstDayMaterialUV($queryDay)
    {
        $list = WechatMaterialSendMsgService::getUnCollectedList();
        myLog('SyncWechatMaterialStatistics')->notice('需要更新的记录：' . json_encode($list));
        foreach ($list as $wechatMaterialItem) {
            $WechatController = new WechatController($wechatMaterialItem->appid);
            $stats            = $WechatController->app->stats;
            $r                = $stats->articleTotal($queryDay, $queryDay);

            if ($r && isset($r['list'])) {

                //获取消息内记录明细
                $materialList = WechatMaterialSendMsg::get_infos_by_batch_id($wechatMaterialItem->batch_id);

                $list = $r['list'];
                foreach ($list as $item) {
                    if (preg_match('/' . $wechatMaterialItem->msg_data_id . '_(\d+)/', $item['msgid'], $match)) {
                        $sequence = (int)$match[1];


                        foreach ($item['details'] as $k => $detail) {
                            $send_count         = $detail['target_user'];
                            $int_page_read_user = $detail['int_page_read_user'];
                            $ori_page_read_user = $detail['ori_page_read_user'];
                            //首日
                            if ($queryDay == $detail['stat_date']) {
                                $messageItem = $materialList->where('sort_no', $sequence)->first();
                                if (isset($messageItem)) {
                                    WechatOfficialAccountMaterialSendStatistics::updateOrCreate([
                                                                                                    'batch_id'              => $wechatMaterialItem->batch_id,
                                                                                                    'appid'                 => $wechatMaterialItem->appid,
                                                                                                    'wechat_material_id'    => $messageItem->id,
                                                                                                    'first_day_material_uv' => $int_page_read_user,
                                                                                                ]);
                                }
                            }
                        }
                    }
                }
            }


        }

    }
}