<?php

namespace App\Modules\WechatMaterial\Services;


use App\Modules\WechatMaterial\Models\BatchWechatMaterial;
use App\Modules\WechatMaterial\Models\WechatMaterial;
use App\Modules\WechatMaterial\Models\WechatMaterialSendMsg;

class WechatMaterialService
{
    
    public static function get_zs_wechat_material_list($request,$extra_param=[]){
        $channel_user_id = $extra_param['channel_user_id'];
        \Log::info('get_zs_wechat_material_list channel_user_id:'.$channel_user_id);
        
        return BatchWechatMaterial::get_zs_wechat_material_list($channel_user_id);
    }
    
    public static function del_zs_wechat_material($request,$extra_param=[]){
        $batch_id = $request->has('batch_id')?$request->get('batch_id'):'';
        
        $channel_user_id = $extra_param['channel_user_id'];
        \Log::info('del_zs_wechat_material:'.$batch_id.' channel_user_id:'.$channel_user_id);
        
        // 权限检测报错出来
        if(!self::check_batch_wechat_user_priv($channel_user_id,$batch_id)){
            return response()->error('BATCH_WECHAT_PRIV_ERROR');
        }
        
        $result = BatchWechatMaterial::del_zs_wechat_material($batch_id,$channel_user_id);
        
        // TODO循环删除appid的素材
        
        return $result;
    }
    
    
    public static function create_zs_wechat_material($request,$extra_param=[]){
        $content = $request->has('content')?$request->get('content'):'';
        $extend_html_content = $request->has('extend_html_content')?$request->get('extend_html_content'):'';
        $name = $request->has('name')?$request->get('name'):'';
        if(!is_array($content)){
            $content_items = json_decode($content);
        }else{
            $content_items = $content;
        }
        
        $channel_user_id = $extra_param['channel_user_id'];
        $distribution_channel_id = $extra_param['channel_id'];
        
        // 批量 
        $batchWechatMaterial = [
            'channel_user_id'=>$channel_user_id,
            'distribution_channel_id'=>$distribution_channel_id,
            'name'=>$name,
            'content'=>json_encode($content_items),
            'status'=>'init',
            'del_flag'=>0,
            'created_at'=>date('Y-m-d H:i:s'),
            'updated_at'=>date('Y-m-d H:i:s'),
        ];
        \Log::info('$create_zs_wechat_material:'.$name);
        \Log::info($batchWechatMaterial);
        
        $new_batchWechatMaterial = BatchWechatMaterial::firstOrCreate($batchWechatMaterial);
        $batch_id = isset($new_batchWechatMaterial->id)?$new_batchWechatMaterial->id:'';
        \Log::info('$new_batchWechatMaterial_batch_id:'.$batch_id);
        \Log::info($content_items);
        
//         单个映射素材表
        if(!empty($content_items)){
            foreach($content_items as $key=>$content_item){
                $sort_no = $key+1;
                $wechatMaterial = [
                    'batch_id'=>$batch_id,
                    'bid'=>isset($content_item[4]->bid)?$content_item[4]->bid:'',
                    'book_name'=>isset($content_item[5]->book_name)?$content_item[5]->book_name:'',
                    'title'=>isset($content_item[0]->title)?$content_item[0]->title:'',
                    'cover_url'=>isset($content_item[3]->image)?$content_item[3]->image:'',
                    'url'=>isset($content_item[2]->url)?$content_item[2]->url:'',
                    'desc'=>isset($content_item[1]->description)?$content_item[1]->description:'',
                    'content_mode'=>isset($content_item[6]->content_mode)?$content_item[6]->content_mode:'',
                    'content'=>isset($content_item[7]->content)?$content_item[7]->content:'',
                    'sort_no'=>$sort_no,
                    'created_at'=>date('Y-m-d H:i:s'),
                    'updated_at'=>date('Y-m-d H:i:s'),
                ];
                \Log::info('$wechatMaterial:');\Log::info($wechatMaterial);
    
                WechatMaterial::firstOrCreate($wechatMaterial);
            }
        }
        
        return $new_batchWechatMaterial;
        
    }
    
