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

namespace App\Modules\SendOrder\Services;

use App\Modules\SendOrder\Models\SendOrder;
use App\Modules\SendOrder\Models\SendOrderExtraStat;
use App\Modules\Statistic\Services\WapVisitStatService;
use DB;
use Redis;

class SendOrderService
{
    /**
     *  更新派单的备注
     * @param $id  派单id
     * @param $distribution_channel_id 渠道id
     * @param $remark 备注
     * @return mixed
     */
    static function updateRemark($id, $distribution_channel_id, $remark)
    {
        return SendOrder::updateRemark($id, $distribution_channel_id, $remark);
    }

    /**
     *  更新派单的星数
     * @param $id  派单id
     * @param $distribution_channel_id 渠道id
     * @param $starNum 星数
     * @return mixed
     */
    static function updateStarNum($id, $distribution_channel_id, $starNum)
    {
        return SendOrder::updateStarNum($id, $distribution_channel_id, $starNum);
    }

    /**
     *  更新派单的星数、备注
     * @param $id  派单id
     * @param $distribution_channel_id 渠道id
     * @param $starNum 星数
     * @return mixed
     */
    static function updateStarNumAndRemark($id, $distribution_channel_id, $starNum, $remark)
    {
        return SendOrder::updateStarNumAndRemark($id, $distribution_channel_id, $starNum, $remark);
    }

    /**
     * 更新派单
     * @param $id  派单id
     * @param $distribution_channel_id 渠道id
     * @param $name 派单名称
     * @param $cost 成本
     * @param $channel_type  派单渠道类型.(允许值: AUTHENTICATED, UNAUTHENTICATED)
     * @return mixed
     */
    static function updateSendOrderInfo($id, $distribution_channel_id, $name, $pre_send_date, $channel_type, $cost, $promotion_type,$subscribe_chapter=[])
    {
        return SendOrder::updateSendOrderInfo($id, $distribution_channel_id, $name, $pre_send_date, $channel_type, $cost, $promotion_type,$subscribe_chapter);
    }

    /**
     * 通过bid获取该书的推广次数
     * @param $bid 书本id
     */
    static function getPromotionCountByBid($bid, $channelId)
    {
        return SendOrder::getPromotionCountByBid($bid, $channelId);
    }

    /**
     * 通过渠道id获取该渠道的推广次数
     * @param $channelId 渠道id
     */
    static function getPromotionCountByChannelId($channelId)
    {
        return SendOrder::getPromotionCountByChannelId($channelId);
    }

    /**
     * 获取渠道下某时间段内推广次数
     * @param $channelId 渠道id
     * @param $begin_time 开始日期
     * @param $end_time 结束日期
     */
    static function getChannelPromotionCount($channelId, $begin_time, $end_time)
    {
        return SendOrder::getChannelPromotionCount($channelId, $begin_time, $end_time);
    }

    /**
     * 获取渠道下某时间段内实际推广次数
     * @param $channelId 渠道id
     * @param $begin_time 开始日期
     * @param $end_time 结束日期
     */
    static function getChannelRealPromotionCount($channelId, $begin_time, $end_time)
    {
        return SendOrder::getChannelRealPromotionCount($channelId, $begin_time, $end_time);
    }

    /**
     * 获取实际推广次数
     * @param $channelId 渠道id
     * @param $begin_time 开始日期
     * @param $end_time 结束日期
     */
    static function getRealPromotionCount($params)
    {
        return SendOrder::getRealPromotionCount($params);
    }

    /**
     * 获取渠道下某时间段内推广次数
     * @param $params begin_time、end_time、distribution_channel_id
     */
    static function getPromotionCount($params)
    {
        return SendOrder::getPromotionCount($params);
    }

    /**
     * 通过渠道id下所有的推广次数
     * @param $channelId 渠道id
     */
    static function getTotalPromotionCountByChannelIds($channelIds)
    {
        return SendOrder::getTotalPromotionCountByChannelIds($channelIds);
    }

