<?php
/**
 * Created by PhpStorm.
 * User: hp
 * Date: 2017/12/1
 * Time: 17:18
 */

namespace App\Http\Controllers\Manage\Channel;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Manage\Channel\Transformers\ChannelBookSellTransformer;
use App\Http\Controllers\Manage\Channel\Transformers\ChannelSellPlatformTransformer;
use App\Modules\Book\Models\Book;
use App\Modules\Channel\Models\ChannelBookSell;
use App\Modules\Channel\Services\ChannelSellPlatformService;
use DB;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use PhpOffice\PhpSpreadsheet\IOFactory;

/**
 * Class ChannelSellPlatformController
 * @package App\Http\Controllers\Manage\Channel
 */
class ChannelSellPlatformController extends Controller
{
    /**
     * 根据id 查找信息
     * @param Request $request
     * @return mixed
     */
    function getChannelSellPlatformById(Request $request)
    {
        $id = $request->has('id') ? $request->input('id') : '';
        if (empty($id)) {
            return response()->error('PARAM_EMPTY');
        }
        if (!is_numeric($id)) {
            return response()->error("PARAM_ERROR");
        }

        $data = ChannelSellPlatformService::getById($id);
        return response()->item(new ChannelSellPlatformTransformer(), $data);
    }

    /**
     * 根据code查找信息
     * @param Request $request
     * @return mixed
     */
    function getChannelSellPlatformByCode(Request $request)
    {
        $code = $request->has('code') ? $request->input('code') : '';
        if (empty($code)) {
            return response()->error('PARAM_EMPTY');
        }

        if (!preg_match("/^[a-zA-Z\s]+$/", $code)) {
            return response()->error('PARAM_ERROR');
        }

        $data = ChannelSellPlatformService::getByCode($code);
        return response()->item(new ChannelSellPlatformTransformer(), $data);
    }

    /**
     * 获取列表
     * @param Request $request
     * @return mixed
     */
    function getList(Request $request)
    {
        $data = ChannelSellPlatformService::getList();
        return response()->pagination(new ChannelSellPlatformTransformer(), $data);
    }

    /**
     * 添加或更新信息
     * @param Request $request
     * @return mixed
     */
    function createOrUpdateChannelSellPlatform(Request $request)
    {
        $name = $request->has('name') ? $request->input('name') : '';
        $code = $request->has('code') ? $request->input('code') : '';
        $desc = $request->has('desc') ? $request->input('desc') : '';
        $bill_type = $request->has('bill_type') ? $request->input('bill_type') : '';

        if (!$code) {
            return response()->error('PARAM_EMPTY');
        }

        if (!preg_match("/^[a-zA-Z\s]+$/", $code)) {
            return response()->error('PARAM_ERROR');
        }

        $params = [];
        if ($name) {
            $params['name'] = $name;
        }

        if ($desc) {
            $params['desc'] = $desc;
        }

        if ($bill_type) {
            $params['bill_type'] = $bill_type;
        }

        $params['code'] = $code;

        $data = ChannelSellPlatformService::getByCode($code);
        //存在就更新，不存在就添加
        if ($data) {
            $res = ChannelSellPlatformService::updateById($data->id, $params);
        } else {
            $res = ChannelSellPlatformService::addInfo($params);
        }

        if ($res) {
            return response()->success();
        } else {
            return response()->error("HANDLE_FAILED");
        }
    }

    public function importChannelBookSell(Request $request)
    {
        if (!$request->hasFile('channel_book_sell')) {
            return response()->error('PARAM_ERROR');
        }
        $file_obj = $request->file('channel_book_sell');
        $spreadsheet = IOFactory::load($file_obj->path());
        $sheetData = $spreadsheet->getActiveSheet(0)->toArray(null, true, true, true);
        \Log::info('sheetData:' . json_encode($sheetData));
        $sheetDataLength = count($sheetData);
        DB::beginTransaction();
        try {
            for ($i = 2; $i <= $sheetDataLength; $i++) {
                $plaform = $sheetData[$i]['A'];
                $zsy_bid = $sheetData[$i]['B'];
                $book_name = $sheetData[$i]['C'];
                $plaform_code = $sheetData[$i]['D'];
                $amount = $sheetData[$i]['E'];
                $sub_num = $sheetData[$i]['F'];
                $date = $sheetData[$i]['G'];
                $month = $sheetData[$i]['H'];

                if (!$plaform || !$zsy_bid || !$book_name || !$plaform_code
                    || !$date || !$sub_num || !$month) {
                    return response()->error('PARAM_EMPTY');
                }

                $channelSellPlatform = ChannelSellPlatformService::getByCode($plaform_code);
                if ($channelSellPlatform) {
                    $is_checked = 0;
                    $is_pushed = 0;

                    $bill_type = $channelSellPlatform->bill_type;
                    $data = compact(
                        'plaform', 'zsy_bid', 'book_name', 'plaform_code',
                        'amount', 'sub_num', 'date', 'month', 'is_checked', 'is_pushed', 'bill_type'
                    );
                    ChannelBookSell::addInfo($data);
                } else {
                    DB::rollback();
                    return ['code'=>304,'msg'=>'第'.$i.'行填写的平台code有误，数据已回滚，请更改后重新上传！'];
                }
            }
        } catch (\Exception $e) {
            DB::rollback();
            \Log::error($e->getMessage());
            return response()->error('UPLOAD_FAILED', $e->getMessage());
        }
        DB::commit();
        return response()->success();
    }

