<?php
/**
 * Created by PhpStorm.
 * User: hp
 * Date: 2017/12/2
 * Time: 15:56
 */

namespace App\Modules\Channel\Services;

use App\Modules\OfficialAccount\Models\DistributionSelfDefineConfig;

use App\Modules\Channel\Models\Channel;
use App\Modules\Finance\Services\FinanceService;
use App\Modules\SendOrder\Services\SendOrderService;
use App\Modules\Trade\Services\PayMerchantService;
use DB;

class ChannelService
{
    /**
     * 获取所有渠道
     * @param array $params
     * @return mixed
     */
    static function getAllChannels($params = [])
    {
        return Channel::getAllChannels($params);
    }

    static function TempgetAllChannels($id)
    {
        $sqlObj = Channel::orderBy('created_at', 'desc')->where('id',$id);

        return $channelResult = $sqlObj->get();
        //return Channel::getAllChannels($params);
    }

    /**
     * 根据手机号码获取
     * @return mixed
     */
    static function getByPhone($phone)
    {
        return Channel::getByPhone($phone);
    }

    /**
     * 根据名称获取id
     * @param $nickName
     * @return mixed
     */
    static function getIdByNickName($nickName)
    {
        return Channel::getIdByNickName($nickName);
    }

    /**
     * 根据账号ID获取渠道列表
     * @return mixed
     */
    static function getByChannelUserId($channel_user_id)
    {
        return Channel::getByChannelUserId($channel_user_id);
    }
    
    /**
     * 删除站点
     * @param unknown_type $distribution_channel_id
     * @param unknown_type $channel_user_id
     */
    static function deleteChannel($distribution_channel_id, $channel_user_id)
    {
    	return Channel::deleteChannel($distribution_channel_id, $channel_user_id);
    }
    

    /**
     * 根据渠道id获取
     * @return mixed
     */
    static function getById($id)
    {
        return Channel::getById($id);
    }

    /**
     * 根据渠道id获取渠道名称
     * @return mixed
     */
    static function getChannelNameById($id)
    {
        if (empty($id)) {
            return '';
        }
        return Channel::getChannelNameById($id);
    }

    /**
     * 根据渠道id获取渠道用户id
     * @return mixed
     */
    static function getUserIdById($id)
    {
        if (empty($id)) {
            return 0;
        }
        return Channel::getUserIdById($id);
    }


    /**
     * 根据渠道id获取渠道昵称
     * @param $id
     * @return string
     */
    static function getChannelNicknameById($id)
    {
        if (empty($id)) {
            return "";
        }
        $result = Channel::getChannelNicknameById($id);
        if (empty($result)) {
            return "";
        }
        return $result['nickname'];
    }
    /**
     * 根据渠道id获取渠道昵称
     * @param $id
     * @return string
     */
    static function getChannelCompanyNameById($id)
    {
        if (empty($id)) {
            return "";
        }
        $result = Channel::getChannelCompanyNameById($id);

        return $result;
    }

    /**
     * 获取渠道对应的支付渠道
     * @param $id
     * @return string
     */
    static function getChannelBankSourceById($id)
    {
        //TODO 获取渠道对应的支付渠道
        $channel = self::getById($id);
        if (!empty($channel) && $channel['pay_merchant_id'] > 0) {
            $payMerchant = PayMerchantService::getPayMerchantSingle($channel['pay_merchant_id']);
            if (!empty($payMerchant) && !empty($payMerchant['source'])) {
                return $payMerchant['source'];
            }
        }
        return config('common.tonglianpay');
    }

    /**
     * 创建渠道
     * @param  array $params ['password','name','pay_type','nickname','latest_login_ip','latest_login_time','remark','register_ip','channel_user_id']
     * @return object
     */
    static function createChannel($params)
    {
        return Channel::createChannel($params);
    }

    /**
     * 获取渠道统计数据
     */
    static function getChannelData()
    {
        //获取所有的渠道
        $channels = Channel::getAllChannels();
        //获取所有渠道账户余额总额(可提现金额总额)
        $avaliableBalanceAll = FinanceService::getChannelAccountBalanceAll();
        //所有充值总则
//        $chargeAllAmount = TradeSevices::getChannelPriceCountAll();
        if (empty($channels)) {
            foreach ($channels as $channelItem) {
                $channelId = $channelItem->id;
                //获取渠道下的账户余额
                $channelAvaliableBalance = FinanceService::getChannelAccountBalance($channelId);
                //获取渠道下的充值总额
//                $channelChargeAllAmount = Trade::getChannelPriceCountSingle($channelId);
                //获取渠道下的总派单数
                $sendOrderCount = SendOrderService::getPromotionCountByChannelId($channelId);
            }
        }
    }


    /**
     * 修改渠道密码
     * @param  string $phone 手机号码
     * @param  string $password 加密后密码
     * @return boolen
     */
    static function modifyPassword($phone, $password)
    {
        return Channel::modifyPassword($phone, $password);
    }

