<?php
/*
|--------------------------------------------------------------------------
| 服务商活动管理 (原来的 “活动系统/平台活动支持” ，服务商提供优惠活动，相当于给我们优惠)
|--------------------------------------------------------------------------
|  增删改查
|  @author liXiaoLin
|  @Date: 2021/7/28
|  @Time: 15:11
|  @Email: lixiaolin@bluearp.com
|  @version 1.0
|  @copyright BlueCity
*/

namespace App\Http\Controllers\Service;

use App\Http\Controllers\BaseController;
use App\Services\AdminService;
use App\Services\GoodsService;
use App\Services\PjBrandsService;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Traits\CurdControllerMethod;
use App\Services\ActivityService;
use Illuminate\Http\Request;

class ActivityController extends BaseController
{
    public $dataService = null;  // CurdControllerMethod 必备参数
    //public $dataFields = ['sup_startime', 'sup_endtime', 'sup_price', 'sup_brname', 'ser_id', 'goods_id'];  // 保存和修改时的 fields 参数
    protected $validateRules = [
        'rules' => [
            'sup_startime' => 'required',
            'sup_endtime' => 'required',
            'sup_price' => 'numeric',
            'sup_brname' => 'required',
            'sup_serid' => 'required',
//            'sup_goodids' => 'required',
            'sup_cadid' => 'required',
            'sup_type' => 'required'
        ],
        'messages' => [

        ],
        'attributes' => [
            'sup_startime' => '开始时间',
            'sup_endtime' => '结束时间',
            'sup_price' => '商品价格',
            'sup_brname' => '商品品牌',
            'sup_serid' => '服务商',
//            'sup_goodids' => '商品IDs',
            'sup_cadid' => '品类id',
            'sup_type' => '型号范围'
        ]
    ];

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

    use CurdControllerMethod;

    /**
     * @api {post} /api/service/activity 服务商活动管理-列表页
     * @apiGroup 平台活动支持
     * @apiName 服务商活动管理-列表页
     * @apiVersion 1.0.0
     *
     * @apiDescription 服务商活动管理-列表页
     *
     * @apiParam {string} brand_name 品牌名称
     * @apiParam {int} page 页码
     * @apiParam {int} page_size 页容量
     * @apiParam {string} token token
     * @apiParam {int} Pri_id 页码权限码
     *
     * @apiParamExample {json} Request-Example
     * {
     * "brand_name":"AC德科",
     * "page":1,
     * "page_size":10,
     * "token":"c961a3c4a3bb91d3d5151c100eb2ffb6",
     * "Pri_id":329
     * }
     *
     * @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": [ //数据列表
        {
        "sup_id": 4,             //id
        "sup_brname": "瓦尔塔",  //品牌
        "sup_price": 12,        // 补贴价格
        "sup_startime": "2016-11-04 17:59:41", //开始时间
        "sup_endtime": "2016-11-05 17:59:44",  //结束时间
        "sup_creacer": "窦斌",                 //添加人
        "sup_num": "S20161103055947735",       //活动编号
        "type": 3             // 1 未开始  2 已开始  3 已结束
        }
        ]
        }
        }
     *
     */


    /**
     * @api {post} /api/service/activity/create 添加界面参数
     * @apiGroup 平台活动支持
     * @apiName 添加界面参数
     * @apiVersion 1.0.0
     *
     * @apiDescription 服务商活动管理-添加界面参数
     *
     * @apiParam {string} ser_name  服务中心名称
     * @apiParam {int} ser_id    已选择服务中心id(可以是数组也可以是逗号分隔的字符串)
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     * @apiSuccessExample {json} Success-Response:
     * {
        "errorCode": 1,
        "errorMessage": "返回成功",
        "data": [    //服务中心列表
        {
        "id": 612,                           //id
        "company_name": "系统演示门店(北京）"  //服务中心名称
        }
        ]
        }
     *
     */
//    public function create(Request $request)
//    {
//        //根据条件 搜索 并移除已选择的服务商
//        $condition = [];
//
//        if (!empty($request->filled('ser_name'))) {
//            $condition[] = ["company_name", 'like', '%' . $request->input('ser_name') . '%'];
//        }
//        if ($request->filled('ser_id') && !empty($request->input('ser_id'))) {
//            $ser_id = $request->input('ser_id');
//            if (is_string($ser_id)) {
//                $temp = trim($ser_id, ',');
//                unset($ser_id);
//                $ser_id = explode(',', $temp);
//            }
//            $condition[] = ['id', 'not in', $ser_id];
//        }
//        if (!empty($condition)) {
//            $condition[] = ['admin_groupnew', '=', 2];
//            $condition[] = ['enable', '=', 1];
//            $data = AdminService::getAdmins($condition, ['id', 'company_name']);
//        } else {
//            $data = [];
//        }
//
//        return $this->success('获取成功', ['list' => $data]);
//    }

