<?php
/*
|--------------------------------------------------------------------------
| 促销价格设定管理（自有平台销售价格查询，免得退换货有问题）
|--------------------------------------------------------------------------
|  增删改查
|  @author liXiaoLin
|  @Date: 2021/7/28
|  @Time: 15:11
|  @Email: lixiaolin@bluearp.com
|  @version 1.0
|  @copyright BlueCity
*/

namespace App\Http\Controllers\Admin;

use App\Services\GoodsService;
use App\Services\SalePriceService;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Traits\CurdControllerMethod;
use Illuminate\Http\Request;
use BlueCity\Core\Controllers\CoreController as Controller;
use DB;

class SalesPriceController extends Controller
{
    public $dataService = null;  // CurdControllerMethod 必备参数
    protected $dataFields = ['start_time', 'end_time', 'cxld', 'pt_id', 'pg_id', 'price'];
    protected $validateRules = [
        'create_rules' => [
            'start_time' => 'required',
            'end_time' => 'required',
            'cxld' => 'required',
            'pt_id' => 'required|integer',
            'price' => 'required|greater_than_field:cxld', //促销力度不能大于平台价格
            'pg_id' => 'required|integer',
        ],
        'edit_rules' => [
            'pt_id' => 'required|alpha',
            'price' => 'required'
        ],
        'messages' => [
            'greater_than_field'=>'促销价格必须大于价格'
        ],
        'attributes' => [
            'pg_id' => '商品id',
            'pt_id' => '平台id',
            'price' => '价格',
            'cxld' => '促销力度',
            'end_time' => '结束时间',
            'start_time' => '开始时间'
        ]
    ];
    use CurdControllerMethod;

    public function __construct()
    {
        $service = new SalePriceService();
        $this->bootWithService($service);
    }

    /**
     * @api {post} /api/service/salePrice 平台卖价列表
     * @apiGroup 平台卖价管理
     * @apiName 平台卖价列表
     * @apiVersion 1.0.0
     *
     * @apiDescription 平台卖价列表
     *
     * @apiParam id       数据id
     * @apiParam type    商品品牌
     * @apiParam pt_id 价格名
     * @apiParam goods_id    服务商id
     * @apiParam brand_name   开始时间
     * @apiParam pg_series      结束时间
     * @apiParam state      结束时间
     * @apiParam order_time      结束时间
     * @apiParam order_num      结束时间
     * @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":[]}
     *
     */

    public function index(Request $request)
{
    $session = $request->get('session_token');

    $data = $this->dataService->search_s($request->all(), ['*'], 1, 20,$session);
    if (method_exists($this->dataService, 'formatPageContent')) {
        //根据权限格式化页面button
        $token = $request->input('token');
        $priId = $request->input('Pri_id');
        $data = $this->dataService->formatPageContent($token, $priId, $data);
    }

    if (!empty($data['list'])) {

        return $this->success('获取成功', $data);
    } else {
        return $this->error('暂无数据', ErrorInc::DATA_EMPTY, $data);
    }
}


