<?php
/*
|--------------------------------------------------------------------------
| 平台价格管理 (原 “活动系统/平台价格管理” ，没改呢)
|--------------------------------------------------------------------------
|  增删改查
|  @author liXiaoLin
|  @Date: 2021/7/28
|  @Time: 15:11
|  @Email: lixiaolin@bluearp.com
|  @version 1.0
|  @copyright BlueCity
*/

namespace App\Http\Controllers\Platform;

use App\Http\Controllers\BaseController;
use App\Services\BmmcService;
use App\Services\CommonService;
use App\Services\GoodsService;
use App\Models\Ptprice;
use App\Services\PlatformPriceService;
use App\Services\PlatformService;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Traits\CurdControllerMethod;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class PlatformPriceController extends BaseController
{
    public function __construct()
    {
        $service = new PlatformPriceService();
        $this->bootWithService($service);
    }

    use CurdControllerMethod;
    /**
     * @api {post} /api/platform/platformPrice 列表页
     * @apiGroup 平台价格
     * @apiName 列表页
     * @apiVersion 1.0.0
     *
     * @apiDescription 平台价格 >> 列表页
     *
     * @apiParam {int} pt_id       平台id
     * @apiParam {String} brand_name  品牌名称
     * @apiParam {String} version     商品型号
     * @apiParam {int} page_size  页大小
     * @apiParam {int} page  页码
     * @apiParam {string} token token
     * @apiParam {int} Pri_id 页码权限码
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {
        "errorCode": 1,
        "errorMessage": "成功",
        "data": {
        "page": {//页码数据
        "page": 1,    //当前页码
        "page_size": 20,//每页显示条数
        "count": 479     //总条数
        },
        "list": [  //数据
        {
        "pri_id": 1,  //id
        "pri_price": "421",  //价格
        "pri_peo": "窦斌",  //添加人
        "pri_ptid": 67,    //平台id 忽略
        "pri_pgid": 196,   //商品id  忽略
        "brand_name": "瓦尔塔",  //商品品牌
        "pg_series": "蓝标-55415", //型号
        "version": "55415"          //通用名称
        "pt_name": "畅通车友会",     //平台名称
        "pri_name": null,           //销售名称
        "national_version": ""      //国际价格
        "pri_show": 1              //1  展示  2 隐藏  或则  1 启用  2停用
        }
        ]
        }
        }
     *
     */

//    public function index(Request $request)
//    {
//        $page_size = (int)$request->input('page_size', 10);
//        if ($request->filled('page')) {
//            $offset = ($request->input('page', 1) - 1) * $page_size;
//        } else {
//            $offset = 0;
//        }
//        $Db = Ptprice::leftJoin('pj_goods', 'pj_pricenew.pri_pgid', '=', 'pj_goods.pg_id')->leftJoin('pt', 'pt.id', '=', 'pj_pricenew.pri_ptid');
//
//        if ($request->filled('pt_id')) {
//            $Db = $Db->where('pri_ptid', (int)$request->input('pt_id'));
//        }
//        if ($request->filled('brand_name')) {
//            $Db = $Db->where('pri_brand', $request->input('brand_name'));
//        }
//        if ($request->filled('version')) {
//            $Db = $Db->where('version', 'like', '%' . $request->input('version') . '%');
//        }
//        $count = $Db->count();
//        $list = $Db->select('pri_id', 'pri_price', 'pri_peo', 'pri_ptid', 'pri_pgid', 'pj_goods.brand_name', 'pj_goods.pg_series', 'pj_goods.version', 'pt_name', 'pri_name', 'pri_show', 'national_version')->offset($offset)->limit($page_size)->orderBy('pri_id', 'DESC')->get();
//
//
//        $data = [];
//        $data['page'] = ['page' => (int)$request->input('page', 1), 'page_size' => $page_size, 'count' => $count];
//
//        //按钮
//        $all_button = BmmcService::whereButton($request->input('token'),$request->input('Pri_id'),$request->input('Login_id'));
//        $export = BmmcService::getTopButton('addPtprice','',$all_button);
//        $data['button_top'] = $export['button_top']??[];//顶部按钮
//        $data['button_search'] = $export['button_search']??[];//搜索栏按钮
//        if (!$list->isEmpty()) {
//            $arr = $list->toArray();
//            foreach ($arr as $key => $value) {
//                $buttonData = [];
//                $buttonData[] = 'editPtprice';
//                if ($value['pri_show'] == 1) {
//                    $buttonData[] = 'stopPtpriceT';
//                } elseif ($value['pri_show'] == 2) {
//                    $buttonData[] = 'stopPtpriceQ';
//                }
//                $button = BmmcService::getListButton($buttonData,$all_button);
//                $arr[$key]['button_one'] = $button['button_one']??[];
//                $arr[$key]['button_two'] = $button['button_two']??[];
//                $arr[$key]['button_three'] = $button['button_three']??[];
//                if ($value['pg_series'] != '') {
//                    $arr[$key]['pg_series'] = $value['pg_series'] . '-' . $value['version'];
//                } else {
//                    $arr[$key]['pg_series'] = $value['version'];
//                }
//            }
//            $data['list'] = $arr;
//            return $this->success('成功', $data);
//        } else {
//            $data['list'] = [];
//
//            return $this->error('暂无数据', ErrorInc::DATA_EMPTY);
//        }
//
//    }


    /**
     * @api {post} /api/platform/platformPrice/store 添加平台价格
     * @apiGroup 平台价格
     * @apiName 添加平台价格
     * @apiVersion 1.0.0
     *
     * @apiDescription 平台价格 >> 添加平台价格
     *
     * @apiParam {int} pt_id            平台id
     * @apiParam {int} goods_id         商品id
     * @apiParam {string} brand_name    品牌名称
     * @apiParam {int} pri_price        金额
     * @apiParam {string} pri_name      销售名称
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {
        "ErrorCode": 1,
        "ErrorMessage": "添加成功",
        "data":[]
        }
     *
     */

    public function store(Request $request)
    {
        $input = $request->all();
        $checkKey=CommonService::checkKey(['pri_price', 'pt_id', 'goods_id','brand_name'],$input,array('pri_price'=>'销售价格','pt_id'=>'平台编号','goods_id'=>'商品编号','brand_name'=>'商品品牌'));
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        if ($request->input('pri_price') <= 0) {

            return $this->error('结算价必须大于0', ErrorInc::INVALID_PARAM);
        }
        $pri_id = DB::table('pj_pricenew')
            ->whereRaw("pri_ptid='" . $request->input('pt_id') . "' and pri_pgid='" . $request->input('goods_id') . "'")
            ->value("pri_id");
        $params['pri_ptid'] = $input['pt_id'];
        $params['pri_pgid'] = $input['goods_id'];
        $pri_id = PlatformPriceService::getPtPrice($params,['pri_id'],'value');
        if ($pri_id) {
            return $this->error('商品已存在', ErrorInc::REPEAT_SUBMIT);
        } else {
            $arr['pri_peo'] = $request->get('session_token')['admin_acc'];           //添加人
            $arr['pri_price'] = $input['pri_price']; //价格
            $arr['pri_ptid'] = $input['pt_id'];      //平台id
            $arr['pri_pgid'] = $input['goods_id'];   //商品id
            $arr['pri_brand'] = $input['brand_name'];//商品品牌
            $arr['pri_name'] = $input['pri_name']??'';   //销售名称
            $arr['pri_show'] = 1;                             //是否第三方显示
            $res = Ptprice::insert($arr);
            if ($res) {
                $info = GoodsService::getGoodsByKey('pg_id', $input['goods_id'],['brand_name','pg_series','version']);
                $goods = $info['good_name'];
                $ptname = PlatformService::getPtBy('id', $input['pt_id'], ['pt_name']);
                $this->insertingLog('添加,', '', "平台：".$ptname.",型号：" . $goods."->售价：".$input['pri_price'], '平台价格管理', $request->ip(), $request->get('session_token')['admin_acc']);
                return $this->success('添加成功', $res);
            } else {
                return $this->error('新增失败', ErrorInc::MYSQL_FAILED);
            }
        }
    }


    /**
     * @api {post} /api/platform/platformPrice/edit 编辑平台价格
     * @apiGroup 平台价格
     * @apiName 编辑平台价格
     * @apiVersion 1.0.0
     *
     * @apiDescription 平台价格 >> 编辑平台价格
     *
     * @apiParam {int} id       id
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {
        "errorCode": 1,
        "errorMessage": "获取成功",
        "data": {
        "pri_id": 1098,  //id
        "pri_price": "1000", //金额
        "brand_name": "瓦尔塔", //品牌
        "pg_series": "蓝标",    //忽略
        "version": "55530",     //忽略
        "pt_name": "畅通车友会", //平台
        "pri_name": "测试数据",  //销售名称
        "type": "瓦尔塔-蓝标-55530"  //商品名称
        }
        }
     *
     */

//    public function edit(Request $request)
//    {
//        $id = $request->input('id');
//        $res = PlatformPriceService::getOne($id);
//        if ($res) {
//            if ($res['pg_series'] == "") {
//                $res['type'] = $res['brand_name'] . '-' . $res['version'];
//            } else {
//                $res['type'] = $res['brand_name'] . '-' . $res['pg_series'] . '-' . $res['version'];
//            }
//            return $this->success('获取成功', $res);
//        } else {
//            return $this->error('未找到内容', ErrorInc::DATA_EMPTY);
//        }
//    }

    /**
     * @api {post} /api/platform/platformPrice/update 保存编辑平台价格
     * @apiGroup 平台价格
     * @apiName 保存编辑平台价格
     * @apiVersion 1.0.0
     *
     * @apiDescription 平台价格 >> 编辑平台价格
     *
     * @apiParam {int} id       id
     * @apiParam {int} pri_price        金额
     * @apiParam {string} pri_name      销售名称
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {
        "ErrorCode": 1,
        "ErrorMessage": "编辑成功",
        "data":[]
        }
     *
     */
    public function update(Request $request)
    {
        $input = $request->all();
        $checkKey=CommonService::checkKey(['pri_price', 'id'],$input,array('pri_price'=>'销售价格','id'=>'数据编号'));
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $id = $input['id'];
        $data = PlatformPriceService::getPtPriceBy('pri_id', $id);
        if(!$data){
            return $this->error('数据不存在', ErrorInc::DATA_EMPTY);
            exit;
        }
        if ($request->input('pri_price') <= 0) {
            return $this->error('结算价格不能小于0', ErrorInc::INVALID_PARAM);
        }
        $pri_price = $input['pri_price'];
        $name = $input['pri_name']??'';
        $ediRes = $this->dataService->update(['pri_price' => $pri_price, 'pri_name' => $name], $id);
        if ($ediRes) {
            $info = GoodsService::getGoodsByKey('pg_id', $data['pri_pgid'],['brand_name','pg_series','version']);
            $goods = $info['good_name'];
            $ptname = PlatformService::getPtBy('id', $data['pri_ptid'], ['pt_name']);
            $sdname = "平台：" . $ptname . "，商品：".$goods."(" . $data['pri_name'] . "->".$name."),价格：".$data['pri_price']."->".$pri_price;
            $this->insertingLog('编辑，', '', $sdname, '平台价格管理', $request->ip(), $request->get('session_token')['admin_acc']);
            return $this->success('修改成功');
        } else {
            return $this->error('操作失败', ErrorInc::MYSQL_FAILED);
        }
    }

    /**
     * @api {post} /api/platform/platformPrice/delete 删除平台价格
     * @apiGroup 平台价格
     * @apiName 删除平台价格
     * @apiVersion 1.0.0
     *
     * @apiDescription 平台价格 >> 删除平台价格
     *
     * @apiParam {int} id  id
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {
        "ErrorCode": 1,
        "ErrorMessage": "删除成功",
        "data":''
        }
     *
     */
    public function destroy(Request $request)
    {
        if ($request->get('session_token')['admin_groupnew'] != 7) {
            return $this->error('没有删除权限', ErrorInc::INVALID_PARAM);
        }
        if ($request->filled('id')) {
            $id = $request->input('id');
            $entity = PlatformPriceService::getPtPriceBy('pri_id',$id);
            if (empty($entity)) {
                return $this->error('未发现数据', ErrorInc::DATA_EMPTY);
            }
            $delRes = $this->dataService->delete($id);
            if ($delRes) {
                $info = GoodsService::getGoodsByKey('pg_id', $entity['pri_pgid'],['brand_name','pg_series','version']);
                $goods = $info['good_name'];
                $ptname = PlatformService::getPtBy('id', $entity['pri_ptid'], ['pt_name']);
                $sdname = "平台：" . $ptname . "，商品：".$goods."(" . $entity['pri_name'] . "),价格：".$entity['pri_price'];
                $this->insertingLog('删除商品，', '', $sdname, '平台价格管理', $request->ip(), $request->get('session_token')['admin_acc']);
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败', ErrorInc::MYSQL_FAILED);
            }
        } else {
            return $this->error('参数错误', ErrorInc::INVALID_PARAM);
        }
    }

    //
    /**
     * @api {delete} /api/platform/platformPrice/setptprice 停用启用
     * @apiGroup 平台价格
     * @apiName 停用启用
     * @apiVersion 1.0.0
     *
     * @apiDescription 平台价格 >> 停用启用
     *
     * @apiParam {int} id  id
     * @apiParam {int} type  启用1 停用2
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":[]}
     *
     */
    public function setPtPrice(Request $request)
    {
        $type = (int)$request->input('type', 1);
        $id = (int)$request->input('id', 0);
        $entity = $this->dataService->find($id);
        if ($entity && in_array($type, [1, 2])) {
            $str = [1 => '启用', 2 => '停用'];
            if ($type == 1) {
                $olaf = "启用，";
            } else {
                $olaf = "停用，";
            }
            $res = $this->dataService->update(['pri_show' => $type], $id);
            if ($res) {
//                $this->inserting_log($olaf, '', '操作数据id->' . $id, '平台价格管理', $request->ip(), $request->get('session_token')['admin_acc']);

                return $this->success($str[$type] . '成功');
            } else {
                return $this->error('失败', ErrorInc::MYSQL_FAILED);
            }
        } else {
            return $this->error('参数错误', ErrorInc::INVALID_PARAM);
        }
    }
}
