<?php

namespace App\Http\Controllers\Manage\Welfare;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Manage\Welfare\Transformer\WelfarePromotionBookTransform;
use App\Modules\Welfare\Models\WelfareBook;
use App\Modules\Welfare\Services\WelfareBookService;
use Cookie;
use DB;
use Illuminate\Http\Request;
use OSS\Core\OssException;
use OSS\OssClient;
use Storage;

class WelfareController extends Controller
{

    /**
     * @apiDefine Welfare 福利
     */

    /**
     * @apiVersion 1.0.0
     * @api {POST} Welfare/addWelfarePromotionBook  添加活动推广书籍
     * @apiGroup Welfare
     * @apiName addWelfarePromotionBook
     * @apiParam {String}  bid 书本id
     * @apiParam {String}  book_name 书本名称
     * @apiParam {String}  charge_rate  付费率
     * @apiParam {String}  is_important 是否是重要渠道(1:是，0:否)
     * @apiParam {String}  channer_user_id 渠道id
     * @apiParam {String}  force_subscribe_rate 强关率
     * @apiParam {String}  data_img 数据图片url
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":{ }
     *     }
     */
    public function add_welfare_promotion_book(Request $request)
    {
//        $data_img = $request->hasFile('data_img') ? $request->file('data_img') : null;
        $data_img = $request->has('data_img') ? $request->input('data_img') : '';

        $is_enable = 1;
        $bid = $request->has('bid') ? $request->input('bid') : '';
        $book_name = $request->has('book_name') ? $request->input('book_name') : '';
        $charge_rate = $request->has('charge_rate') ? $request->input('charge_rate') : '';
        $is_important = $request->has('is_important') ? $request->input('is_important') : '';
        $channer_user_id = $request->has('channer_user_id') ? $request->input('channer_user_id') : 0;
        $force_subscribe_rate = $request->has('force_subscribe_rate') ? $request->input('force_subscribe_rate') : '';

        if (!$bid || !$book_name || !$charge_rate || !is_numeric($is_important) || !$force_subscribe_rate) {
            return response()->error('PARAM_EMPTY');
        }

        if ($data_img) {
//            $file_path = $data_img->path();
//            $extension = $data_img->extension();
//            $file_name = date('YmdHis') . $bid . '.' . $extension;
//            $result = $this->ossObject()->uploadFile(env('OSS_BUCKET', 'zhuishuyun'), 'distribution/welfare/' . $file_name, $file_path);
//            $imageUrl = str_ireplace('zhuishuyun.oss-cn-hangzhou.aliyuncs.com', 'cdn-novel.iycdm.com', $result['oss-request-url']);
//            $data_img = str_ireplace('http://', 'https://', $imageUrl);

            $welfareBook = WelfareBook::createWelfareBook(compact('bid', 'book_name', 'charge_rate', 'data_img', 'is_enable', 'is_important', 'channer_user_id', 'force_subscribe_rate'));
            if ($welfareBook) {
                return response()->success();
            } else {
                return response()->error("HANDLE_FAILED");
            }
        } else {
            return response()->error('PARAM_EMPTY');
        }
    }

