<?php

namespace App\Http\Controllers\Cp\Book;

use App\Http\Controllers\Cp\BaseController;
use App\Modules\CpSub\Services\CpSubService;
use App\Modules\CpUser\Services\CpUserService;
use Illuminate\Http\Request;
use App\Modules\Book\Services\CpExceptBookService;
use Storage;

class BookController extends BaseController
{

    /**
     * @apiVersion 1.0.0
     * @apiDescription 书籍列表
     * @api {POST} book/index 书籍列表
     * @apiGroup Book
     * @apiName index
     * @apiParam {String}  book_name 书名.
     * @apiParam {String}  book_id 书籍id.
     * @apiParam {String}  start_time 开始时间.
     * @apiParam {String}  end_time 结束时间.
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {}
     *     }
     */
    public function index(Request $request)
    {
        $params = array();

        $params['cp_user_id'] = session('cp_manage_auth');
        if ($params['cp_user_id'] == 1) {
            $params['cp_user_id'] = $request->get('cp_user_id') ? $request->get('cp_user_id') : $params['cp_user_id'];
        }
        $params['book_name'] = $request->has('book_name') ? $request->get('book_name') : '';
        $params['book_id'] = $request->has('book_id') ? $request->get('book_id') : '';
        $params['start_time'] = $request->has('start_time') ? $request->get('start_time') : date('Y-m', strtotime('- 3 month'));
        $params['end_time'] = $request->has('end_time') ? $request->get('end_time') : date('Y-m');
        \Log::info($params);

        $all_bid = CpExceptBookService::getCpBidList($params['cp_user_id']);
        if ($all_bid) {
            $params['all_bid'] = $all_bid;
        } else {
            $params['all_bid'] = [];
        }

        if ($params['cp_user_id'] == 1) {
            $params['cp_user_id'] = '';
        }
        $records = CpSubService::getCpSubs($params);
        $cps = CpExceptBookService::getAllcp();
        $cp_user = CpUserService::getCpUserById($params['cp_user_id']);
        \Log::info('$cp_user');
        \Log::info($cp_user);
        $params['cp'] = isset($cp_user['username']) ? $cp_user['username'] : '';
        \Log::info('params');
        \Log::info($params);
        $is_show_total_amount = isset($cp_user->is_show_total_amount) ? $cp_user->is_show_total_amount : '0';

        return view('cp.web.book.index', compact('records', 'params', 'is_show_total_amount', 'cps'));
    }

    public function subscribe_detail()
    {

    }

