<?php

namespace App\Http\Controllers\Manage\OfficialAccount;

use App\Http\Controllers\Manage\BaseController;
use App\Modules\OfficialAccount\Services\CustomMsgService;
use App\Modules\OfficialAccount\Services\BatchCustomMsgService;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
use App\Modules\OfficialAccount\Services\OfficialAccountService;
use App\Modules\OfficialAccount\Models\OfficialAccount;
use App\Http\Controllers\Manage\OfficialAccount\Transformers\CustomSendMsgsTransformers;
use App\Http\Controllers\Manage\OfficialAccount\Transformers\BatchCustomSendMsgsTransformers;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use Hashids;
use App\Modules\Book\Services\BookConfigService;
use App\Modules\Statistic\Services\SendStatistics;


class CustomMsgController extends BaseController
{
    
    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/customSendMsgsByTrusteeship 全部发送客服消息列表获取
     * @apiGroup OfficialAccount
     * @apiName customSendMsgsByTrusteeship
     */
    function  customSendMsgsByTrusteeship(Request $request) {
    	\Log::info('customSendMsgsByTrusteeship');

    	$param = array();
    	$param['trusteeship'] = 1;
    	$customMsgServices = CustomMsgService::customSendMsgsByTrusteeship($param);
    	
    	// 统计
    	foreach($customMsgServices as $key=>$customMsgService){
    		$temp_customMsgService = $customMsgService;
    		$customMsgService->pv = '';
    		$customMsgService->uv = '';
    		$customMsgService->total_order_num = '';
    		$customMsgService->suc_order_num = '';
    		$customMsgService->order_suc_rate = '';
    		$pv = $uv = $total_order_num = $suc_order_num = $order_suc_rate = array();
    		for($i=1;$i<=4;$i++){
    			$temp_statistics= $this->get_custom_msg_statistics($temp_customMsgService,$i);
    			$pv[$i] = $temp_statistics->pv;
    			$uv[$i] = $temp_statistics->uv;
    			$total_order_num[$i] = $temp_statistics->total_order_num;
    			$suc_order_num[$i] = $temp_statistics->suc_order_num;
    			$order_suc_rate[$i] = $temp_statistics->order_suc_rate;
    			$success_order_sum[$i] = $temp_statistics->success_order_sum;
    		}
    		
    		// 解析bid,非贪婪匹配
    		$matches = array();
    		preg_match_all('/bid=(.*?)&cid/', $customMsgService->content, $matches);
    		$bids = isset($matches[1])?$matches[1]:array();
    		$simple_bids = $book_names = array();
    		$j = 1;
    		if(!empty($bids)){
    			foreach($bids as $bid){
    				$simple_bid = Hashids::decode($bid);
    				if(isset($simple_bid[0]) && !empty($simple_bid[0])){
    					$simple_bids[$j] = $simple_bid[0];
    					$book = BookConfigService::getBookById($simple_bid[0]);
    					$book_names[$j] = isset($book->book_name)?$book->book_name:'';
    					$j++;
    				}
    			}
    		}
    		
    		$customMsgService->bids = json_encode($simple_bids);
    		$customMsgService->book_names = json_encode($book_names);
    		$customMsgService->pv = json_encode($pv);
    		$customMsgService->uv = json_encode($uv);
    		$customMsgService->total_order_num = json_encode($total_order_num);
    		$customMsgService->suc_order_num = json_encode($suc_order_num);
    		$customMsgService->order_suc_rate = json_encode($order_suc_rate);
    		$customMsgService->success_order_sum = json_encode($success_order_sum);
    		// 公众号名称
    		$official_account = OfficialAccount::officialAccountByAppid($customMsgService->appid);
    		$customMsgService->official_account_name = isset($official_account->nickname)?$official_account->nickname:'';

    		$customMsgServices[$key] = $customMsgService;
    	}
    
    	if (!empty($customMsgServices)) {
    
    		return response()->pagination(new CustomSendMsgsTransformers(), $customMsgServices);
    	}else{
    
    		return response()->success(['data'=>0]);
    	}
    
    }
    
    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/customSendMsgsByTrusteeshipAndBacthNo 发送客服消息列表获取
     * @apiGroup OfficialAccount
     * @apiName customSendMsgsByTrusteeshipAndBacthNo
     * @apiParam {String}  batch_no 批次id.
     */
    function  customSendMsgsByTrusteeshipAndBacthNo(Request $request) {
    	$batch_no = $request->has('batch_no') ? $request->input('batch_no') : '';
    	
    	if(empty($batch_no)) {
    	
    		return response()->error("PARAM_EMPTY");
    	}
    	$param = array();
    	$param['trusteeship'] = 1;
    	$param['batch_no'] = $batch_no;
    	$customMsgService = CustomMsgService::customSendMsgsByTrusteeshipAndBacthNo($param);
    
    	if (!empty($customMsgService)) {
    
    		return response()->collection(new CustomSendMsgsTransformers(), $customMsgService);
    	}else{
    
    		return response()->success(['data'=>0]);
    	}
    
    }
    
    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/batchCustomMsgsList 获取批次客服消息列表
     * @apiGroup OfficialAccount
     * @apiName batchCustomMsgsList
     */
    function  batchCustomMsgsList(Request $request) {
    	
    	\Log::info('batchCustomMsgsList_start:');
    	$batchCustomMsgs = BatchCustomMsgService::batchCustomMsgList();
    	\Log::info($batchCustomMsgs);
    	foreach($batchCustomMsgs as $batch_key=>$batchCustomMsg){
    		// 得到渠道列表
    		$param = array();
    		$param['trusteeship'] = 1;
    		$param['batch_no'] = $batchCustomMsg->id;
    		\Log::info('batchCustomMsgsList:id:'.$batchCustomMsg->id);
    		$child_custom_msgs = CustomMsgService::customSendMsgsByTrusteeshipAndBacthNo($param);
    		
    		$pv = $uv = $pay_user_num = $total_order_num = $suc_order_num = $order_suc_rate = $success_order_sum = array();
    		$simple_bids = $book_names = array();
    		// 子渠道汇总，统计到每本书的级别
    		foreach($child_custom_msgs as $key=>$customMsgService){
//     			\Log::info('key:'.$key);
    			$temp_customMsgService = $customMsgService;
    			for($i=1;$i<=4;$i++){
    				$temp_statistics= $this->get_custom_msg_statistics($temp_customMsgService,$i);
    				// init
    				if(!isset($pv[$i])) {
    					$pv[$i] = $uv[$i] = $pay_user_num[$i] = $total_order_num[$i] = $suc_order_num[$i]=$order_suc_rate[$i]=$success_order_sum[$i]=0;
    				}
    				$pv[$i] += $temp_statistics->pv;
    				$uv[$i] += $temp_statistics->uv;
    				$pay_user_num[$i] += $temp_statistics->pay_user_num;
    				$total_order_num[$i] += $temp_statistics->total_order_num;
    				$suc_order_num[$i] += $temp_statistics->suc_order_num;
    				$order_suc_rate[$i] += $temp_statistics->order_suc_rate;
    				$success_order_sum[$i] += $temp_statistics->success_order_sum;
    				
    				break;
    			}
    			// 同1批次，内容一致
    			if($key == 0){
    				\Log::info('key0');
//     				\Log::info($customMsgService);
    				// 解析bid,非贪婪匹配
    				$matches = array();
    				preg_match_all('/bid=(.*?)&cid/', $customMsgService->content, $matches);
    				$bids = isset($matches[1])?$matches[1]:array();
    				$j = 1;
    				if(!empty($bids)){
    					foreach($bids as $bid){
    						$simple_bid = Hashids::decode($bid);
    						if(isset($simple_bid[0]) && !empty($simple_bid[0])){
    							$simple_bids[$j] = $simple_bid[0];
    							$book = BookConfigService::getBookById($simple_bid[0]);
    							$book_names[$j] = isset($book->book_name)?$book->book_name:'';
    							$j++;
    						}
    					}
    				}
    			}

    			$batchCustomMsg->user_num += $customMsgService->user_num;
    		}
    		
    		$batchCustomMsg->pv = json_encode($pv);
    		$batchCustomMsg->uv = json_encode($uv);
    		$batchCustomMsg->pay_user_num = json_encode($pay_user_num);
    		$batchCustomMsg->total_order_num = json_encode($total_order_num);
    		$batchCustomMsg->suc_order_num = json_encode($suc_order_num);
    		$batchCustomMsg->order_suc_rate = json_encode($order_suc_rate);
    		$batchCustomMsg->success_order_sum = json_encode($success_order_sum);
    		$batchCustomMsg->bids = json_encode($simple_bids);
    		$batchCustomMsg->book_names = json_encode($book_names);
    		
    		$batchCustomMsgs[$batch_key] = $batchCustomMsg;
    		
    	}
    	if (!empty($batchCustomMsgs)) {
    		return response()->pagination(new BatchCustomSendMsgsTransformers(), $batchCustomMsgs);
    	}else{
    		return response()->success(['data'=>0]);
    	}
    
    }

    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/batchCustomMsgById 通过ID获取指定批次客服消息
     * @apiGroup OfficialAccount
     * @apiName batchCustomMsgById
     * @apiParam {String}  id 批次id.
     */
    function  batchCustomMsgById(Request $request) {
        $id = $request->has('id') ? $request->input('id') : '';
        if(empty($id)) {
            return response()->error("PARAM_EMPTY");
        }
        \Log::info('batchCustomMsgById:'.$id);
        
        $param = array();
        $param['id'] = $id;

        $batchCustomMsgService = BatchCustomMsgService::batchCustomMsgById($param);
//         \Log::info($batchCustomMsgService);
        if (!empty($batchCustomMsgService)) {
            return response()->item(new BatchCustomSendMsgsTransformers(), $batchCustomMsgService);
        }else{
            return response()->success(['data'=>0]);
        }
        
    }

    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/updateBatchCustomSendMsgStatusById 更新发送客服消息
     * @apiGroup OfficialAccount
     * @apiName updateBatchCustomSendMsgStatusById
     * @apiParam {String}  id 客服消息批次id.
     * @apiParam {String}  status 状态 1待发送  3发送成功  4删除  8发送中 .
     * @apiParam {String}  del_flag 是否删除：1是 0否.
     * @apiSuccessExample {json} Success-Response:
     *
     *      {
     *          "code": 0,
     *          "msg": "",
     *          "data": {
     *          }
     *      }
     */
    function  updateBatchCustomSendMsgStatusById(Request $request) {
        $id = $request->has('id') ? $request->input('id') : '';
        if(empty($id)) {
        	return response()->error("PARAM_EMPTY");
        }
        
        $status = $request->has('status') ? $request->input('status') : '';
        if(empty($status)) {
        	return response()->error("PARAM_EMPTY");
        }
        
        $del_flag = $request->has('del_flag') ? $request->input('del_flag') : '0';
        
        \Log::info('updateBatchCustomSendMsgStatusById_start,id:'.$id.' status:'.$status.' $del_flag:'.$del_flag);
        $param = array();
        $param['id'] = $id;
        $param['status'] = $status;
        $param['del_flag'] = $del_flag;
        $batch_res = BatchCustomMsgService::updateBatchCustomSendMsgStatusById($param);
        // 循环子消息
        $param = array();
        $param['trusteeship'] = 1;
        $param['batch_no'] = $id;
        $customMsgServices = CustomMsgService::customSendMsgsByTrusteeshipAndBacthNo($param);
//         \Log::info($customMsgServices);
        if(!empty($customMsgServices)){
        	foreach($customMsgServices as $customMsgService){
        		\Log::info('stopBatchCustomSendMsgsById_single:'.json_encode($customMsgService));
        		$customMsgService = CustomMsgService::updateCustomSendMsgsStatusMulty($customMsgService->id,$status,$del_flag);
        	}
        }

        if ($batch_res == 1) {
            return response()->success();
        }else {
            return response()->error('CUSTOMS_SETTING_FAILED');
        }
        
    }

   
    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/batchAddCustomSendMsgs 批量添加客服消息
     * @apiGroup OfficialAccount
     * @apiName batchAddCustomSendMsgs
     * @apiParam {String}  name 客服消息标题.
     * @apiParam {String}  send_time 客服消息发送时间.
     * @apiParam {String}  content 客服消息内容. 格式：[[{"title":"横眉冷对千夫指，俯首甘为孺子牛"},{"description":"横眉冷对千夫指，俯首甘为孺子牛"},{"url":"http://www.baidu.com"},{"image":"https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=314110819,2721402218&fm=173&s=91B3C23586024F4D0235ECFB0300C036&w=550&h=550&img.JPEG"}],[{"title":"来他家做佣人半年，结果天天被男主人这样！"},{"description":"来他家做佣人半年，结果天天被男主人这样！"},{"url":"http://www.baidu.com"},{"image":"https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=314110819,2721402218&fm=173&s=91B3C23586024F4D0235ECFB0300C036&w=550&h=550&img.JPEG"}]]
     * @apiParam {String}  redirect_url 点击消息重定向地址.
     * @apiParam {String}  sex 用户性别.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       } 
     */
    function  batchAddCustomSendMsgs(Request $request) {
    	\Log::info('manage_batchAddCustomSendMsgs_start');
    	\Log::info($request->all());
        
        $name = $request->has('name') ? $request->input('name') : '';
        if(empty($name)) {
            return response()->error("PARAM_EMPTY");
        }

        $send_time = $request->has('send_time') ? $request->input('send_time') : '';
        if(empty($send_time)) {
            return response()->error("PARAM_EMPTY");
        }

        $content = $request->has('content') ? $request->input('content') : '';
        if(empty($content)) {
            return response()->error("PARAM_EMPTY");
        }

        $redirect_url = $request->has('redirect_url') ? $request->input('redirect_url') : '';
        if(empty($redirect_url)) {
            return response()->error("PARAM_EMPTY");
        }

        $sex = $request->has('sex') ? $request->input('sex') : '';
        if(empty($sex)) {
            return response()->error("PARAM_EMPTY");
        }

        
        $customMsgPrams['name'] = $name;
        $customMsgPrams['send_time'] = $send_time;
        $customMsgPrams['content'] = json_encode($content);
        $customMsgPrams['redirect_url'] = $redirect_url;
        $customMsgPrams['sex'] = $sex;
        $customMsgPrams['subscribe_time'] = 'g';// 关注1天前，有过交互的
        $customMsgPrams['trusteeship'] = '1'; // 托管
        $customMsgPrams['balance'] = 'z';
        $customMsgPrams['order_type'] = 'z';
        $customMsgPrams['category_id'] = 'z';
        $customMsgPrams['status'] = '1';
        $customMsgPrams['is_show_list'] = '0';// 分销界面不展示
        \Log::info($customMsgPrams);
        $batch_no = '';
        
        $batch_res = BatchCustomMsgService::addBatchCustomSendMsgs($customMsgPrams,$batch_no);
        \Log::info('$batch_res:'.$batch_res.' $batch_no:'.$batch_no);
        if($batch_res == 1){
        	$customMsgPrams['batch_no'] = $batch_no;
        	$official_accounts =  OfficialAccountService::getTrusteeshipOfficialAccounts();
        	\Log::info('getTrusteeshipOfficialAccounts');
//         	\Log::info($official_accounts);
        	foreach($official_accounts as $official_account){
        		$customMsgPrams['appid'] = $official_account->appid;
        		$customMsgPrams['distribution_channel_id'] = $official_account->distribution_channel_id;
        		\Log::info('getTrusteeshipOfficialAccounts:appid:'.$official_account->appid.' distribution_channel_id:'.$official_account->distribution_channel_id);
        		 
        		//先判断在发送时间段1小时以内，有没有发起过相同的模板消息，如果有发送过，就提示用户已经创建过相同模板消息，不创建新的模板消息
        		$isSendCustomer = CustomMsgService::isSendCustomerAtSameTime($customMsgPrams);
        		if (!empty($isSendCustomer)) {
        			\Log::info('isSendCustomerAtSameTime already_send:appid:'.$customMsgPrams['appid'].' distribution_channel_id:'.$customMsgPrams['distribution_channel_id']);
        			continue;
        		}
        		$customMsgService = CustomMsgService::addCustomSendMsgs($customMsgPrams);
        	}
        }
        
        if ($batch_res == 1) {
        	return response()->success();
        }elseif ($batch_res == 2) {
            return response()->error('CUSTOMS_SEND_FAILED');
        }elseif ($batch_res == 3) {
            return response()->error('CUSTOMS_DOUBLE_FAILED');
        }elseif ($batch_res == 4) {
            return response()->error('CUSTOMS_DOUBLE_FAILED');
        }elseif ($batch_res == 0) {
            return response()->error('CUSTOMS_SEND_FAILED');
        }
        else{
            return response()->error('CUSTOMS_SEND_FAILED');
        }
        
    }


    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/editCustomSendMsgs 编辑客服消息
     * @apiGroup OfficialAccount
     * @apiName editCustomSendMsgs
     * @apiParam {String}  appid 服务号，英文逗号隔开.
     * @apiParam {String}  distribution_channel_id 渠道号.
     * @apiParam {String}  name 客服消息标题.
     * @apiParam {String}  send_time 客服消息发送时间.
     * @apiParam {String}  content 客服消息内容. 格式：[[{"title":"横眉冷对千夫指，俯首甘为孺子牛"},{"description":"横眉冷对千夫指，俯首甘为孺子牛"},{"url":"http://www.baidu.com"},{"image":"https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=314110819,2721402218&fm=173&s=91B3C23586024F4D0235ECFB0300C036&w=550&h=550&img.JPEG"}],[{"title":"来他家做佣人半年，结果天天被男主人这样！"},{"description":"来他家做佣人半年，结果天天被男主人这样！"},{"url":"http://www.baidu.com"},{"image":"https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=314110819,2721402218&fm=173&s=91B3C23586024F4D0235ECFB0300C036&w=550&h=550&img.JPEG"}]]
     * @apiParam {String}  redirect_url 点击消息重定向地址.
     * @apiParam {String}  sex 用户性别.
     * @apiParam {String}  id id.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       } 
     */
    // 批量编辑暂时不支持，逻辑复杂
    function  editCustomSendMsgs(Request $request) {
    	\Log::info('editCustomSendMsgs_start');
    	\Log::info($request->all());
    	return response()->error("PARAM_EMPTY");
    }


    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/testAddCustomSendMsgs 测试向单个用户发送客服消息
     * @apiGroup OfficialAccount
     * @apiName testAddCustomSendMsgs
     * @apiParam {String}  uid 用户id或者openid.
     * @apiParam {String}  name 客服消息标题.
     * @apiParam {String}  content 客服消息内容. 格式：[[{"title":"横眉冷对千夫指，俯首甘为孺子牛"},{"description":"横眉冷对千夫指，俯首甘为孺子牛"},{"url":"http://www.baidu.com"},{"image":"https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=314110819,2721402218&fm=173&s=91B3C23586024F4D0235ECFB0300C036&w=550&h=550&img.JPEG"}],[{"title":"来他家做佣人半年，结果天天被男主人这样！"},{"description":"来他家做佣人半年，结果天天被男主人这样！"},{"url":"http://www.baidu.com"},{"image":"https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=314110819,2721402218&fm=173&s=91B3C23586024F4D0235ECFB0300C036&w=550&h=550&img.JPEG"}]]
     * @apiParam {String}  redirect_url 点击消息重定向地址.
     * @apiSuccessExample {json} Success-Response:
     *
     *       {
     *           "code": 0,
     *           "msg": "",
     *           "data": []
     *       } 
     */
    function  testAddCustomSendMsgs(Request $request) {
    	\Log::info('testAddCustomSendMsgs_start');
    	\Log::info($request->all());

        $name = $request->has('name') ? $request->input('name') : '';
        if(empty($name)) {
            return response()->error("PARAM_EMPTY");
        }

        $content = $request->has('content') ? $request->input('content') : '';
        if(empty($content)) {
            return response()->error("PARAM_EMPTY");
        }

        $redirect_url = $request->has('redirect_url') ? $request->input('redirect_url') : '';
        if(empty($redirect_url)) {
            return response()->error("PARAM_EMPTY");
        }

        $uid = $request->has('uid') ? $request->input('uid') : '';
        if(empty($uid)) {
            return response()->error("PARAM_EMPTY");
        }
        
        $customMsgPrams['name'] = $name;
        $customMsgPrams['redirect_url'] = $redirect_url;
        $customMsgPrams['uid'] = $uid;
        $customMsgPrams['distribution_channel_id'] = 14;// 线上改为14
    	$customMsgPrams['appid'] = 'wxb2aaa55b088f12e9,wxdbc486f1b4f6a8c3';
    	// 测试发送加上域名
    	foreach($content as $key=>$_content){
//     		\Log::info($_content);
    		$url = env('PROTOCOL').'://site'.encodeDistributionChannelId($customMsgPrams['distribution_channel_id']).'.'.env('CUSTOM_HOST').'.com'.$_content[2]['url'];
    		\Log::info('key:'.$key.' url:'.$url);
    		$content[$key][2]['url'] = $url;
    	}
    	$customMsgPrams['content'] = json_encode($content);
    	
        $customMsgService = CustomMsgService::testAddCustomSendMsgs($customMsgPrams);

        if ($customMsgService == 1) {
            return response()->success();
        }elseif ($customMsgService == 2) {
            return response()->error('CUSTOMS_SEND_FAILED');
        }elseif ($customMsgService == 0) {
            return response()->error('CUSTOMS_SEND_FAILED');
        }else{
            return response()->error('CUSTOMS_SEND_FAILED');
        }
        
    }
   
    public static function get_custom_msg_statistics($customMsgService,$num){
    	$start_date = date('Y-m-d',strtotime('-7 day'));
    	$end_date = date('Y-m-d',strtotime('+1 day'));
    	$stat_type = 'custom_'.$customMsgService->id.'_'.$num;
//     	\Log::info('get_custom_msg_statistics:'.$customMsgService->distribution_channel_id.' start_date:'.$start_date.' end_date:'.$end_date.' stat_type:'.$stat_type);
    	$user_pay_stat = SendStatistics::getWechatMsgUseRecord($customMsgService->distribution_channel_id,$stat_type,$start_date,$end_date);
//     	\Log::info('get_custom_msg_statistics:');\Log::info($user_pay_stat);
    	$customMsgService->uv = isset($user_pay_stat['uv'])?$user_pay_stat['uv']:0;
    	$customMsgService->pv = isset($user_pay_stat['pv'])?$user_pay_stat['pv']:0;
    	$customMsgService->pay_user_num = isset($user_pay_stat['user_num'])?$user_pay_stat['user_num']:0;
    	$customMsgService->total_order_num = isset($user_pay_stat['order_count'])?$user_pay_stat['order_count']:0;
    	$customMsgService->suc_order_num = isset($user_pay_stat['success_order_count'])?$user_pay_stat['success_order_count']:0;
    	$customMsgService->success_order_sum = isset($user_pay_stat['success_order_sum'])?$user_pay_stat['success_order_sum']:0;
    	if(isset($customMsgService->total_order_num) && $customMsgService->total_order_num > 0){
    		$customMsgService->order_suc_rate = round(100*$customMsgService->suc_order_num/$customMsgService->total_order_num,2);
    	}else{
    		$customMsgService->order_suc_rate = 0;
    	}

    	return $customMsgService;
    }
    
    
}