    /**
     * @api {post} /api/service/activity/store 服务商活动管理-添加
     * @apiGroup 平台活动支持
     * @apiName 服务商活动管理-添加
     * @apiVersion 1.0.0
     *
     * @apiDescription 服务商活动管理-添加
     *
     * @apiParam {int} ser_id    已选择服务中心id
     * @apiParam {int} sup_type 1:全部型号; 2:部分型号
     * @apiParam {int} goods_id 商品id
     * @apiParam sup_startime 开始时间
     * @apiParam sup_endtime 结束时间
     * @apiParam sup_price 金额
     * @apiParam {string} sup_brname 品牌名称
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     * @apiSuccessExample {json} Success-Response:
     * {
        "ErrorCode": 1,
        "ErrorMessage": "添加成功",
        "data":''
        }
     *
     */
    private function _beforeStore($input)
    {
        $rea = ActivityService::getSupport(['sup_brname'=>$input['sup_brname'],'sup_startime'=>$input['sup_startime'],'sup_endtime'=>$input['sup_endtime']],['sup_id'],'first');
        if($rea){
            return $this->error('数据已存在', ErrorInc::REPEAT_SUBMIT);
        }
        return false;
    }
    private function _setStore($input)
    {
        if (is_array($input['ser_id'])) {
            $temp = $input['ser_id'];
            $input['ser_id'] = implode(',', $temp);
        }
        if (is_array($input['goods_id'])) {
            $temp = $input['goods_id'];
            $input['goods_id'] = implode(',', $temp);
        }
        $data = [];
        $data['sup_num'] = "S" . date("Ymdhis") . str_pad(rand(0, 999), 3, '0', STR_PAD_LEFT);//活动编号
        $data['sup_creactime'] = date('Y-m-d H:i:s');  //创建时间
        $data['sup_creacer'] = Request()->get('session_token')['admin_acc'];
        $data['sup_startime'] = $input['sup_startime'];
        $data['sup_endtime'] = $input['sup_endtime'];
        $data['sup_price'] = $input['sup_price'];
        $data['sup_brname'] = $input['sup_brname'];
        $data['sup_serid'] = $input['sup_serid'];
        $data['sup_goodids'] = $input['goods_id'];
        $data['sup_cadid'] = $input['sup_cadid'];
        $data['sup_type'] = $input['sup_type'];
        return $data;
    }

    private function _afterStore($entity)
    {
        $ip = Request()->ip();
        $creatorID = Request()->get('session_token')['admin_acc'];
        $content = "品牌:" . $entity['sup_brname'] . "；金额：" . $entity['sup_price'] . "；" . $entity['sup_startime'] . "至" . $entity['sup_endtime'] . "(" . $entity['sup_num'] . ")";
        $this->insertingLog("添加，", $entity['sup_num'], $content, '平台活动支持', $ip, $creatorID);
    }

    /**
     * @api {post} /api/service/activity//edit 服务商活动管理-编辑
     * @apiGroup 平台活动支持
     * @apiName 服务商活动管理-编辑
     * @apiVersion 1.0.0
     *
     * @apiDescription 服务商活动管理-编辑
     *
     * @apiParam {int} id  数据id
     *
     * @apiSuccess {int} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {array} Data    返回数据
     * @apiSuccessExample {json} Success-Response:
     * {
        "ErrorCode": 1,
        "ErrorMessage": "成功",
        "data": {
        "sup_data": {   //参数
        "sup_id": 6,     //id
        "sup_serid": "621",  //忽略
        "sup_type": "1",     //  1 全部型号   2 部分型号
        "sup_brname": "瓦尔塔",  //品牌
        "sup_price": 25,        //价格
        "sup_startime": "2019-10-11 15:30:25", //开始时间
        "sup_endtime": "2020-05-11 15:30:25"   //结束时间
        },
        "ser_data": [ //已选的服务中心
        {
        "id": 621,    //服务中心id
        "company_name": "北京-瓦尔塔-雷锋" //服务中心名称
        }
        ],
        "brand_data": [  //品牌列表
        {
        "brand_name": "AC德科", //品牌名称
        "type": 1               //1 代表 没有选择   2 代表 选中
        },
        {
        "brand_name": "瓦尔塔",
        "type": 2
        }
        ]
        "goods_data": [   //商品列表
        {
        "pg_id": 196,              //商品id
        "type": 1,                 //1 代表 没有选择   2 代表 选中
        "good_name": "蓝标-55415"  //商品名称
        }
        ]
        }
        }
     *
     */

