<?php
/**
 * Created by PhpStorm.
 * User: hp
 * Date: 2017/11/22
 * Time: 11:36
 */

namespace App\Http\Controllers\Channel\SendOrder;

use App\Http\Controllers\Channel\BaseController;

use App\Modules\Book\Models\BookConfig;
use App\Modules\Book\Services\BookConfigService;
use App\Modules\Book\Services\BookSubscribleChapterService;
use App\Modules\Book\Services\ChapterService;
use App\Modules\SendOrder\Services\SendOrderService;
use Hashids;
use Illuminate\Http\Request;
use PhpOffice\PhpSpreadsheet\IOFactory;
use DB;


class SendOrderBatchHandleController extends BaseController
{
    /**
     * @apiDefine sendOrder 派单
     */
    public function downloadTemplate(Request $request) {
        $bids = $request->input('bids',[]);
        if(!$bids) {
            return response()->error('PARAM_EMPTY');
        }
        if(!is_array($bids)) {
            return response()->error('PARAM_ERROR');
        };
        foreach ($bids as $key=>$bid) {
            $bids[$key] = Hashids::decode($bid)[0];
        }
        $header = ['书本编号','派单渠道名称','成本', '书名','阅读章节原文','派单类型','推广类型'];
        $books = BookConfig::leftjoin('books','books.id','=','book_configs.bid')
            ->leftjoin('chapters','chapters.id','=','book_configs.recommend_cid')
            ->select(['books.id as bid','book_configs.book_name','chapters.sequence'])
            ->whereIn('book_configs.bid',$bids)
            ->get();
        $data = array();
        foreach ($books as $book) {
            $data[] = array(
                Hashids::encode($book->bid),
                '','',
                $book->book_name,
                $book->sequence,
                1,
                1
            );
        }

        saveExcelData($header,$data,'',[
            ['cell'=>'I2','contents'=>'1、推广类型一栏请填写1或者2 ,1代表微信，2代表站外'],
            ['cell'=>'I3','contents'=>'2、派单类型一栏请填写1或者2 ,1代表内部，2代表外部'],
            ['cell'=>'I4','contents'=>'3、阅读章节原文默认为推荐章节，原文链接为当前章节'],
            ['cell'=>'I5','contents'=>'4、同一书本编号可产生多条记录，上传后一条记录对应产生一条派单链接'],
        ]);
    }

