<?php

namespace App\Http\Controllers\Manage\Book;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Manage\Book\Transformers\BookPromotionCheckedTransformer;
use App\Http\Controllers\Manage\Book\Transformers\BookPromotionTransformer;
use App\Modules\Book\Models\BookConfig;
use App\Modules\Book\Models\BookPromotionChecked;
use App\Modules\Book\Services\BookConfigService;
use App\Modules\Book\Services\BookPromotionCheckedService;
use App\Modules\Channel\Models\Channel;
use App\Modules\Channel\Services\ChannelService;
use App\Modules\Manage\Services\ManageService;
use App\Modules\SendOrder\Models\SendOrder;
use App\Modules\SendOrder\Models\SendOrderStat;
use App\Modules\SendOrder\Services\SendOrderService;
use App\Modules\SendOrder\Services\SendOrderStatService;
use Cache;
use Cookie;
use DB;
use Illuminate\Http\Request;
use Storage;

class BookPromotionController extends Controller
{
    /**
     * @apiDefine BookPromotion 书籍推广
     */


    /**
     * 获取书籍推广数据
     * @param Request $request
     */
    public function getBookPromotionInfo(Request $request)
    {
        $result = [];
        $end_date = $request->input('end_date');
        $book_name = $request->input('book_name');
        $begin_date = $request->input('begin_date');
        $orderBy = $request->input('orderBy');
        $company_name = $request->input('company_name');

        $manageId = $request->session()->get('manage_auth');
        if ($manageId) {
            $manageModel = ManageService::getById($manageId);
            if ($manageModel) {
                $role = $manageModel->role;
                $channels = ($role == 'admin' || $role == 'business_leader') ? [] : ChannelService::getChannelIdList($manageId);
                $param = compact('company_name', 'book_name', 'begin_date', 'end_date', 'orderBy');
                $result = SendOrderStatService::getChannelPromotionBook($channels, $param, false);
                foreach ($result as &$item) {
                    $company_id = $item->company_id;
                    $channels = Channel::getChanneIdByCompanyId($company_id);
                    $params = [
                        'channels' => $channels,
                        'book_id' => $item->bid,
                        'begin_time' => $item->date,
                        'end_time' => $item->date . ' 23:59:59'
                    ];
                    if (!$item->uv_three_day) {
                        $item->uv_three_day = 0;
                    }

                    if (!$item->percent_recharge_devide_uv_three_day) {
                        $item->percent_recharge_devide_uv_three_day = 0;
                    }
                    $item->send_order_count = SendOrderService::getPromotionCount($params);
                    $item->percent_recharge_devide_uv = number_format($item->percent_recharge_devide_uv, 2);
                }
            }
        }
        return response()->pagination(new BookPromotionTransformer(), $result);
    }


    /**
     * 设置当期推广的书籍的信息
     * @param Request $request
     * @return mixed
     */
    public function setPromotionStatus_v1(Request $request)
    {
        $cacheKey = 'setPromotionStatus';
        $book_id = $request->input('book_id');
        $promotion_status = $request->input('promotion_status', 0);

        $tempBookString = '';
        $exist = Cache::get($cacheKey, '');
        if (1 == $promotion_status) {
            $tempBookString = $exist . ',' . $book_id;
            Cache::put($cacheKey, $tempBookString, 3 * 24 * 60);
        } else {
            $book_ids = explode(',', $exist);
            foreach ($book_ids as $book_id_item) {
                if (!empty($book_id_item) && $book_id_item != $book_id) {
                    $tempBookString = $tempBookString . ',' . $book_id_item;
                }

                if ($book_id_item == $book_id) {
                    Cache::forget('infos' . $book_id);
                }
            }
            Cache::put($cacheKey, $tempBookString, 3 * 24 * 60);
        }
        return response()->success(['promotion_status' => $promotion_status, 'tempBookString' => $tempBookString]);
    }