    /*public function edit(Request $request)
    {
        $id = $request->input('id');
        //请求编辑数据
        $sup_data = $this->dataService->find($id);
        if (!$sup_data->isEmpty()) {
            $sup_arr = $sup_data->toArray()[0];
            //获取已有的服务中心
            $ser_id = explode(',', trim($sup_arr['sup_serid']));
            $condition = [];
            $condition['admin_groupnew'] = 2;
            $condition['id_searchin'] = $ser_id;
            $ser_data = AdminService::getAdmins($condition);
            //获取品牌数据
            $brand = GoodsService::getInUseBrands();
            foreach ($brand as $key => $value) {
                if ($value['brand_name'] == $sup_arr['sup_brname']) {
                    $brand[$key]['type'] = 2;
                } else {
                    $brand[$key]['type'] = 1;
                }
            }
            //处理商品信息；
            $goods_id = explode(',', $sup_arr['sup_goodids']);
            $goods = GoodsService::getBrandGoods($sup_arr['sup_brname']);
            foreach ($goods as $key => $val) {
                if (in_array($val['pg_id'], $goods_id)) {
                    $goods[$key]['type'] = 2;
                } else {
                    $goods[$key]['type'] = 1;
                }
                if ($val['pg_series'] == "") {
                    $goods[$key]['good_name'] = $val['version'];
                } else {
                    $goods[$key]['good_name'] = $val['pg_series'] . '-' . $val['version'];
                }
                unset($goods[$key]['version']);
                unset($goods[$key]['pg_series']);
            }

            return $this->success('获取 成功', ['sup_data' => $sup_arr, 'ser_data' => $ser_data, 'brand_data' => $brand, 'goods_data' => $goods]);
        } else {
            return $this->error('未找到数据', ErrorInc::DATA_EMPTY);
        }
    }*/

    /**
     * @api {post} /api/service/activity/update 服务商活动管理-添加
     * @apiGroup 平台活动支持
     * @apiName 服务商活动管理-添加
     * @apiVersion 1.0.0
     *
     * @apiDescription 服务商活动管理-添加
     *
     * @apiParam id        数据id
     * @apiParam ser_id        服务商id (array or string)
     * @apiParam goods_id      商品id(array or string)
     * @apiParam sup_startime  开始时间
     * @apiParam sup_endtime   结束时间
     * @apiParam sup_price     金额
     * @apiParam sup_brname    品牌名称
     *
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     * @apiSuccessExample {json} Success-Response:
     * {"Data":"","ErrorCode":1,"ErrorMessage":"修改成功"}
     *
     */
//    public function update ( Request $request ){
//        if(!$request->filled('id')){
//            return $this->error('缺少必要参数id', ErrorInc::INVALID_PARAM);
//            exit;
//        }else {
//            $input = $request->all();
//            if (is_array($input['ser_id'])) {
//                $temp = $input['ser_id'];
//                $input['ser_id'] = implode(',', $temp);
//            }
//            if (is_array($input['goods_id'])) {
//                $temp = $input['goods_id'];
//                $input['goods_id'] = implode(',', $temp);
//            }
//            $data = [];
//            $data['sup_startime'] = $input['sup_startime'];
//            $data['sup_endtime'] = $input['sup_endtime'];
//            $data['sup_price'] = $input['sup_price'];
//            $data['sup_brname'] = $input['sup_brname'];
//            $data['sup_serid'] = $input['sup_serid'];
//            $data['sup_goodids'] = $input['goods_id'];
//            $data['sup_cadid'] = $input['sup_cadid'];
//            $data['sup_type'] = $input['sup_type'];
//        }
//    }
    private function _setUpdate($input)
    {
        if (is_array($input['ser_id'])) {
            $temp = $input['ser_id'];
            $input['ser_id'] = implode(',', $temp);
        }
        if (is_array($input['goods_id'])) {
            $temp = $input['goods_id'];
            $input['goods_id'] = implode(',', $temp);
        }
        $data = [];
        $data['sup_startime'] = $input['sup_startime'];
        $data['sup_endtime'] = $input['sup_endtime'];
        $data['sup_price'] = $input['sup_price'];
        $data['sup_serid'] = $input['sup_serid'];
        $data['sup_goodids'] = $input['goods_id'];
        $data['sup_cadid'] = $input['sup_cadid'];
        $data['sup_type'] = $input['sup_type'];

        return $data;
    }

    private function _afterUpdate($entity, $beforeData)
    {
        $ip = Request()->ip();
        $creatorID = Request()->get('session_token')['admin_acc'];
        $content = "id:" . $entity['id'] . "，品牌:" . $entity['sup_brname'] . "；金额：" . $entity['sup_price'] . "；" . $entity['sup_startime'] . "至" . $entity['sup_endtime'] . "(" . $entity['sup_num'] . ")";
        $this->insertingLog("编辑，", $entity['sup_num'], $content, '平台活动支持', $ip, $creatorID);
    }