    /**
     * 获取渠道列表
     * @param $id 渠道ID
     * @param $params []
     *                  name:渠道名称 可选
     *                  nickname:渠道昵称 可选
     *                  pay_merchant_id: 支付通道 可选
     *                  distribution_manages_id: 管理员 可选
     *                  phone:电话 可选
     *                  person_in_charge_name:负责人 可选
     *                  remark:备注 可选
     *                  is_enabled: 是否开通 0:未审核； 1:审核通过
     * @return mixed
     */
    public static function updateChannelData($id, $params = [])
    {
        return Channel::updateChannelData($id, $params);
    }

    /**
     * 获取渠道列表
     * @param $params []
     *                  channel_id:渠道ID 可选
     *                  channel_name:渠道名称 可选
     *                  search_name: 搜索名称
     *                  start_date:开始时间 可选
     *                  end_date:结束时间 可选
     *                  is_enabled: 是否开通 0:未审核； 1:审核通过
     *                  distribution_manages_id: 管理员 可选
     * @param $isAll
     * @return mixed
     */
    public static function getChannelList($params = [], $isAll = '')
    {
        return Channel::getChannelList($params, $isAll);
    }

    /**
     * 获取当前渠道经理下所有渠道ID
     * @param $distribution_manages_id
     * @return mixed
     */
    public static function getChannelIdList($distribution_manages_id = '')
    {
        return Channel::getChannelIdList($distribution_manages_id);
    }

    public static function getSourceName($source)
    {
        if (config('common.tonglianpay') == $source) {
            return "通联支付";

        } else if (config('common.lianlianpay') == $source) {
            return "连连支付";

        } else if (config('common.officialpay') == $source) {
            return "官方支付";

        }
        return "";
    }

    static function getDefault($channel_user_id)
    {
        return Channel::getDefault($channel_user_id);
    }

    /**
     * 通过渠道ID、用户ID获取渠道
     */
    static function getUserChannel($distribution_channle_id, $channel_user_id)
    {
        return Channel::getUserChannel($distribution_channle_id, $channel_user_id);
    }

    /**
     * 获取用户下所有渠道ID
     * @param $channel_user_id
     */
    static function getUserChannelIds($channel_user_id)
    {
        return Channel::getUserChannelIds($channel_user_id);
    }

    static function getUserChannelIdsV2($channel_user_id)
    {
        return Channel::where('channel_user_id', $channel_user_id)->get()->pluck('id')->toArray();
    }

    /**
     * 设置站点别名
     */
    static function setChannelSiteNickName($distribution_channle_id, $nick_name)
    {
        return Channel::where('id', $distribution_channle_id)->update(['site_nick_name' => $nick_name]);
    }

    /**
     * 通过DistributionManagesId获取
     */
    static function getByDistributionManagesId($distribution_manage_id)
    {
        return Channel::getByDistributionManagesId($distribution_manage_id);
    }
    
    /**
     * 更新外站开关
     * @return mixed
     */
    static function updateDistributionOuterSiteSwitch($distribution_channel_id,$status)
    {
    	return Channel::updateDistributionOuterSiteSwitch($distribution_channel_id,$status);
    }
    
    /**
     * 更新老年站点开关
     * @return mixed
     */
    static function updateDistributionOldUserSiteSwitch($distribution_channel_id,$status)
    {
    	return Channel::updateDistributionOldUserSiteSwitch($distribution_channel_id,$status);
    }
    
    
    /**
     * 获取渠道信息
     * @return mixed
     */
    static function getDistributionChannel($distribution_channel_id)
    {
    	return Channel::getDistributionChannel($distribution_channel_id);
    }
    
    /**
     * 获取渠道信息
     * @return mixed
     */
    static function getDistributionChannelSwitchByCategory($distribution_channel_id,$category)
    {
    	return DistributionSelfDefineConfig::getDistributionSelfDefineConfig($distribution_channel_id,$category);
    }
    
    /**
     * 获取渠道信息
     * @return mixed
     */
    static function getDistributionChannelSwitchByCategoryAndCompany($company_id,$category)
    {
    	return DistributionSelfDefineConfig::getDistributionChannelSwitchByCategoryAndCompany($company_id,$category);
    }
    
    // 判断渠道的某个分类的 按照公司的权限
    static function check_channel_company_priv($distribution_channel_id,$category){
    	$distribution = self::getDistributionChannel($distribution_channel_id);
    	$channel_user_id = isset($distribution->channel_user_id)?$distribution->channel_user_id:'';
    	$channel_user = ChannelUserService::getById($channel_user_id);
    	$company_id = isset($channel_user->company_id)?$channel_user->company_id:'';
    	 
    	return self::getDistributionChannelSwitchByCategoryAndCompany($company_id,$category);
    }
    