    public function setPromotionStatus(Request $request)
    {
        //$cacheKey = 'setPromotionStatus';
        $book_id = $request->input('book_id');
        $promotion_status = $request->input('promotion_status', 0);


        if (1 == $promotion_status) {
            BookConfig::where('bid', $book_id)->update(['is_current_week_promotion' => 1]);
        } else {
            BookConfig::where('bid', $book_id)->update(['is_current_week_promotion' => 0]);
        }
        return response()->success(['promotion_status' => $promotion_status]);
    }

    public function commitPromotionStatus(Request $request)
    {
        $cacheKey = 'setPromotionStatus';
        $bidString = Cache::get($cacheKey, '');
        $book_ids = explode(',', $bidString);
        $period = BookPromotionCheckedService::getMaxPeriod();
        foreach ($book_ids as $book_id) {
            if ($book_id) {
                $book = Cache::get('infos' . $book_id);
                if ($book) {
                    $book = json_decode($book, true);
                    $book['onshelf_date'] = $book['created_at'];
                    unset($book['created_at']);
                    $book['periods'] = $period;
                    BookPromotionCheckedService::create($book);
                    Cache::forget('infos' . $book_id);
                }
            }
        }
        Cache::forget($cacheKey);
        return response()->success();
    }

    public function getPromotionBooksUnCheck(Request $request)
    {
        $res = [];
        $exist = Cache::get('setPromotionStatus', '');
        $operator = unserialize($request->session()->get('manage_user'))->nickname;
        $book_ids = explode(',', $exist);
        foreach ($book_ids as $book_id) {
            $book_info = Cache::get('infos' . $book_id);
            if ($book_info) {
                $book_info = json_decode($book_info, true);
            } else {
                $book_info = $this->getBookPromotionData($operator, $book_id);
            }
            if ($book_info) {
                $res[] = $book_info;
            }
        }
        return response()->success($res);
    }


    public function getPromotionBooksChecked(Request $request)
    {
        $periods = $request->input('periods');
        $result = BookPromotionChecked::getInfo($periods, false);
        return response()->pagination(new BookPromotionCheckedTransformer(), $result);
    }


    private function getBookPromotionData($operator, $book_id)
    {
        $book_config = BookConfigService::getBookById($book_id);

        if ($book_config) {
            $data = [];
            $data['book_id'] = $book_id;
            $data['operator'] = $operator;
            $data['size'] = $book_config->size;
            $data['status'] = $book_config->status;
            $data['author'] = $book_config->author;
            $data['book_name'] = $book_config->book_name;
            $data['cp_source'] = $book_config->cp_source;
            $data['created_at'] = date("Y-m-d H:i:s", strtotime($book_config->created_at));
            $data['is_on_shelf'] = $book_config->is_on_shelf;

            $now_time = date('Y-m-d H:i:s', strtotime(time()));
            $send_30_day_time = date('Y-m-d H:i:s', strtotime(time()) - 86400 * 30);

            $recharge_amount_in_24h_outside = SendOrderStat::getRechargeAmountByBookId(['book_id' => $book_id, 'start_time' => $send_30_day_time, 'end_time' => $now_time], true, true);
            $recharge_amount_in_24h_inside = SendOrderStat::getRechargeAmountByBookId(['book_id' => $book_id, 'start_time' => $send_30_day_time, 'end_time' => $now_time], false, true);
            $recharge_amount_in_72h_inside = SendOrderStat::getRechargeAmountByBookId(['book_id' => $book_id, 'start_time' => $send_30_day_time, 'end_time' => $now_time], false, false);
            $recharge_amount_in_72h_outside = SendOrderStat::getRechargeAmountByBookId(['book_id' => $book_id, 'start_time' => $send_30_day_time, 'end_time' => $now_time], true, false);

            //获取一个月内的总派单书
            $promotionCount = SendOrder::getDuringPromotionCountByBid($book_id, $send_30_day_time, $now_time);
            if (is_numeric($promotionCount) && $promotionCount > 0) {
                $recharge_amount_in_24h_outside = $recharge_amount_in_24h_outside / $promotionCount;
                $recharge_amount_in_24h_inside = $recharge_amount_in_24h_inside / $promotionCount;
                $recharge_amount_in_72h_inside = $recharge_amount_in_72h_inside / $promotionCount;
                $recharge_amount_in_72h_outside = $recharge_amount_in_72h_outside / $promotionCount;
            }

            $data['recharge_amount_in_24h_outside'] = $recharge_amount_in_24h_outside ? $recharge_amount_in_24h_outside : 0;
            $data['recharge_amount_in_24h_inside'] = $recharge_amount_in_24h_inside ? $recharge_amount_in_24h_inside : 0;
            $data['recharge_amount_in_72h_inside'] = $recharge_amount_in_72h_inside ? $recharge_amount_in_72h_inside : 0;
            $data['recharge_amount_in_72h_outside'] = $recharge_amount_in_72h_outside ? $recharge_amount_in_72h_outside : 0;
            Cache::put("infos" . $book_id, json_encode($data), 3 * 24 * 60);
            return $data;
        } else {
            return null;
        }
    }

