<?php
/*
|--------------------------------------------------------------------------
| 对服务商补贴管理(原 “活动系统/铅价指数补贴” ，对服务商需要进行补贴的管理)
|--------------------------------------------------------------------------
|  增删改查
|  @author liXiaoLin
|  @Date: 2021/7/27
|  @Time: 10:07
|  @Email: lixiaolin@bluearp.com
|  @version 1.0
|  @copyright BlueCity
*/

namespace App\Http\Controllers\Service;

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


class SubsidyController extends BaseController
{
    public $dataService = null;  // CurdControllerMethod 必备参数
    public $dataFields = ['chomodel', 'ld_price', 'pg_id', 'brand_name', 'ld_type', 'ld_release'];  // 保存和修改时的 fields 参数
    protected $validateRules = [
        'rules' => [
            'chomodel' => 'required|max:50',
            'ld_price' => 'required',
            'pg_id' => 'required|int',
            'brand_name' => 'required|max:50',
            'ld_type' => 'required',
            'ld_release' => 'required'
        ],
        'messages' => [

        ],
        'attributes' => [
            'chomodel' => '产品型号',
            'ld_price' => '补贴金额',
            'pg_id' => '产品ID',
            'brand_name' => '品牌名称',
            'ld_type' => '业务类型',
            'ld_release' => '业务类型'
        ]
    ];

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

    use CurdControllerMethod;

    /**
     * @api {post} /api/service/subsidy 列表页
     * @apiGroup 对服务商补贴管理
     * @apiName 列表页
     * @apiVersion 1.0.0
     *
     * @apiDescription 供货价列表页
     *
     * @apiParam order_time 时间
     * @apiParam brand_name 品牌名称
     * @apiParam goods_name 商品名称
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":[]}
     *
     */

    /**
     * @api {post} /api/service/subsidy/store 新增
     * @apiGroup 对服务商补贴管理（铅价补贴）
     * @apiName 新增
     * @apiVersion 1.0.0
     *
     * @apiDescription 对服务商补贴新增
     *
     * @apiParam {int} pg_id       商品id
     * @apiParam ld_price    补贴价格(type3)
     * @apiParam {string} brand_name  品牌名称(type3)
     * @apiParam {string} chomodel    电瓶型号框显示的内容(type3)
     * @apiParam {int} ld_type   19 淡季活动价补贴，14 结算补贴 	19
     * @apiParam {int} ld_release  1 开启 2 未开启
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":[]}
     *
     */
    private function _beforeStore($input){
        $data['le_setyid'] = $input['ld_type'] ?? 19;
        $data['ld_goodid'] = $input['pg_id'];
        if (SubsidyService::getLeadsubsidieBy($data,['ld_id'],'first')) {
            return $this->error('数据已经存在', ErrorInc::DATA_EXIST);
        }
        return false;
    }

    private function _setStore($input)
    {
        $data['ld_goodid'] = $input['pg_id'];
        if($input['ld_price']<0){
            $input['ld_price'] = 0 - $input['ld_price'];
        }
        $data['ld_price'] = $input['ld_price'];
        $data['ld_brand'] = $input['brand_name'];
        $data['le_setyid'] = $input['ld_type'] ?? 19;
        $data['ld_release'] = $input['ld_release'] ?? 2;
        $data['ld_creacter'] = Request()->get('session_token')['admin_acc'];

        return $data;
    }

    private function _afterStore($res)
    {
        $choModel = Request()->get('chomodel');
        $ip = Request()->ip();
        $creatorID = Request()->get('session_token')['admin_acc'];
        $this->insertingLog("添加，", '', "补贴：" . $choModel . " -> 价格：" . $res->ld_price, '金额补贴', $ip, $creatorID);
    }

    /**
     * @api {post} /api/service/subsidy/update 修改
     * @apiGroup 对服务商补贴管理（铅价补贴）
     * @apiName 修改
     * @apiVersion 1.0.0
     *
     * @apiDescription 对服务商补贴新增
     *
     * @apiParam id        id号
     * @apiParam ld_price    补贴价格(type3)
     * @apiParam {int} ld_type   19 淡季活动价补贴，14 结算补贴 	19
     * @apiParam {int} ld_release  1 开启 2 未开启
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":[]}
     *
     */
    private function _beforeUpdate($input,$id){
        $data['le_setyid'] = $input['ld_type'] ?? 19;
        $data['ld_goodid'] = $input['pg_id'];
        $data['ld_id_noteq'] = $id;
        if (SubsidyService::getLeadsubsidieBy($data,['ld_id'],'first')) {
            return $this->error('同类型数据已存在数据已经存在', ErrorInc::DATA_EXIST);
        }
        return false;

    }