    public static function get_zs_wechat_batch_distribution_infos($request,$extra_param=[]){
        $batch_id = $request->has('batch_id')?$request->get('batch_id'):'';
        
        return WechatMaterialSendMsg::get_zs_wechat_batch_distribution_infos($batch_id);
    }
    
    
    public static function update_zs_wechat_material($request,$extra_param=[]){
        $batch_id = $id = $request->has('batch_id')?$request->get('batch_id'):'';
        $channel_user_id = $extra_param['channel_user_id'];
        \Log::info('update_zs_wechat_material:'.$id.' channel_user_id:'.$channel_user_id);
        
        if(!self::check_batch_wechat_user_priv($channel_user_id,$batch_id)){
            return response()->error('BATCH_WECHAT_PRIV_ERROR');
        }
        
        $content = $request->has('content')?$request->get('content'):'';
        if(!is_array($content)){
            $content_items = json_decode($content);
        }else{
            $content_items = $content;
        }
        $name = $request->has('name')?$request->get('name'):'';
        
        $updated_at = date('Y-m-d H:i:s');
        $content = json_encode($content_items);

        $base_data = compact('id','channel_user_id');
        $extra_data = compact('content','updated_at');
        \Log::info('update_zs_wechat_material:'.$id);
        
        BatchWechatMaterial::where($base_data)->update($extra_data);
        
        // 单个映射素材表
        if(!empty($content_items)){
            foreach($content_items as $key=>$content_item){
                $sort_no = $key+1;
                
                // 删除老的素材
                WechatMaterial::delByBatchId($id);
                
                $wechatMaterial = [
                    'batch_id'=>$batch_id,
                    'bid'=>isset($content_item[4]->bid)?$content_item[4]->bid:'',
                    'book_name'=>isset($content_item[5]->book_name)?$content_item[5]->book_name:'',
                    'title'=>isset($content_item[0]->title)?$content_item[0]->title:'',
                    'cover_url'=>isset($content_item[3]->image)?$content_item[3]->image:'',
                    'url'=>isset($content_item[2]->url)?$content_item[2]->url:'',
                    'desc'=>isset($content_item[1]->description)?$content_item[1]->description:'',
                    'content_mode'=>isset($content_item[6]->content_mode)?$content_item[6]->content_mode:'',
                    'content'=>isset($content_item[7]->content)?$content_item[7]->content:'',
                    'sort_no'=>$sort_no,
                    'created_at'=>date('Y-m-d H:i:s'),
                    'updated_at'=>date('Y-m-d H:i:s'),
                ];
                \Log::info('$wechatMaterial:');\Log::info($wechatMaterial);
                
                WechatMaterial::firstOrCreate($wechatMaterial);
            }
        }
        
        return true;
        
    }
    
    public static function set_wechat_material_batch_send_info($request,$extra_param=[]){
        $id = $request->has('batch_id')?$request->get('batch_id'):'';
        $send_time = $request->has('send_time')?$request->get('send_time'):'';
        $subscribe_time = $request->has('subscribe_time')?$request->get('subscribe_time'):'';
        $balance = $request->has('balance')?$request->get('balance'):'';
        $sex = $request->has('sex')?$request->get('sex'):'';
        $pay_type = $request->has('pay_type')?$request->get('pay_type'):'';
        $interaction_time = $request->has('interaction_time')?$request->get('interaction_time'):'';
//         $status = $request->has('status')?$request->get('status'):'';
        $is_all_user = $request->has('is_all_user')?$request->get('is_all_user'):'';
//         $del_flag = $request->has('del_flag')?$request->get('del_flag'):'';
        $channel_user_id = $extra_param['channel_user_id'];
        \Log::info('set_wechat_material_batch_send_info:'.$id.' channel_user_id:'.$channel_user_id);
        
        // 权限检测报错出来
        if(!self::check_batch_wechat_user_priv($channel_user_id,$batch_id)){
            return response()->error('BATCH_WECHAT_PRIV_ERROR');
        }
        
        $updated_at = date('Y-m-d H:i:s');
        \Log::info('set_wechat_material_batch_send_info:'.$id);
        
        $base_data = compact('id');
        $extra_data = compact('send_time', 'subscribe_time', 'balance', 'sex', 'pay_type', 'interaction_time', 'is_all_user','updated_at');
        \Log::info('set_wechat_material_batch_send_info:'.$id);
        
        return BatchWechatMaterial::where($base_data)->update($extra_data);

    }
    