    /**
     * 导出书籍推广数据
     * @param Request $request
     */
    public function exportBookPromotionInfo(Request $request)
    {
        set_time_limit(0);
        $end_date = $request->input('end_date');
        $book_name = $request->input('book_name');
        $begin_date = $request->input('begin_date');
        $orderBy = $request->input('orderBy');
        $company_name = $request->input('company_name');

        $manage_id = $request->session()->get('manage_auth');
        if ($manage_id) {
            $manageModel = ManageService::getById($manage_id);
            if ($manageModel) {
                $role = $manageModel->role;
                $channels = ($role == 'admin' || $role == 'business_leader') ? [] : ChannelService::getChannelIdList($manage_id);
                $param = compact('company_name', 'book_name', 'begin_date', 'end_date', 'orderBy');
                $result = SendOrderStatService::getChannelPromotionBook($channels, $param, true);

                header("Content-type:application/vnd.ms-excel");
                header("Content-Disposition:attachment;filename=" . "明细" . date("YmdHis") . ".csv");
                echo iconv("UTF-8", "GBK", "\"日期\",\"公司名称\",\"书本名称\",\"书本id\",\"24小时充值\",\"72小时充值\",\"注册用户数\",\"24小时UV\",\"24小时充值/24小时UV\",\"72小时UV\",\"72小时充值/72小时UV\",\"当日创建派单数\"\r\n");
                foreach ($result as $item) {
                    $company_id = $item->company_id;
                    $channels = Channel::getChanneIdByCompanyId($company_id);
                    $params = [
                        'channels' => $channels,
                        'book_id' => $item->bid,
                        'begin_time' => $item->date,
                        'end_time' => $item->date . ' 23:59:59'
                    ];
                    $item->uv_three_day = $item->uv_three_day ? $item->uv_three_day : 0;
                    if (!$item->percent_recharge_devide_uv_three_day) {
                        $item->percent_recharge_devide_uv_three_day = 0;
                    }
                    $item->send_order_count = SendOrderService::getPromotionCount($params);
                    $item->percent_recharge_devide_uv = number_format($item->percent_recharge_devide_uv, 2);

                    echo("\"" . mb_convert_encoding($item->date, "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($item->company_name, "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($item->book_name, "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($item->bid, "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($item->recharge_amount_in_one_day, "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($item->recharge_amount_in_three_days, "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($item->register_user_num, "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($item->uv_one_day, "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($item->percent_recharge_devide_uv, "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($item->uv_three_day, "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($item->percent_recharge_devide_uv_three_day, "GBK", "UTF-8") . "\",");
                    echo("\"" . $item->send_order_count . "\"\r\n");
                }
            }
        }
        exit();
    }
}