    /**
     * 通过区间内的渠道id获取该渠道的推广次数
     * @param $channelId 渠道id
     * @param $start_time 开始时间
     * @param $end_time 结束时间
     */
    static function getDuraingPromotionCountByChannelId($channelId, $start_time = '', $end_time = '')
    {
        return SendOrder::getDuraingPromotionCountByChannelId($channelId, $start_time, $end_time);
    }

    /**
     * 获取派单信息
     * @param $bookId 推广书籍id
     * @param $distribution_channel_id 推广渠道id
     * @param $name 派单名称
     * @param $bookName 书名
     * @param $sendOrderId 派单id
     * @param string $start_date 开始时间
     * @param string $end_date 结束时间
     * @param string $isAll 是否获取所有
     * @return mixed
     */
    static function getSendOrders($bookId, $distribution_channel_id, $name = null, $bookName = null, $sendOrderId, $start_time = '', $end_time = '', $isAll = false)
    {
        return SendOrder:: getSendOrders($bookId, $distribution_channel_id, $name, $bookName, $sendOrderId, $start_time, $end_time, $isAll);
    }


    /**
     * 管理后台获取派单信息
     * @param $bookId 推广书籍id
     * @param $distribution_channel_id 推广渠道id
     * @param $name 派单名称
     * @param $bookName 书名
     * @param $sendOrderId 派单id
     * @param string $start_date 开始时间
     * @param string $end_date 结束时间
     * @param string $isAll 是否获取所有
     * @return mixed
     */
    static function getManageSendOrders($params = [], $is_all = false)
    {
        return SendOrder:: getManageSendOrders($params, $is_all);
    }

    /**
     * 创建推广派单（章节）
     * @param  array ['name', 'channel_type', 'promotion_type','sex_preference', 'book_id', 'cost','book_name','qr_code_id', 'chapter_id', 'chapter_name', 'document_end_chapter_seq', 'original_guide_id', 'headline_id', 'body_template_id', 'document_cover_id', 'subscribe_chapter_id', 'subscribe_chapter_name', 'subscribe_chapter_seq', 'distribution_channel_id', 'redirect_url']
     */
    static function createFromChapter($data)
    {
        return SendOrder::createFromChapter($data);
    }

    /**
     * 创建推广派单（推广页面）
     * @param  array ['name', 'channel_type','promotion_type', 'page_id', 'entrance','cost', 'qr_code_id','distribution_channel_id', 'redirect_url', 'subscribe_chapter_id', 'subscribe_chapter_name', 'subscribe_chapter_seq']
     */
    static function createFromPage($data)
    {
        return SendOrder::createFromPage($data);
    }

    /**
     * 创建推广派单（目录）
     * @param  array ['name', 'channel_type', 'promotion_type','book_id', 'book_name','cost', 'chapter_id','qr_code_id', 'chapter_name', 'distribution_channel_id', 'redirect_url', 'subscribe_chapter_id', 'subscribe_chapter_name', 'subscribe_chapter_seq']
     */
    static function createFromDirectory($data)
    {
        return SendOrder::createFromDirectory($data);
    }

    /**
     * 获取Pv
     * @param $id 派单id
     * @return int PV
     */
    static function getPv($id)
    {
        return WapVisitStatService::getSendOrderTotalPv($id);
        //return (float)Redis::hget('send_order_pv_' . $id, 'total');
    }

    static function getBrowserUvAndPv($id){
        return WapVisitStatService::getBrowserSendOrderTotalPvAndUv($id);
    }

    /**
     * 获取Uv
     * @param $id 派单id
     * @return int UV
     */
    static function getUv($id)
    {
        return WapVisitStatService::getSendOrderTotalUv($id);
        //return (float)Redis::hget('send_order_uv_' . $id, 'total');
    }