    /**
     * @api {post} /api/service/salePrice/create 平台卖价保存
     * @apiGroup 平台卖价管理
     * @apiName 平台卖价保存
     * @apiVersion 1.0.0
     *
     * @apiDescription 平台卖价保存到数据库
     *
     * @apiParam {int} id       数据id
     * @apiParam {int} type      公开状态
     *
     * @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->only($this->dataFields);
        if ($this->validateRules) {
            $validate = validator()
                ->make(
                    $input,
                    $this->validateRules['create_rules'],
                    $this->validateRules['messages'],
                    $this->validateRules['attributes']
                );
            if ($validate->fails()) {
                $messages = $validate->messages();

                return $this->error('参数错误', ErrorInc::INVALID_PARAM, $messages);
            }
        }
        $data = $this->_setStore($input);

        $salesprice = SalePriceService::getPrice($request->input('pg_id'));
        $data['brand_name'] = $salesprice['brand_name'];
        $data['pg_series'] = $salesprice['pg_series'];
        $data['company_id'] = $request->get('session_token')['company_id'];
        $res = $this->dataService->create($data);
        if ($res) {
            return $this->success('操作成功');
        } else {
            return $this->error('操作失败', ErrorInc::MYSQL_FAILED);
        }
    }

    private function _setStore($input)
    {
        $data['pt_id'] = $input['pt_id'];
        $data['cxld'] = $input['cxld'];
        $data['price'] = $input['price'];
        $data['pg_id'] = $input['pg_id'];
        $data['cx_price'] = $input['price'] - $data['cxld'];
        $data['start_time'] = $input['start_time'];
        $data['end_time'] = $input['end_time'];
        $data['addtime'] = date("Y-m-d H:i:s");
        $data['update_time'] = date("Y-m-d H:i:s");
        $data['type'] = '2';

        return $data;
    }


    public function selectAddEntry(Request $request)
    {
        $Db = Db::table('salesprice');
        if ($request->filled('brand_name')) {
            $brand_name = $request->input('brand_name');
        }
        if ($request->filled('pg_series')) {
            $pg_series = $request->input('pg_series');
        }
        $end_time = $request->input('end_time');
        $end_time = strtotime($end_time);
        $end_time = $end_time + "86400";
        $end_time = date("Y-m-d H:i:s", $end_time);
        //开始时间
        if ($request->filled('start_time')) {
            $Db = $Db->where('start_time', '>=', $request->input('start_time'));
            $Db = $Db->orWhere('start_time', '<=', $request->input('end_time'));
        }
        //结束时间
        if ($request->filled('end_time')) {
            $Db = $Db->orWhere('end_time', '<=', $request->input('start_time'));
            $Db = $Db->orWhere('end_time', '>=', $request->input('end_time'));
        }
        $id = $Db->pluck('pg_id')->toArray();
        $goods_id = Db::table('salesprice')
            ->where('pt_id', $request->input('pt_id'))
            ->where('brand_name', $request->input('brand_name'))
            ->where('pg_series', $request->input('pg_series'))
            ->where('type', '2')
            ->where('revoke_type', '1')
            ->pluck('pg_id')
            ->toArray();
        $res = array_intersect($goods_id, $id);
        $pj_goods = Db::table('salesprice')
            ->where('pt_id', $request->input('pt_id'))
            ->where('brand_name', $request->input('brand_name'))
            ->where('pg_series', $request->input('pg_series'))
            ->where('price', "!=", '0')->where('revoke_type', '1')
            ->pluck('pg_id')
            ->toArray();
        foreach ($pj_goods as $k => $v) if (in_array($v, $res)) unset($pj_goods[$k]);
        $pj_goods = array_values($pj_goods);

        $ids = implode(',', $pj_goods);
        $data = Db::table('salesprice')->where('pt_id', $request->input('pt_id'))->where('type', '1')->whereRaw(" FIND_IN_SET (pg_id," . "'" . $ids . "'" . ")")->select('pg_id', 'price')->where('revoke_type', '1')->get()->toArray();

        foreach ($data as $key => $value) {
            $data[$key]['goods_name'] = Db::table('pj_goods')
                ->where('pg_id', $data[$key]['pg_id'])
                ->select('pg_id', 'brand_name', 'pg_series', 'version')
                ->get()
                ->first();
        }
        if ($data) {
            return response()->json(['ErrorCode' => 1, 'ErrorMessage' => "操作成功", 'Data' => $data]);
            exit;
        } else {
            return response()->json(['ErrorCode' => 3, 'ErrorMessage' => "操作失败", 'Data' => '']);
            exit;
        }
    }


    private function _setUpdate($input)
    {
        $update = [];
        $update['pt_id'] = $input['pt_id'];
        $update['price'] = $input['price'];
        $update['update_time'] = date("Y-m-d H:i:s");

        return $update;
    }

    private function _afterUpdate($res, $beforeData)
    {
        SalePriceService::insertLog($res->pg_id, $res->price, $res->pt_id, (new Request())->get('session_token')['admin_acc']);
//        $this->insertingPriceLog($request->input('pg_id'), $request->input('price'), $request->input('pt_id'), $request->get('session_token')['admin_acc']);
    }

    /**|---------------------------------------------------------------------------------
     * 获取同步商品
     * @return mixed
     * @author dou <2020/8/13 18:19>
     * |---------------------------------------------------------------------------------
     */
    public function synchro()
    {
        $list = GoodsService::syncGoods();

        return $this->success('操作成功', $list);
    }

    /**|---------------------------------------------------------------------------------
     * 同步平台卖价
     *
     * @param pt_id 平台id
     * @param good_id 商品id
     * @return mixed
     * @author dou <2020/8/13 18:18>
     * |---------------------------------------------------------------------------------
     */
    public function synchroDo(Request $request)
    {
        $input = $request->all();
        $res = SalePriceService::findPrice($input['pt_id'], $input['pg_id']);

        if (empty($res)) {
            $data['pt_id'] = $input['pt_id'];
            $data['pg_id'] = $input['pg_id'];
            $data['brand_name'] = $input['brand_name'];
            $data['pg_series'] = $input['pg_series'];
            $data['price'] = '0';
            $data['addtime'] = date("Y-m-d H:i:s");
            $data['start_time'] = "2015-01-01";
            $data['end_time'] = "2100-12-31";
            $data['company_id'] = $request->get('session_token')['company_id'];
            $res = SalePriceService::create($data);
            if (empty($res)) {
                return $this->error('同步失败', ErrorInc::MYSQL_FAILED);
            } else {
                return $this->success('同步成功');
            }
        } else {
            return $this->error('平台商品已存在', ErrorInc::REPEAT_SUBMIT);
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name  撤销
     * @param id       数据id
     * @param revoke      撤销状态1 未撤销 2已撤销
     * @return \Illuminate\Http\JsonResponse
     * @author hzc <2020/08/13>
     * |---------------------------------------------------------------------------------
     */
    public function revoke(Request $request)
    {
        $id = $request->input('id');
        $price = $this->dataService->find($id);
        if (!$price) {
            return $this->error('id不存在', ErrorInc::DATA_EMPTY);
        }
        $update['revoke_type'] = '2';
        $res = $price->update($update);
        if ($res) {
            return $this->success('成功');
        } else {
            return $this->success('操作失败', ErrorInc::MYSQL_FAILED);
        }
    }


    public function getLogs(Request $request)
    {
        //页码数据
        $pageSize = (int)$request->input('page_size', 20);
        $page = (int)$request->input('page', 1);
        if ($page < 1) {
            $page = 1;
        }
        $param = $request->only(['pt_id', 'pg_id']);
        $data = SalePriceService::getLogs($param, $columns = array('*'), $page, $pageSize);
        if (!empty($data['list'])) {
            return $this->success('', $data);
        } else {
            return $this->error('操作失败', ErrorInc::DATA_EMPTY);
        }
    }
}
