<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2018/3/23
 * Time: 上午9:09
 */

namespace App\Http\Controllers\Manage\Channel;


use App\Http\Controllers\Manage\BaseController;
use App\Http\Controllers\Manage\Channel\Transformers\ChannelTransformer;
use App\Http\Controllers\Manage\Channel\Transformers\CompanyTransformer;
use App\Modules\Book\Services\BookService;
use App\Modules\Channel\Services\ChannelUserService;
use App\Modules\Channel\Services\CompanyService;
use App\Modules\Channel\Services\CompanySpecialBookService;
use Illuminate\Http\Request;

class CompanyController extends BaseController
{

    /**
     * @apiDefine channel 渠道
     */

    /**
     * @apiVersion 1.0.0
     * @apiDescription 添加公司
     * @api {POST} channel/company/add 添加公司
     * @apiGroup channel
     * @apiName channel/company/add
     * @apiParam   {String}  name 公司名称
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":{}
     *     }
     */
    public function addCompany(Request $request) {
        $name = $request->has('name') ? $request->input('name') : '';
        if(empty($name)) {
            return response()->error("PARAM_EMPTY");
        }
        $company = CompanyService::findByName($name);
        if($company) {
            return response()->error("COMPANY_EXIST");
        }

        $data = ['name' => $name, 'is_important' => 0];
        $company = CompanyService::addCompany($data);

        return response()->item(new CompanyTransformer(), $company);
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 删除公司
     * @api {POST} channel/company/remove 删除公司
     * @apiGroup channel
     * @apiName channel/company/remove
     * @apiParam   {Number}  id 公司ID
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":{}
     *     }
     */
    public function rmCompany(Request $request) {
        $id = $request->has('id') ? $request->input('id') : '';
        if(empty($id)) {
            return response()->error("PARAM_EMPTY");
        }
        $company = CompanyService::getCompany($id);
        if(!$company) {
            return response()->error("PARAM_ERROR");
        }
        CompanySpecialBookService::rmCompany($id);
        $company->delete();

        return response()->success();
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 更新公司
     * @api {POST} channel/company/update 更新公司
     * @apiGroup channel
     * @apiName channel/company/update
     * @apiParam   {Number}  id 公司ID
     * @apiParam   {String}  [name] 公司名称
     * @apiParam   {Number}  [is_important] 是否重要 0：不是重点，默认    1：重点商户
     * @apiParam   {Number}  [distribution_manages_id] 商务ID
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":{}
     *     }
     */
    public function updateCompany(Request $request) {
        $id = $request->has('id') ? $request->input('id') : '';
        if(empty($id)) {
            return response()->error("PARAM_EMPTY");
        }
        $is_important = $request->input('is_important','');

        if($request->has('is_important') && !in_array($is_important, [0,1])) {
            return response()->error("PARAM_ERROR");
        }
        if(!CompanyService::getCompany($id)) {
            return response()->error("PARAM_ERROR");
        }
        $name = $request->has('name') ? $request->input('name') : '';
        $data = [];
        if($name){
            $data['name'] =$name;
        }
        if($request->has('is_important') && in_array($is_important,[0,1])) {
            $data['is_important'] = $is_important;
        }
        //$data = ['name' => $name, 'is_important' => $is_important];

        if($this->getLoginUserRole() == "business_leader" || $this->getLoginUserRole() == "admin" || $this->getLoginUserRole()=="business") {
            //只有商务主管能修改 公司对应商务，
            $distribution_manages_id = $request->has('distribution_manages_id') ? $request->input('distribution_manages_id') : '';
            if(is_numeric($distribution_manages_id) && $distribution_manages_id > 0) {
                //更新公司对应用户的所属商务
                $data['distribution_manages_id']= $distribution_manages_id;
                ChannelUserService::updateChannelUserManager($distribution_manages_id, $id);
            }
        }
        $fans_type = $request->input('fans_gender','');
        if($fans_type){
            if(!in_array($fans_type,[1,2,3])){
                return response()->error('PARAM_ERROR');
            }
            $data['fans_gender'] = $fans_type;
        }
        if($data){
            //\Log::info('delete_company_books:rmCompany:$id'.$id);
            $company_old = CompanyService::getCompany($id);
            $company = CompanyService::updateCompany($id, $data);

            if($request->has('is_important') && $is_important == 0) {
                //设置为普通商户之后，对应书籍删除
                \Log::info('delete_company_books:rmCompany:$id'.$id.'is_important:'.$is_important);
                CompanySpecialBookService::rmCompany($id);
            }
            if($request->has('is_important') && $is_important == 1 && $company_old->is_important==0) {
                \Log::info('delete_company_books:rmCompany:$id'.$id.'is_important:'.$is_important);
                CompanySpecialBookService::rmCompany($id);

                $bids = CompanySpecialBookService::getBidByFirst();
                if($bids) {
                    foreach ($bids as $i) {
                        CompanySpecialBookService::addBook($i, $id);
                    }
                }
            }
        }
        $company = CompanyService::getCompany($id);
        return response()->item(new CompanyTransformer(), $company);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 公司列表分页
     * @api {GET} channel/company/list 公司列表分页
     * @apiGroup channel
     * @apiName channel/company/list
     * @apiParam   {String}  [search_name] 搜索名称
     * @apiParam   {Number}  [is_important] 是否重要
     * @apiSuccess {Number}  id 公司ID
     * @apiSuccess {String}  name 公司名称
     * @apiSuccess {Number}  is_important 是否重要
     * @apiSuccess {String}  create_time 创建时间
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {
     *          "list": [
     *          {
     *          "id": 2,
     *          "name": "杭州掌维科技有限公司",
     *          "is_important": 0,
     *          "create_time": "2018-03-23 09:32:29"
     *          },
     *          ],
     *          "meta": {
     *          "total": 2,
     *          "per_page": 15,
     *          "current_page": 1,
     *          "last_page": 1,
     *          "next_page_url": "",
     *          "prev_page_url": ""
     *          }
     *          }
     *     }
     */
    public function getList(Request $request) {
        $search_name = $request->has('search_name') ? $request->input('search_name') : '';
        $is_important = $request->input('is_important');

        $searchData = [
            'search_name' => $search_name,
            'is_important' => $is_important,
        ];

        $manager_info= json_decode(json_encode(unserialize($request->session()->get('manage_user'))),true);
        $manager_id = '';
        if($manager_info['role']=='business'){
            $manager_id = $manager_info['id'];
        }
        $data = CompanyService::getList($searchData,false,$manager_id);

        return response()->pagination(new CompanyTransformer(), $data);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 公司列表
     * @api {GET} channel/company/allList 公司列表
     * @apiGroup channel
     * @apiName channel/company/allList
     * @apiParam   {String}  [search_name] 搜索名称
     * @apiParam   {Number}  [is_important] 是否重要
     * @apiSuccess {Number}  id 公司ID
     * @apiSuccess {String}  name 公司名称
     * @apiSuccess {Number}  is_important 是否重要
     * @apiSuccess {String}  create_time 创建时间
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":[
     *              {
     *          "id": 2,
     *          "name": "杭州掌维科技有限公司",
     *          "is_important": 0,
     *          "create_time": "2018-03-23 09:32:29"
     *          }
     *          ]
     *     }
     */
    public function getAllList(Request $request) {
        $search_name = $request->has('search_name') ? $request->input('search_name') : '';
        $is_important = $request->input('is_important');

        $searchData = [
            'search_name' => $search_name,
            'is_important' => $is_important,
        ];

        $data = CompanyService::getList($searchData, true);

        return response()->collection(new CompanyTransformer(), $data);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 公司列表图书ID
     * @api {GET} channel/company/listByBookId 公司列表图书ID
     * @apiGroup channel
     * @apiName channel/company/listByBookId
     * @apiParam   {Number}  bid 书籍ID
     * @apiSuccess {Number}  id 公司ID
     * @apiSuccess {String}  name 公司名称
     * @apiSuccess {Number}  is_important 是否重要
     * @apiSuccess {String}  create_time 创建时间
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":[
     *              {
     *          "id": 2,
     *          "name": "杭州掌维科技有限公司",
     *          "is_important": 0,
     *          "create_time": "2018-03-23 09:32:29"
     *          }
     *          ]
     *     }
     */
    public function getListByBookId(Request $request) {
        $bid = $request->has('bid') ? $request->input('bid') : '';
        if(empty($bid) || !is_numeric($bid)) {
            return response()->error("PARAM_ERROR");
        }

        $data = CompanySpecialBookService::findCompanyToBid($bid);

        return response()->collection(new CompanyTransformer(), $data);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 获取公司渠道列表
     * @api {GET} channel/company/getChannelList 获取公司渠道列表
     * @apiGroup channel
     * @apiName channel/company/getChannelList
     * @apiParam   {Number}  company_id 公司id
     * @apiParam   {Number}  channel_user_id 账户id
     *
     * @apiSuccess {Number}  id 渠道ID.
     * @apiSuccess {String}  name 渠道名称.
     * @apiSuccess {String}  phone 手机号码.
     * @apiSuccess {String}  pay_merchant 支付商户.
     * @apiSuccess {String}  nickname 昵称.
     * @apiSuccess {String}  latest_login_time  最后登陆时间.
     * @apiSuccess {String}  latest_login_ip 最后登陆IP.
     * @apiSuccess {String}  remark 备注.
     * @apiSuccess {String}  register_ip 注册IP.
     * @apiSuccess {String}  person_in_charge_name 负责人.
     * @apiSuccess {String}  create_time 注册时间
     * @apiSuccess {Number}  distribution_manages_id 管理员ID
     * @apiSuccess {String}  distribution_manages_account 管理员
     * @apiSuccess {String}  distribution_manages_number 管理员
     * @apiSuccess {String}  distribution_manages_nickname 管理员昵称
     * @apiSuccess {String}  price_rate 章节价格
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": [
     *             {
     *                  "id": 1,
     *                   "phone": "",
     *                   "name": "121",
     *                   "pay_merchant_id": 1,
     *                   "nickname": "是说",
     *                   "latest_login_time": "",
     *                   "latest_login_ip": "",
     *                   "is_enabled": 1,
     *                   "register_ip": "",
     *                   "remark": "",
     *                   "person_in_charge_name": "波哥帅",
     *                   "create_time": "2017-11-20 18:34:17",
     *                   "distribution_manages_id": 0,
     *                   "distribution_manages_account": null,
     *                   "distribution_manages_number": null,
     *                   "distribution_manages_nickname": null
     *              }
     *          ]
     *     }
     */
    public function getChannelList(Request $request) {
        $company_id = $request->has('company_id') ? $request->input('company_id') : '';
        $channel_user_id = $request->has('channel_user_id') ? $request->input('channel_user_id') : '';

        if($company_id && !is_numeric($company_id) && !is_numeric($channel_user_id)) {
            return response()->error("PARAM_ERROR");
        }

        if($company_id == 0) {
            $channelUser = ChannelUserService::getById($channel_user_id);
            if($channelUser) {
                $company_id = $channelUser->company_id;
            }
        }

        $channelUserIds = [];
        if(is_numeric($company_id) && $company_id > 0) {
            $channelUserIds = ChannelUserService::getChannelUserIdListByCompany($company_id);
        } else {
            $channelUserIds[] = $channel_user_id;
        }
//        $channelUserIds = ChannelUserService::getChannelUserIdListByCompany($company_id);
        $channels = ChannelUserService::getChannelListByChannelUserIds($channelUserIds);
        foreach ($channels as &$v){
            $price_rate = BookService::getChapterPrice($v->id);
            $default_rate = (float)env('DEFAULT_CHAPTER_PRICE',0.015)*100;
            $v->price_rate = $price_rate?$price_rate:$default_rate;
        }
        return response()->collection(new ChannelTransformer(), $channels);
    }



    /**
     * @apiVersion 1.0.0
     * @apiDescription 添加书籍
     * @api {POST} channel/company/addBook 添加书籍
     * @apiGroup channel
     * @apiName channel/company/addBook
     * @apiParam   {Number}  bid 书籍ID
     * @apiParam   {Number}  company_ids 公司ids [1,2,3,4]
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":{}
     *     }
     */
    public function addCompanyBook(Request $request) {
        $bid = $request->has('bid') ? $request->input('bid') : '';
        $company_ids = $request->has('company_ids') ? $request->input('company_ids') : '';

        if(!is_numeric($bid)) {
            return response()->error("PARAM_ERROR");
        }

//        if(count($ids) == 0) {
//            return response()->error("PARAM_ERROR");
//        }
        \Log::info('delete_special_book_log:addCompanyBook:$bid:'.$bid);
        CompanySpecialBookService::rmAllBook($bid);

        if(!empty($company_ids)) {
            $ids = explode(',', $company_ids);

            foreach ($ids as $id) {
                $data = CompanySpecialBookService::addBook($bid, $id);
            }
        }
        return response()->success();
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 删除书籍
     * @api {POST} channel/company/rmBook 删除书籍
     * @apiGroup channel
     * @apiName channel/company/rmBook
     * @apiParam   {Number}  bid 书籍ID
     * @apiParam   {Number}  company_ids 公司id[1,2,3,4]
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":{}
     *     }
     */
    public function rmCompanyBook(Request $request) {
        $bid = $request->has('bid') ? $request->input('bid') : '';
        $company_ids = $request->has('company_ids') ? $request->input('company_ids') : '';

        if(!is_numeric($bid) || empty($company_ids)) {
            return response()->error("PARAM_ERROR");
        }
        $ids = explode(',', $company_ids);
        if(count($ids) == 0) {
            return response()->error("PARAM_ERROR");
        }
        \Log::info('delete_special_book_log:rmCompanyBook:ids:'.json_encode($ids).'bid:'.$bid);
        foreach ($ids as $id) {
            $data = CompanySpecialBookService::rmBook($bid, $id);
        }

        return response()->success();
    }

    /**
     * 设置商务公司所在的城市
     * @param Request $request
     * @return mixed
     */
    function setChannelCityInfo(Request $request)
    {
        $city = $request->has('city') ? $request->input('city') : '';
        $companyId = $request->has('companyId') ? trim($request->input('companyId')) : '';

        if (empty($companyId) || empty($city)) {
            return response()->error('PARAM_ERROR');
        }
        $result = CompanyService::updateCompany($companyId, ['city' => $city]);
        if ($result) {
            return response()->success();
        }
        return response()->error("HANDLE_FAILED");
    }
}