    /**
     * cp书籍导出
     * @param Request $request
     */
    public function record_export(Request $request)
    {
        set_time_limit(0);
        $params = array();
//     	\Log::info('cp_manage_auth');
//     	\Log::info(session('cp_manage_auth'));

        $params['cp_user_id'] = session('cp_manage_auth');
        $params['book_name'] = $request->has('book_name') ? $request->get('book_name') : '';
        $params['book_id'] = $request->has('book_id') ? $request->get('book_id') : '';
        $params['start_time'] = $request->has('start_time') ? $request->get('start_time') : date('Y-m', strtotime('- 3 month'));
        $params['end_time'] = $request->has('end_time') ? $request->get('end_time') : date('Y-m');
        \Log::info($params);

        $all_bid = CpExceptBookService::getCpBidList($params['cp_user_id']);
        if ($all_bid) {
            $params['all_bid'] = $all_bid;
        } else {
            $params['all_bid'] = [];
        }

        if ($params['cp_user_id'] == 1) {
            \Log::info('isis_1:' . $params['cp_user_id']);
            $params['cp_user_id'] = '';
        }
        \Log::info($params);
        $records = CpSubService::getCpSubs($params, true);
        //\Log::info('book_export_records');
        //\Log::info($records);
//     	$cp_user = CpUserService::getCpUserById($params['cp_user_id']);
//     	\Log::info('$cp_user');\Log::info($cp_user);
//     	$is_show_total_amount = isset($cp_user->is_show_total_amount)?$cp_user->is_show_total_amount:'0';

        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=" . "cp书籍列表" . date("YmdHis") . ".csv");
        if (session('cp_manage_auth') == 1) {
            echo iconv("UTF-8", "GBK", "\"月份\",\"统计时间(截止零点)\",\"渠道\",\"书名\",\"书籍ID\",\"本月订阅量(书币)\",\"可分成金额\",\"最终分成金额\" \r\n");
        } else {
            echo iconv("UTF-8", "GBK", "\"月份\",\"统计时间(截止零点)\",\"书名\",\"书籍ID\",\"本月订阅量(书币)\",\"可分成金额\",\"最终分成金额\" \r\n");
        }

        /*$filename = 'cptotal' . date('YmdHis') . '.csv';
        if (session('cp_manage_auth') == 1){
            Storage::append($filename, mb_convert_encoding("月份,统计时间(截止零点),渠道,书名,书籍ID,本月订阅量(书币),可分成金额,最终分成金额", 'gbk'));
        }else{
            Storage::append($filename, mb_convert_encoding("月份,统计时间(截止零点),书名,书籍ID,本月订阅量(书币),可分成金额,最终分成金额", 'gbk'));
        }
        $str = '';
        $i = 1;
        foreach ($records as $record) {
            $month = isset($record->month) ? $record->month : "";
            $calculate_date = isset($record->calculate_date) ? $record->calculate_date : "";
            $cp_source = '';
            if (session('cp_manage_auth') == 1) {
                $cp_source = isset($record->cp_source) ? $record->cp_source : "";
            }
            $book_name =  isset($record->book_name) ? $record->book_name : "";
            $bid = isset($record->bid) ? $record->bid : "";
            $current_month_book_num = isset($record->current_month_book_num) ? $record->current_month_book_num : "";
            $total_amount = isset($record->total_amount) ? $record->total_amount : "";
            $available_amount = isset($record->available_amount) ? $record->available_amount : "";
            $last_amount = isset($record->last_amount) ? $record->last_amount : "";
            if(session('cp_manage_auth') == 1){
                $str .= "{$month},{$calculate_date},{$cp_source},{$book_name},{$bid},{$total_amount},{$available_amount},{$last_amount}\r\n";
            }else{
                $str .= "{$month},{$calculate_date},{$book_name},{$bid},{$total_amount},{$available_amount},{$last_amount}\r\n";
            }

            if(($i++)%100 == 0){
                Storage::append($filename, mb_convert_encoding($str, 'gbk'));
                $str = '';
            }
        }
        Storage::append($filename, mb_convert_encoding($str, 'gbk'));
        return response()->download(storage_path('app/' . $filename))->deleteFileAfterSend(true);*/


        if ($records) {
            foreach ($records as $record) {
                echo("=\"" . (iconv('utf-8', 'gbk', isset($record->month) ? $record->month : "")) . "\",");
                echo("=\"" . (iconv('utf-8', 'gbk', isset($record->calculate_date) ? $record->calculate_date : "")) . "\",");
                if (session('cp_manage_auth') == 1) {
                    echo("\"" . (iconv('utf-8', 'gbk', isset($record->cp_source) ? $record->cp_source : "")) . "\",");
                }
                echo("\"" . (iconv('utf-8', 'gbk//IGNORE', isset($record->book_name) ? $record->book_name : "")) . "\",");
                echo("\"" . (isset($record->bid) ? $record->bid : "") . "\",");
                // 实际书币不展示，展示折算过的值
                //echo("\"" . (isset($record->current_month_book_num) ? $record->current_month_book_num : "") .  "\",");
                echo("\"" . (iconv('utf-8', 'gbk', isset($record->total_amount) ? $record->total_amount : "")) . "\",");
                echo("\"" . (isset($record->available_amount) ? $record->available_amount : "") . "\",");
                echo("\"" . (isset($record->last_amount) ? $record->last_amount : "") . "\"\r\n");
            }

        }
        exit();
    }

    public function exceptBook(Request $request)
    {
        $cp = $request->get('cp');
        $where = [];
        if ($cp)
            $where['username'] = $cp;
        $info = CpExceptBookService::getList($where);
        return view('cp.web.book.except', ['data' => $info, 'param' => $where]);
    }

    public function getBooks(Request $request)
    {
        $cp_user = $request->input('cp_user');
        $name = $request->input('name');
        $res = CpExceptBookService::getBookByCp($cp_user, $name);
        $str = '';
        if ($res) {
            $format = '<button type="button" class="btn btn-default btn-block js-list" data-id="%s">%s</button>';
            foreach ($res as $v) {
                $str .= sprintf($format, $v->id, $v->name);
            }
        }
        return response()->success($str);
    }

    public function exceptAddView(Request $request)
    {
        if (session('cp_manage_auth') != 1) {
            return redirect('book/index');
        }
        $cps = CpExceptBookService::getAllcp();
        return view('cp.web.book.exceptadd', ['cps' => $cps]);
    }