    /**
     * 获取每一天的Uv信息列表
     * @param $id 派单id
     * @return int UV
     */
    static function getUvInfo($id)
    {
        return WapVisitStatService::getSendOrderUv($id);
        //return Redis::hgetAll('send_order_uv_' . $id);
    }

    /**
     * 获取每一天的pv信息列表
     * @param $id 派单id
     * @return int PV
     */
    static function getPvInfo($id)
    {
        return WapVisitStatService::getSendOrderPv($id);
        //return Redis::hgetAll('send_order_pv_' . $id);
    }

    /**
     * 删除派单
     * @param $id 派单id
     * @param $distribution_channel_id 渠道id
     * @return
     */
    static function removeSendOrder($id, $distribution_channel_id)
    {
        return SendOrder::removeSendOrder($id, $distribution_channel_id);
    }

    /**
     * 获取重定向url
     * @param $id
     * @return mixed
     */
    static function getRedirectUrlById($id)
    {
        return SendOrder::where('id', $id)->select('redirect_url', 'book_id', 'send_time', 'distribution_channel_id', 'name','promotion_point','force_show_qrcode')->first();
    }

    /**
     * 根据id获取信息
     * @param $id
     * @return mixed
     */
    static function getById($id)
    {
        return SendOrder::find($id);
    }

    //获取推广总uv、pv
    static function getChannelPromotionTotalUvPv($distribution_channel_id, $date)
    {
        //return WapVisitStatService::getChannelPromotionTotalUvPv($distribution_channel_id,$date);
        $send_orders = SendOrder::getSendOrders(null, $distribution_channel_id, null, null, '', '', '', true);
        $uv = 0;
        $pv = 0;
        foreach ($send_orders as $send_order) {
            $uv += (float)Redis::hget('send_order_uv_' . $send_order->id, $date);
            $pv += (float)Redis::hget('send_order_pv_' . $send_order->id, $date);
        }
        return compact('uv', 'pv');
    }

    /**
     * 获取date的实际派单数
     */
    static function getActualSendOrderNum($distribution_channel_id, $date)
    {
        return SendOrder::whereBetween('send_time', [$date, date('Y-m-d', strtotime($date) + 86400)])->where('distribution_channel_id', $distribution_channel_id)->count();
    }

    /**
     * 获取继续阅读的uv
     * @param $distribution_channel_id
     * @param $date
     * @return array
     */
    static function getContinueTotalReadUv($send_order_id)
    {
        return (float)Redis::hget('send_order:continue:' . $send_order_id, 'total');
    }

    /**
     * 设置成本
     * @param $id  派单id
     * @param $distribution_channel_id 渠道id
     * @param $cost  成本
     * @return mixed
     */
    static function setSendOrderCost($id, $distribution_channel_id, $cost)
    {
        return SendOrder::setSendOrderCost($id, $distribution_channel_id, $cost);
    }

    /**
     * 获取派单下的首充用户数
     * $id 派单id
     * @param $id
     */
    static function getFirstChargeUserNum($id)
    {
        return SendOrder::getFirstChargeUserNum($id);
    }

    /**
     * 获取派单下的非首充用户数
     * $id 派单id
     * @param $id
     */
    static function getRepetitiousChargeUserNum($id)
    {
        return SendOrder::getRepetitiousChargeUserNum($id);
    }

    /**
     * 获取派单uv大于20的时间
     * @param $sendOrderId 派单id
     * @return float|int 时间
     */
    static function getUv20Time($sendOrderId)
    {
        $uv20Time = '';
        $periodTotalUV = 0;
        $uvInfos = SendOrderService::getUvInfo($sendOrderId);
        if (isset($uvInfos['total'])) {
            unset($uvInfos['total']);
        }
        ksort($uvInfos);
        foreach ($uvInfos as $key => $v) {
            $periodTotalUV += $v;
            //如果uv总数大于20
            if ($periodTotalUV > 20) {
                $uv20Time = $key;
                break;
            }
        }
        return $uv20Time;
    }