    /**
     * 同步素材到公众号
     * @param unknown $request
     * @param array $extra_param
     */
    public static function sync_zs_wechat_material($request,$extra_param=[]){
        $batch_id = $id = $request->has('batch_id')?$request->get('batch_id'):'';
        $distribution_appids = $request->has('distribution_appids')?$request->get('distribution_appids'):'';
        
        $channel_user_id = $extra_param['channel_user_id'];
        \Log::info('sync_zs_wechat_material:'.$id.' channel_user_id:'.$channel_user_id);
        
        if(!self::check_batch_wechat_user_priv($channel_user_id,$batch_id)){
            return response()->error('BATCH_WECHAT_PRIV_ERROR');
        }
        
        // 获取素材 
        $batch_wechat_material = BatchWechatMaterial::find($batch_id);
        $batch_wechat_material_contents = WechatMaterialService::getWeChatMaterials($batch_id);
        \Log::info('batch_wechat_material');\Log::info($batch_wechat_material);
        \Log::info('batch_wechat_material_contents');\Log::info($batch_wechat_material_contents);
        $distribution_appids = json_decode($distribution_appids);
        foreach($distribution_appids as $distribution_channel_id=>$appids){
            foreach($appids as $appid){
                try{
                    // 把任务扔队列处理
                    \Log::info('sync_zs_wechat_material:'.$distribution_channel_id.' appid:'.$appid);
                    $wechatMaterialSendMsg = [
                        'batch_id'=>$batch_id,
                        'appid'=>$appid,
                        'distribution_channel_id'=>$distribution_channel_id,
                        'created_at'=>date('Y-m-d H:i:s'),
                        'updated_at'=>date('Y-m-d H:i:s')
                    ];
                    WechatMaterialSendMsg::firstOrCreate($wechatMaterialSendMsg);
                    
                    $queue_param = [
                        'action_type'=>'sync_zs_wechat_material',
                        'batch_wechat_material'=>$batch_wechat_material,
                        'batch_wechat_material_contents'=>$batch_wechat_material_contents,
                    ];
                    ActionService::PushActionToQueue($queue_param);
                }catch(\exception $e){
                    \Log::info('sync_zs_wechat_material_ept:'.$e->getMessage());
                }
                
            }
        }

    }
    
    /**
     * 检查权限
     * @param unknown $request
     * @param array $extra_param
     */
    public static function check_batch_wechat_user_priv($channel_user_id,$batch_id){
        $checkRes = BatchWechatMaterial::get_zs_wechat_material($batch_id,$channel_user_id);
        if(empty($checkRes)){
            return false;
        }else{
            return true;
        }
    }
    
    /**
     * 获取素材内容
     * @param unknown $request
     * @param array $extra_param
     */
    public static function getWeChatMaterials($batch_id){
        return WechatMaterial::getWeChatMaterials($batch_id);
    }


    public static function delWechatMaterialById($id){
        try{

            $queue_param = [
                'action_type'=>'del_wechat_material',
                'wechat_material_id'=>$id,
            ];
            ActionService::PushActionToQueue($queue_param);
        }catch(\exception $e){
            \Log::info('delWechatMaterial:'.$e->getMessage());
        }
        return 1;

//        return WechatMaterial::where('id',$id)->update(
//            [
//                'del_flag'=>1,
//                'updated_at'=>date('Y-m-d H:i:s')
//            ]
//        );
    }

    public static function deleteBatchSendWechatMaterial($id){
        try{

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

    }


}