    public function importSendOrders(Request $request) {
        if(!$request->hasFile('send_orders')) {
            return response()->error('PARAM_ERROR');
        }
        $file_obj = $request->file('send_orders');
        $spreadsheet = IOFactory::load($file_obj->path());
        $sheetData = $spreadsheet->getActiveSheet(0)->toArray(null, true, true, true);
        //\Log::info('sheetData:'.json_encode($sheetData));
        $sheetDataLength = count($sheetData);
        $distribution_channel_id = $this->getChannelId();
        DB::beginTransaction();
        try{
            for($i=2;$i<=$sheetDataLength;$i++) {
                $chapter_sequnce = $sheetData[$i]['E'];
                $book_id = $sheetData[$i]['A'];
                \Log::info('book_id'.$book_id);
                if($book_id){
                    $bid = Hashids::decode($book_id)[0];
                    if($bid==2423 && time() >= strtotime('2018-10-10 00:00:00') && time() <= strtotime('2018-10-15 23:59:59')) {
                        DB::rollback();
                        return response()->error('UPLOAD_FAILED');
                        //return response()->error('PARAM_ERROR');
                    }
                    $chapter_info = ChapterService::getChapterInfoByBidAndSeq($bid,$chapter_sequnce);
                    $chapter_id = $chapter_info->id;
                    $book_info = BookConfig::getBookById($bid);
                    $subscribe_chapter_seq =$this->getSubscribeChapterNum($book_info,$distribution_channel_id);
                    $subscribe_chapter_info = ChapterService::getChapterInfoByBidAndSeq($bid,$subscribe_chapter_seq);
                    $name = $sheetData[$i]['B'];
                    $cost = $sheetData[$i]['C']?$sheetData[$i]['C']:0;

                    $book_name = $sheetData[$i]['D'];
                    $qr_code_id =  '';
                    $chapter_name = $chapter_info?$chapter_info->name:'';
                    $channel_type = '';
                    $promotion_type = $sheetData[$i]['F']==1?'INTERNAL':'EXTERNAL';
                    $subscribe_chapter_id = $subscribe_chapter_info ? $subscribe_chapter_info->id : '';
                    //$subscribe_chapter_seq = $book_info->force_subscribe_chapter_seq ? $book_info->force_subscribe_chapter_seq : '';
                    $subscribe_chapter_name = $subscribe_chapter_info ? $subscribe_chapter_info->name : '';
                    $promotion_point = $sheetData[$i]['G']==1?1:2;
                    if (!in_array($promotion_point, [1, 2])) {
                        $promotion_point = 1;
                    }

                    //if (!$name || !$channel_type || !$promotion_type || !$book_id || !$book_name || !$chapter_id || !$chapter_name || !$subscribe_chapter_id || !$subscribe_chapter_seq || !$subscribe_chapter_name) return response()->error('PARAM_EMPTY');

                    if (empty($qr_code_id)) {
                        $qr_code_id = 0;
                    }
                    $redirect_url = "/reader?bid={$book_id}&cid={$chapter_info->id}";
                    $book_id = Hashids::decode($book_id)[0];
                    if ($promotion_point == 2) {
                        $domain = 'chunnuan555.com';
                    } else {
                        $domain = $this->getDomainByBid($book_id);
                    }
                    $charge_type = $this->getBookChargeTypeByBid($book_id);
                    $sendOrder = SendOrderService::createFromDirectory(compact(
                        'name',
                        'channel_type',
                        'promotion_type',
                        'charge_type',
                        'cost',
                        'domain',
                        'book_id',
                        'qr_code_id',
                        'book_name',
                        'chapter_id',
                        'subscribe_chapter_id',
                        'subscribe_chapter_name',
                        'subscribe_chapter_seq',
                        'chapter_name',
                        'distribution_channel_id',
                        'redirect_url',
                        'promotion_point'
                    ));

                    // $promotion_url = '/yun/' . $sendOrder->id;
                    if ($promotion_point == 2) {
                        $promotion_url = 'https://bsite' . encodeDistributionChannelId($distribution_channel_id) . '.chunnuan555.com/yun/' . $sendOrder->id;
                    } else {
                        $promotion_url = 'https://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . $this->getDomainByBid($book_id) . '/yun/' . $sendOrder->id;
                    }
                }

            }
        }catch (\Exception $e) {
            DB::rollback();
            \Log::error($e->getMessage());
            return response()->error('UPLOAD_FAILED',$e->getMessage());
        }
        DB::commit();
        return response()->success();

    }

    /**
     * 根据图书id获取域名
     * @param $bid
     */
    function getDomainByBid($bid = '')
    {
        $domain = 'chunnuan555.com';
        return $domain;
    }

    /**
     * 根据图书id获取图书的收费类型
     * @param string $bid
     */
    function getBookChargeTypeByBid($bid = '')
    {
        $charge_type = '';
        $bookConfig = BookConfigService::getBookById($bid);
        if ($bookConfig) {
            $charge_type = $bookConfig->charge_type;
        }
        return $charge_type;
    }

    protected function getSubscribeChapterNum($book,$distribution_channel_id)
    {

        //渠道设置的强关
        $subscribe = BookSubscribleChapterService::getSubcribleChapter($book->bid, $distribution_channel_id);
        if ($subscribe) {
            return (isset($subscribe->subscribe_chapter_id) && $subscribe->subscribe_chapter_id > 0) ? $subscribe->subscribe_chapter_id : $book->force_subscribe_chapter_seq;
        }
        //默认强关
        return $book->force_subscribe_chapter_seq;
    }

}