    /**
     * 新获取派单列表
     * @param $bookId 推广书籍id
     * @param $distribution_channel_id 推广渠道id
     * @param $name 派单名称
     * @param $bookName 书名
     * @param $sendOrderId 派单id
     * @param string $start_date 开始时间
     * @param string $end_date 结束时间
     * @param string $isAll 是否获取所有
     * @return mixed
     */
    static function search($params, $isAll = false)
    {
        return SendOrder:: search($params, $isAll);
    }

    /*
     * 更新派单时间
     */
    static function updateSendOrderTime($send_order_id)
    {
        return SendOrder::where('id', $send_order_id)->update(['send_time' => date('Y-m-d H:i:s')]);
        /*$send_time = SendOrder::where('id',$send_order_id)->select('send_time')->first();
        if($send_time && $send_time->send_time){
            return true;
        }else{
            return SendOrder::where('id',$send_order_id)->update(['send_time'=>date('Y-m-d H:i:s')]);
        }*/
    }

    /**
     * 获取实际派单数
     */
    static function getRealSendOrderCount($distribution_channel_id = '', $date)
    {
        return SendOrder::getSendOrderCount($distribution_channel_id, $date);
    }

    static function getChannelPromotionBooks($distribution_channel_id = [], $endData, $book_name = '', $channel_name = '', $isAll = false)
    {
        $obj = SendOrder::select('send_orders.book_name', "companies.name as nickname", DB::raw("GROUP_CONCAT(distinct send_orders.distribution_channel_id) as distribution_channel_id"), DB::raw("count(*) as count"))
            ->join("distribution_channels", 'send_orders.distribution_channel_id', "=", "distribution_channels.id")
            ->join("channel_users", 'distribution_channels.channel_user_id', "=", "channel_users.id")
            ->join('companies', 'companies.id', "=", "channel_users.company_id")
            ->where("send_orders.created_at", "<=", $endData)
            ->groupBy('send_orders.book_name')
            ->groupBy('distribution_channels.channel_user_id');

        if ($book_name) {
            $obj = $obj->where('send_orders.book_name', $book_name);
        }

        if ($channel_name) {
            $obj = $obj->where('companies.name', 'like', '%' . $channel_name . '%');
        }

        if ($distribution_channel_id) {
            $obj = $obj->whereIn('send_orders.distribution_channel_id', $distribution_channel_id);
        }

        if ($isAll) {
            return $obj->get();
        } else {
            return $obj->paginate();
        }
    }

    static function getExtraStat($send_order_id)
    {
        return SendOrderExtraStat::getBySendOrderId($send_order_id);
    }

    static function getPeriodActualSendOrdersNum($channel_id,$start_time,$end_time) {
        return SendOrder::where([
            ['distribution_channel_id','=',$channel_id],
            ['send_time','>=',$start_time],
            ['send_time','<=',$end_time],
        ])->count();
    }

    static function getCompanyPromotionBooks($company_id,$start_time,$end_time) {
        $res = DB::select("select * from (select bcs.bid,bcs.book_name,count(so.id) as promotion_times 
 from channel_users cu
 left join distribution_channels dc on dc.channel_user_id=cu.id
 left join send_orders so on so.distribution_channel_id=dc.id
 left join book_configs bcs on bcs.bid=so.book_id
 where cu.company_id=".$company_id." and so.book_id is not null and so.send_time between '".$start_time."' and '".$end_time."' 
 group by so.book_id) tmp order by tmp.promotion_times desc");
        return $res;
    }

    //成本统计
    static function getCostStats($distribution_channels) {
        return SendOrder::whereIn('distribution_channel_id',$distribution_channels)
            ->where('is_enable',1)
            ->whereNotNull('send_time')
            ->sum('cost');
    }
}