    /**
     * @api {delete} /api/service/activity/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:
     * {"Data":"","ErrorCode":1,"ErrorMessage":"删除成功"}
     *
     */

    private function _afterDestroy($entity)
    {
        $ip = Request()->ip();
        $creatorID = Request()->get('session_token')['admin_acc'];
        $content = "id->" . $entity['id '] . "，品牌:" . $entity['sup_brname'] . $entity['sup_startime'] . "至" . $entity['sup_endtime'];
        $this->insertingLog('删除，', '', $content, '平台活动支持', $ip, $creatorID);
    }


    /**
     * @api {post} /api/service/activity/show 服务商活动管理-查看
     * @apiGroup 平台活动支持
     * @apiName 服务商活动管理
     * @apiVersion 1.0.0
     *
     * @apiDescription 服务商活动管理-查看
     *
     * @apiParam {int} id       数据id
     *
     * @apiError {Number} ErrorCode    状态码，1：请求成功
     * @apiError {String} ErrorMessage   提示信息
     * @apiError {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"Data":["ser_data" => [], "goods_data" => []],"ErrorCode":1,"ErrorMessage":"成功"}
     *
     */
    public function show(Request $request)
    {
        if(!$request->filled('id')){
            return $this->error('缺少必要参数', ErrorInc::INVALID_PARAM);
            exit;
        }else {
            $id = $request->input('id');
            $sup_serid = ActivityService::getSupportByKey('sup_id',$id);
            if ($sup_serid) {
                $brand = PjBrandsService::getAll([],'brand_name');
                $sup_serid['brandid'] = $brand[$sup_serid['sup_brname']]['id'];
                //获取已有的服务中心
                $ser_id = explode(',', trim($sup_serid['sup_serid']));
                $condition = [];
                $condition['admin_groupnew'] = 2;
                $condition['id_searchin'] = $ser_id;
                $ser_data = AdminService::getAdmins($condition);
                //处理商品信息；
                $goods_id = explode(',', $sup_serid['sup_goodids']);
                if($goods_id) {
                    $goods = GoodsService::getGoodsByKey('pg_id', $goods_id, ['pg_id', 'brand_name', 'pg_series', 'version', 'cd_id']);
                }
                $sup_serid['ser_data'] = $ser_data;
                $sup_serid['goods_data'] = $goods;
                return $this->success('成功', $sup_serid);
            } else {
                return $this->error('暂无数据', ErrorInc::DATA_EMPTY);
            }
        }
    }


    //废掉的函数
    public function handle_data($input)
    {
        if (empty($input['sup_startime']) || empty($input['sup_endtime']) || empty($input['sup_brname']) || empty($input['ser_id'])) {
            throw new Exception("缺少参数");
        }
        if (empty($input['sup_price']) || $input['sup_price'] <= 0) {
            throw new Exception("支持价格不能小于0");
        }
        $start = strtotime($input['sup_startime']);
        $end = strtotime($input['sup_endtime']);
        if (($start + 20 * 3600) > $end) {
            throw new Exception("活动时长必须超过20个小时");
        }
        /*if(!$input['goods_id']){
            throw new Exception("商品不能为空,请选择商品");

        }*/
        if (is_array($input['ser_id'])) {
            $temp = $input['ser_id'];
            unset($input['ser_id']);
            $input['ser_id'] = implode(',', $temp);
        }
        if (is_array($input['goods_id'])) {
            $temp = $input['goods_id'];
            unset($input['goods_id']);
            $input['goods_id'] = implode(',', $temp);
        }
        return $input;
    }


    /**
     * @api {post} /api/service/activity/AdvanceEnd 提前结束活动
     * @apiGroup 平台活动支持
     * @apiName 提前结束活动
     * @apiVersion 1.0.0
     *
     * @apiDescription 服务商活动管理-查看
     *
     * @apiParam sup_id       数据id
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     * @apiSuccessExample {json} Success-Response:
     * {
        "ErrorCode": 1,
        "ErrorMessage": "操作成功",
        "data":''
        }
     *
     */

    public function AdvanceEnd(Request $request)
    {
        $id = (int)$request->input('sup_id', 0);
        $time = date('Y-m-d H:i:s');
        $sup_serid = $this->dataService->update(['sup_endtime' => $time], $id);

        if ($sup_serid) {
//            $this->inserting_log("提前结束，", "", "结束时间:" . $time . "，id->" . $id, "平台活动支持", $request->ip(), $request->get('session_token')['admin_acc']);//日志
            $this->insertingLog("编辑，", $request->input('sup_num'), '提前关闭活动：'.$request->input('sup_num'), '平台活动支持', $request->ip(), $request->get('session_token')['admin_acc']);

            return $this->success('操作成功');
        } else {

            return $this->error('操作失败', ErrorInc::MYSQL_FAILED);
        }
    }
}