    private function ossObject()
    {
        $accessKeyId = env('OSS_ACCESS_ID');
        $accessKeySecret = env('OSS_ACCESS_KEY');
        $endpoint = env('OSS_END_POINT');
        $ossClient = null;
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        } catch (OssException $e) {
            return null;
        }
        return $ossClient;
    }


    /**
     * @apiVersion 1.0.0
     * @api {get} Welfare/getWelfarePromotionBook  添加活动推广书籍
     * @apiGroup Welfare
     * @apiName getWelfarePromotionBook
     * @apiSuccess {String}  bid 书本id
     * @apiSuccess {String}  book_name 书本名称
     * @apiSuccess {String}  charge_rate  付费率
     * @apiSuccess {String}  is_important 是否是重要渠道(1:是，0:否)
     * @apiSuccess {String}  channer_user_id 渠道id
     * @apiSuccess {String}  updated_at 更新时间
     * @apiSuccess {String}  created_at 创建时间
     * @apiSuccess {String}  force_subscribe_rate 强关率
     * @apiSuccess {String}  data_img 数据图片url
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":
     *            [
     *                  {
     * "                "  bid": "11111",
     *                    "book_name": "图书1111",
     *                    "charge_rate":"75%"
     *                    "is_important": "1",
     *                    "channer_user_id": 1111,
     *                    "force_subscribe_rate": "9%",
     *                    "created_at": "2018-6-16 12:12;12"
     *                    "updated_at": "2018-6-16 12:12;12"
     *                    "data_img": "http://www.baidu.com",
     *                  },
     *                  {
     *                    "bid": "11111",
     *                    "book_name": "图书1111",
     *                    "charge_rate":"75%"
     *                    "is_important": "1",
     *                    "channer_user_id": 1111,
     *                    "created_at": "2018-6-16 12:12;12"
     *                    "updated_at": "2018-6-16 12:12;12"
     *                    "force_subscribe_rate": "9%",
     *                    "data_img": "http://www.baidu.com",
     *                 }.
     *            ]
     *     }
     */
    public function get_welfare_promotion_books(Request $request)
    {
        $is_important_channel = $request->has('is_important') ? $request->input('is_important') : 0;
        $id = $request->has('id') ? $request->input('id') : 0;
        $params = ['is_important' => $is_important_channel, 'id' => $id];
        $data = WelfareBookService::getWelfarePromotionBooks($params, false);
        return response()->pagination(new WelfarePromotionBookTransform(), $data);
    }

    /**
     * @api {GET} Welfare/exportWelfarePromotionBook  导出活动推广书籍
     * @apiSuccess {String}  bid 书本id
     * @apiSuccess {String}  book_name 书本名称
     * @apiSuccess {String}  charge_rate  付费率
     * @apiSuccess {String}  is_important 是否是重要渠道(1:是，0:否)
     * @apiSuccess {String}  channer_user_id 渠道id
     * @apiSuccess {String}  updated_at 更新时间
     * @apiSuccess {String}  created_at 创建时间
     * @apiSuccess {String}  force_subscribe_rate 强关率
     * @apiSuccess {String}  data_img 数据图片url
     * @apiSuccessExample {json} Success-Response:
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":
     *            [
     *                  {
     * "                "  bid": "11111",
     *                    "book_name": "图书1111",
     *                    "charge_rate":"75%"
     *                    "is_important": "1",
     *                    "channer_user_id": 1111,
     *                    "force_subscribe_rate": "9%",
     *                    "created_at": "2018-6-16 12:12;12"
     *                    "updated_at": "2018-6-16 12:12;12"
     *                    "data_img": "http://www.baidu.com",
     *                  },
     *                  {
     *                    "bid": "11111",
     *                    "book_name": "图书1111",
     *                    "charge_rate":"75%"
     *                    "is_important": "1",
     *                    "channer_user_id": 1111,
     *                    "created_at": "2018-6-16 12:12;12"
     *                    "updated_at": "2018-6-16 12:12;12"
     *                    "force_subscribe_rate": "9%",
     *                    "data_img": "http://www.baidu.com",
     *                 }.
     *            ]
     *     }
     * @return mixed
     */
    function export_welfare_promotion_books(Request $request)
    {
        $is_important_channel = $request->has('is_important') ? $request->input('is_important') : 0;
        $params = ['is_important' => $is_important_channel];
        $data = WelfareBookService::getWelfarePromotionBooks($params, true);
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=" . "推广书籍信息" . date("YmdHis") . ".csv");

        echo iconv("UTF-8", "GBK", "\"id\",\"图书id\",\"图书名称\",\"付费率\",\"强关率\",\"创建时间\",\"最近修改时间\",\"是否为重要渠道\",\"数据图片url\"\r\n");
        if ($data) {
            foreach ($data as $item) {
                echo("\"" . iconv("UTF-8", "GBK", ($item->id ? $item->id : "未填")) . "\",");
                echo("\"" . iconv("UTF-8", "GBK", ($item->bid ? $item->bid : "未填")) . "\",");
                echo("\"" . iconv("UTF-8", "GBK", ($item->book_name ? $item->book_name : "未填")) . "\",");
                echo("\"" . iconv("UTF-8", "GBK", ($item->charge_rate ? $item->charge_rate : "未填")) . "\",");
                echo("\"" . iconv("UTF-8", "GBK", ($item->force_subscribe_rate ? $item->force_subscribe_rate : "未填")) . "\",");
                echo("\"" . iconv("UTF-8", "GBK", ($item->created_at->toDateTimeString())) . "\",");
                echo("\"" . iconv("UTF-8", "GBK", ($item->updated_at->toDateTimeString())) . "\",");
                echo("\"" . iconv("UTF-8", "GBK", ($item->is_important ? $item->is_important : "未填")) . "\",");
                echo("\"" . iconv("UTF-8", "GBK", ($item->data_img ? $item->data_img : "未填")) . "\"\r\n");
            }
        }
        exit();
    }

    /**
     * @apiVersion 1.0.0
     * @api {POST} Welfare/updateWelfarePromotionBook  添加活动推广书籍
     * @apiGroup Welfare
     * @apiName updateWelfarePromotionBook
     * @apiParam {String}  bid 书本id [必传]
     * @apiParam {Number}  channer_user_id 渠道id [必传]
     *
     * @apiParam {Number}  is_enable 是否可用(1: 可用，0：不可用) [可不传]
     * @apiParam {String}  book_name 书本名称 [可不传]
     * @apiParam {String}  charge_rate  付费率 [可不传]
     * @apiParam {String}  is_important 是否是重要渠道(1:是，0:否) [可不传]
     * @apiParam {String}  force_subscribe_rate 强关率 [可不传]
     * @apiParam {String}  data_img 数据图片url [可不传]
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":{ }
     *     }
     */
    function updateWelfarePromotionBook(Request $request)
    {
        $id = $request->has('id') ? $request->input('id') : '';
        $data_img = $request->has('data_img') ? $request->input('data_img') : '';
        $is_enable = $request->has('is_enable') ? $request->input('is_enable') : '';
        $bid = $request->has('bid') ? $request->input('bid') : '';
        $book_name = $request->has('book_name') ? $request->input('book_name') : '';
        $charge_rate = $request->has('charge_rate') ? $request->input('charge_rate') : '';
        $is_important = $request->has('is_important') ? $request->input('is_important') : '';
        $force_subscribe_rate = $request->has('force_subscribe_rate') ? $request->input('force_subscribe_rate') : '';

        if (!$id && !$data_img && !$book_name && !$charge_rate && !is_numeric($is_important) && !$force_subscribe_rate) {
            return response()->error('PARAM_EMPTY');
        }

        $params = ['data_img' => $data_img, 'is_enable' => $is_enable, 'book_name' => $book_name,
            'charge_rate' => $charge_rate, 'is_important' => $is_important, 'force_subscribe_rate' => $force_subscribe_rate];

        $result = WelfareBookService::updateWelfarePromotionBook($id, $params);
        if ($result) {
            return response()->success();
        } else {
            return response()->error("HANDLE_FAILED");
        }
    }
}