    private function _setUpdate($input)
    {
        $creatorID = Request()->get('session_token')['admin_acc'];
        if($input['ld_price']<0){
            $input['ld_price'] = 0 - $input['ld_price'];
        }
        $data['ld_price'] = $input['ld_price'];
        $data['le_setyid'] = $input['ld_type'] ?? 19;
        $data['ld_release'] = $input['ld_release'] ?? 2;
        $data['ld_creacter'] = $creatorID;

        return $data;
    }

    private function _afterUpdate($info, $beforeData)
    {
        $choModel = Request()->get('chomodel');
        $ip = Request()->ip();
        $creatorID = Request()->get('session_token')['admin_acc'];
        $content = "编辑补贴，" . $choModel . "（" . $beforeData['ld_id'] . "）：" . $beforeData['le_setyid'] . "-" . $beforeData['ld_price'] . "->" . $info['le_setyid'] . "-" . $info['ld_price'];
        $this->insertingLog("编辑，", '', $content, '金额补贴', $ip, $creatorID);
    }


    /**
     * @api {post} /api/service/subsidy/delete 删除补贴
     * @apiGroup 对服务商补贴管理（铅价补贴）
     * @apiName 删除补贴
     * @apiVersion 1.0.0
     *
     * @apiDescription 对服务商补贴新增
     *
     * @apiParam id        id号
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":[]}
     *
     */

    private function _afterDestroy($entity)
    {
        $ip = Request()->ip();
        $creatorID = Request()->get('session_token')['admin_acc'];
        $info = GoodsService::getGoodsByKey('pg_id', $entity['ld_goodid'],['brand_name','pg_series','version']);
        $goods = $info['good_name'];
        $content = "补贴删除".$goods."(" . $entity['le_setyid'].")";
        $this->insertingLog('删除,', '', $content, '铅价指数补贴', $ip, $creatorID);
    }

    /**
     * @api {post} /api/service/subsidy/Switch 开启补贴或关闭补贴
     * @apiGroup 对服务商补贴管理（铅价补贴）
     * @apiName 开启补贴或关闭补贴
     * @apiVersion 1.0.0
     *
     * @apiDescription 对服务商补贴关闭或者开启
     *
     * @apiParam id        id号
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":[]}
     *
     */

    public function releaseSwitch(Request $request)
    {
        if ($request->filled('id')) {
            $id = $request->input('id');

            $entity = SubsidyService::getSubsidy($id);
            if (!$entity) {
                return  $this->error('未找到内容', ErrorInc::DATA_EMPTY);
            }
            if ($entity['ld_release'] == 1) {
                $str = "关闭，";
                $type = 2;
            } elseif ($entity['ld_release'] == 2) {
                $str = "开启，";
                $type = 1;
            } else {
                $type = 2;
            }
            $delRes = $this->dataService->update(['ld_release' => $type], $id);
            if ($delRes) {
                $info = GoodsService::getGoodsByKey('pg_id', $entity['ld_goodid'],['brand_name','pg_series','version']);
                $goods = $info['good_name'];
                $content = $str.":".$goods."(".$entity['le_setyid'].")";
                $this->insertingLog($str.',', '', $content, '铅价指数补贴', $request->ip(),  $request->get('session_token')['admin_acc']);
                return $this->success('更新成功，补贴内容已 '  . ($type == 1 ? '开启' : '关闭'));
            } else {
                return  $this->error('更新失败，请确认您已修改了内容', ErrorInc::MYSQL_FAILED);
            }
        } else {
            return  $this->error('参数错误', ErrorInc::INVALID_PARAM);
        }
    }


    /**
     * @api {post} /api/service/subsidy/switchAll 开启和关闭全部功能
     * @apiGroup 对服务商补贴管理（铅价补贴）
     * @apiName 开启和关闭全部功能
     * @apiVersion 1.0.0
     *
     * @apiDescription 开启和关闭全部功能
     *
     * @apiParam id        id号
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":[]}
     *
     */

    public function switchAll(Request $request)
    {
        if(!$request->filled('type')){
            return $this->error('操作类型必传', ErrorInc::INVALID_PARAM);exit;
        }
        $type = (int)$request->input('type', 1);
        if ($type == 1) {
            $state = 1;
            $sts = "开启全部补贴，";
            $sti = "开启全部补贴";
        } else {
            $state = 2;
            $sts = "关闭全部补贴，";
            $sti = "关闭全部补贴";
        }
        $str = [1 => '开启', 2 => '关闭'];
        $delRes = SubsidyService::switches($state, []);
        if ($delRes) {
            $this->insertingLog($sts, "", "操作：" . $sti, "铅价指数补贴", $request->ip(), $request->get('session_token')['admin_acc']);

            return $this->success('更新成功，补贴内容已 '  . $str[$state]);
        } else {
            return  $this->error($str[$state] . '失败', ErrorInc::INVALID_PARAM);
        }
    }

}