    public function exceptAddPost(Request $request)
    {
        if (session('cp_manage_auth') != 1) {
            return redirect('book/index');
        }
        $data = $request->all();
        if (empty($data['cp_user_id']) || empty($data['book_name']) || empty($data['bid'])) {
            return back()->withErrors(['message' => '缺少参数']);
        }
        IF (CpExceptBookService::isHadExcept($data['cp_user_id'], $data['bid'])) {
            return back()->withErrors(['message' => '已经添加过了']);
        }
        CpExceptBookService::create($data);
        return redirect('book/exceptadd')->with(['message' => '添加成功', 'cp_user_id' => $data['cp_user_id']]);
    }

    public function deleteExcept(Request $request)
    {
        if (session('cp_manage_auth') != 1) {
            return redirect('book/index');
        }
        $id = $request->input('id');
        if ($id) {
            CpExceptBookService::deleteExcept($id);
            return redirect('book/except')->with(['message' => '删除成功']);
        }

        return back()->withErrors(['message' => '缺少参数']);
    }

    public function bookCpList(Request $request)
    {
        if (session('cp_manage_auth') != 1) {
            return redirect('book/index');
        }
        $old_name = $request->get('old_name');
        $new_name = $request->get('new_name');
        $result = CpExceptBookService::getBookCpList($old_name, $new_name);
        $on_shelf_status = [
            ['未上架', 'bg-danger'],
            ['内部上架', 'bg-success'],
            ['外部上架', 'bg-primary'],
            ['屏蔽', 'bg-warning'],
            ['版权到期下架', 'bg-info']
        ];
        return view('cp.web.book.bookCpList', ['data' => $result, 'param' => compact('old_name', 'new_name'), 'on_shelf_status' => $on_shelf_status]);
    }

    public function editCp(Request $request)
    {
        if (session('cp_manage_auth') != 1) {
            return response()->json(['code' => 0, 'msg' => '']);
        }
        $param = $request->except('_url');
        $res = checkParam($param, ['id', 'cpid']);
        if ($res) {
            return response()->json(['code' => 0, 'msg' => $res . '不能为空']);
        }
        $cp_info = CpUserService::getCpUserById($param['cpid']);
        $param['cpname'] = $cp_info->username;
        CpExceptBookService::editBookCp($param['id'], $param['cpid'], $param['cpname']);
        return response()->json(['code' => 1, 'msg' => 'ok']);
    }

    public function cpDataStats(Request $request){
        if (session('cp_manage_auth') != 1) {
            return redirect('book/index');
        }
        $cps = CpExceptBookService::getAllcp();
        $param = $request->except('_url');
        $where = [];
        $whereIn = [];
        if(isset($param['bid']) && !empty($param['bid'])) {
            $whereIn = explode(',',$param['bid']);
        }

        if(isset($param['book_name']) && !empty($param['book_name'])){
            $where[] = ['book_configs.book_name','like','%'.trim($param['book_name']).'%'];
        }

        if(isset($param['cp_source']) && !empty($param['cp_source'])){
            $where[] = ['book_configs.cp_source','=',$param['cp_source']];
        }

        if(isset($param['start_time']) && !empty($param['start_time'])){
            $where[] = ['book_order_statistical.day','>=',$param['start_time']];
        }

        if(isset($param['end_time']) && !empty($param['end_time'])){
            $where[] = ['book_order_statistical.day','<=',$param['end_time']];
        }

        if(isset($param['groupby']) && !empty($param['groupby'])){
            \Log::info($param['groupby']);
        }
        $exporparam = $param;
        $exporparam['export'] = 1;

        if(isset($param['export']) && !empty($param['export'])){
            $result = CpExceptBookService::cpDataStats($where,$whereIn,[],true);
            $filename = 'cptotal'.date('YmdHis').'.csv';

            Storage::append($filename,mb_convert_encoding("图书bid,书名,所属cp,日期,书币,月份,年份",'gbk'));
            $str = '';
            foreach ($result as $val){
                $str .= "{$val->bid},{$val->book_name},{$val->cp_source},{$val->day},{$val->charge_balance},{$val->month},{$val->year}\r\n";
            }
            Storage::append($filename,mb_convert_encoding($str,'gbk'));
            return response()->download(storage_path('app/'.$filename))->deleteFileAfterSend(true);
        }else{
            $result = CpExceptBookService::cpDataStats($where,$whereIn,[]);
        }
        return view('cp.web.book.cpDataStats',['cps'=>$cps,'param'=>$param,'data'=>$result,'exporparam'=>$exporparam]);
    }

}