    /**
     * 获取列表
     * @param Request $request
     * @return mixed
     */
    function getChannelBookShellList(Request $request)
    {
        $data = ChannelBookSell::getList();
        return response()->pagination(new ChannelBookSellTransformer(), $data);
    }

    function updateStatus(Request $request)
    {
        $id = $request->has('id') ? $request->input('id') : '';
        $isPush = $request->has('isPush') ? $request->input('isPush') : '';
        $isChecked = $request->has('isChecked') ? $request->input('isChecked') : '';
        if (!$id) {
            return response()->error('PARAM_EMPTY');
        }

        if (!$isPush && !$isChecked) {
            return response()->error('PARAM_ERROR');
        }
        $params = [];
        if ($isPush) {
            $params['is_pushed'] = $isPush;
        }

        if ($isChecked) {
            $params['is_checked'] = $isChecked;
        }

        \Log::info('id is: ' . $id);
        $data = ChannelBookSell::getById($id);
        if ($isChecked) {
            //已审核通过
            if ($data && 1 == $data->is_checked) {
                return response()->error("ALREADY_CHECKED");
            } else {
                $res = ChannelBookSell::updateStatus($id, $params);
                if ($res) {
                    return response()->success();
                } else {
                    return response()->error("HANDLE_FAILED");
                }
            }
        } else {
            //如果没有审核通过进行推送
            if (!$data || (1 != $data->is_checked && 1 == $isPush)) {
                return response()->error("NOT_CHECKED");
            }

            //已经推送了
            if ($data && 1 == $isPush && 1 == $data->is_pushed) {
                return response()->error("ALREADY_PUSHED");
            }

            if ($data && 1 == $isPush && 1 == $data->is_checked) {
                $content = $this->uploadToYcsd($data);
                \Log::info('content is: ' . $content);
                if ($content) {
                    $content = json_decode($content);
                    if (isset($content->code)) {
                        if ($content->code == 0) {
                            \Log::info("推送到原创成功");
                            ChannelBookSell::updateStatus($id, $params);
                            return response()->success();
                        } else {
                            $data = ['code' => $content->code, 'msg' => $content->msg, 'data' => ''];
                            return response()->json($data);
                        }
                    }
                }
            }
            return response()->error("HANDLE_FAILED");
        }
    }

    function uploadToYcsd($data)
    {
        $content = '';
        try {
            $bill_type = $data->bill_type;
            $book = Book::getBook($data->zsy_bid);
            $daytime = ($bill_type == 'month') ? ($data->month . '00') : $data->date;

            $params = [
                'daytime' => $daytime,
                'amount' => $data->amount,
                'platform' => $data->plaform,
                'lybid' => $book ? $book->ly_bid : '',
                'platform_code' => $data->plaform_code,
                'itype' => ($bill_type == 'month') ? 1 : 0,
                'sign' => md5($daytime . 'ycsd2015')
            ];

            $path = 'http://www.ycsd.cn/ycsdApp/own/?action=getOutChannelPay';
            $client = new Client(['timeout' => 3.0,]);
            \Log::info($params);
            $response = $client->request('POST', $path, ['form_params' => $params]);
            $resultCode = $response->getStatusCode();
            \Log::info("code is: " . $resultCode);
            if ($resultCode == 200 || $resultCode == 302) {
                $content = $response->getBody()->getContents();
            }
        } catch (\Exception $e) {
            \Log::info($e->getMessage());
        }
        return $content;
    }
}