    // 判断渠道的某个分类的 按照登录账号的权限
    static function check_channel_account_priv($distribution_channel_id,$category){
    	$distribution = self::getDistributionChannel($distribution_channel_id);
    	$channel_user_id = isset($distribution->channel_user_id)?$distribution->channel_user_id:'';
    	$channel_user = ChannelUserService::getById($channel_user_id);
    	$account = isset($channel_user->phone)?$channel_user->phone:'';
    
    	return self::getDistributionChannelSwitchByCategoryAndAccount($account,$category);
    }
    
    static function getDistributionChannelSwitchByCategoryAndAccount($account,$category)
    {
    	return DistributionSelfDefineConfig::getDistributionChannelSwitchByCategoryAndAccount($account,$category);
    }
    
    /**
     * 根据站点属性，转换对应的回复链接
     */
    static function convertChannelReplyUrl($is_outer_site,$appid,$openid,$content,$fromwhere='')
    {
    	if(!$is_outer_site) return $content;
    	$matchs = [];
    	$from_where_str = '&fromwhere='.$fromwhere;
    	\Log::Info('convertChannelReplyUrl_before:appid'.$appid.' openid:'.$openid.' is_outer_site:'.$is_outer_site.' fromwhere:'.$fromwhere);
    	$new_content = $content;
//     	\Log::Info('$content');\Log::Info($content);
    	// 图文模式
    	if(is_array($new_content)){
    		foreach ($new_content as $key=>$one_content){
    			if(isset($new_content[$key]['url']) && !empty($new_content[$key]['url'])){
    				if(strpos($new_content[$key]['url'],'?') > -1){
    					$new_content[$key]['url'] = $new_content[$key]['url'].'&appid='.$appid.'&openid='.$openid.$from_where_str;
    				}else{
    					$new_content[$key]['url'] = $new_content[$key]['url'].'?appid='.$appid.'&openid='.$openid.$from_where_str;
    				}
    			}
    		}
    	}
    	// 文字模式
    	else{
    		preg_match_all('/href=\"(.*)\"/u', $content, $matchs1);
    		$matchs1 = isset($matchs1[1])?$matchs1[1]:[];
    		preg_match_all('/href=\'(.*)\'/u', $content, $matchs2);
    		$matchs2 = isset($matchs2[1])?$matchs2[1]:[];
    		$matchs_all = array_merge($matchs1,$matchs2);
    		
    		if(!empty($matchs_all)){
    			foreach($matchs_all as $match){
    				$new_url = $url  = $match;
    				 
    				if(strpos($url,'?') > -1){
    					$new_url = $url.'&appid='.$appid.'&openid='.$openid.$from_where_str;
    				}else{
    					$new_url = $url.'?appid='.$appid.'&openid='.$openid.$from_where_str;
    				}
    				// 小链接可能多次被替换，所以一定要引号结尾
    				$new_content = str_replace($url.'"',$new_url.'"',$new_content);
    				$new_content = str_replace($url."'",$new_url."'",$new_content);
    			}
    		}
    	}
    	
//     	\Log::Info('convertChannelReplyUrl_after:appid'.$appid.' openid:'.$openid);
//     	\Log::Info('$new_content');\Log::Info($new_content);
    	return $new_content;
    }

    static function getContentByUrl($url)
    {
        $ch = curl_init();
        $timeout = 10; // set to zero for no timeout
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $html = curl_exec($ch);
        return $html;
    }

    public static function getChannelCompanyInfo($distribution_channel_id){
        return Channel::select(DB::raw("companies.*"))
            ->leftjoin('channel_users','channel_users.id','=','distribution_channels.channel_user_id')
            ->leftjoin('companies','companies.id','=','channel_users.company_id')
            ->where('distribution_channels.id',$distribution_channel_id)
            ->first();
    }
    
    public static function getChannelCompanySex($distribution_channel_id){
    	$company =  Channel::select(DB::raw("companies.*"))
    	->leftjoin('channel_users','channel_users.id','=','distribution_channels.channel_user_id')
    	->leftjoin('companies','companies.id','=','channel_users.company_id')
    	->where('distribution_channels.id',$distribution_channel_id)
    	->first();
    	// 1男 2女 3混合
    	$sex = isset($company->fans_gender)?$company->fans_gender:'3';
    	return $sex;
    }
    public static function getInnerChannelIds(){
        $distribution_out_channel_ids = DB::table('distribution_channels')
            ->whereIn('channel_user_id',[123,5,2012,395,2681])
            ->whereNotIn('id',[])
            ->pluck('id')
            ->toArray();
        return $distribution_out_channel_ids;
    }

    public static function getBrushChannelIds(){
        $distribution_out_channel_ids = [];
        return $distribution_out_channel_ids;
    }

    public static function getContractChannelIds(){
        $distribution_out_channel_ids = [
           
        ];
        return $distribution_out_channel_ids;
    }

}