<?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\Models\PjGoods;
use App\Services\AdminService;
use App\Services\CommonService;
use App\Services\GoodsService;
use App\Services\SupplierXPriceService;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Traits\CurdControllerMethod;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SupplierXPriceController extends BaseController
{

    public $dataService = null;  // CurdControllerMethod 必备参数
    protected $dataFields = ['goods_id', 'ser_id', 'supply_price', 'goods_name','pt_type'];
    protected $validateRules = [
        'create_rules' => [
            'goods_id' => 'required|int',
            'ser_id' => 'required|int',
            'supply_price' => 'required',
            'remark' => 'max:50',
            'pt_type' => 'required|int',
            'goods_name' => 'required|max:50',
        ],
        'update_rules' => [
            'supply_price_new' => 'required',
            'remark_new' => 'max:100',
            'id' => 'required',
        ],
        'messages' => [
        ],
        'attributes' => [
            'goods_id' => '商品id',
            'ser_id' => '服务商id',
            'supply_price' => '供货价',
            'remark' => '备注',
            'goods_name' => '商品名称'
        ],'updat_attributes' => [
            'supply_price_new' => '供货价',
            'remark_new' => '备注',
            'id' => '数据编号',
        ]
    ];
    use CurdControllerMethod;

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

    /**
     * @api {post} /api/service/supplierPrice 列表页
     * @apiGroup 供货价管理
     * @apiName 列表页
     * @apiVersion 1.0.0
     *
     * @apiDescription 供货价列表页
     *
     * @apiParam version       商品编号
     * @apiParam brand_name    商品品牌
     * @apiParam gh_price_name 价格名
     * @apiParam company_id    服务商id
     * @apiParam create_time   开始时间
     * @apiParam end_time      结束时间
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":[]}
     *
     */


    /**
     * @api {post} /api/service/supplierPrice/create 添加供货价
     * @apiGroup 供货价管理
     * @apiName 添加供货价
     * @apiVersion 1.0.0
     *
     * @apiDescription 供货价列表添加供货价
     *
     * @apiParam {int} goods_id       商品id
     * @apiParam {int} ser_id         服务商id
     * @apiParam {float} supply_price 供货价
     * @apiParam {string} remark      备注
     *
     * @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('goods_id', 'ser_id', 'supply_price', 'goods_name','remark','pt_type');

        if ($this->validateRules) {
            $validate = validator()->make($input, $this->validateRules['create_rules'], $this->validateRules['messages'], $this->validateRules['attributes']);
            if ($validate->fails()) {
                $error = CommonService::validatorToString($validate);
                return $this->error($error, ErrorInc::INVALID_PARAM);
            }
        }
        //新增时直接查询是不是已经存在该服务商的指定商品签约价
        $exist = SupplierXPriceService::checkExistPrice($input['ser_id'], $input['goods_id'], $input['pt_type']);
        if ($exist) {
            return $this->error('选择的服务商已拥有该商品的供货价', ErrorInc::REPEAT_SUBMIT);
        }
        $data = $this->_setStore($input);
        $res = $this->dataService->create($data);
        if ($res) {
            $this->_afterStore($data);
            return $this->success('新增成功');
        } else {
            return $this->error('新增失败', ErrorInc::MYSQL_FAILED);
        }
    }

    /**
     * 新增时转译input内容到数据表字段内容
     * @param (array) $input
     * @return mixed
     */
    private function _setStore($input)
    {
        $arr = [];
        $arr['pt_type'] = $input['pt_type'];
        $arr['goods_id'] = $input['goods_id'];
        $arr['ser_id'] = $input['ser_id'];
        $arr['supply_price'] = $input['supply_price'];
        $arr['gh_price_name'] = Request()->get('session_token')['admin_acc'];
        if (!empty($input['remark'])) {
            $arr['remarks'] = $input['remark'];
        }
        $arr['gh_gname'] = $input['goods_name'];

        return $arr;
    }

    private function _afterStore($res) {
        if($res['ser_id'] =='0'){
            $company = '统一价格';
        }else {
            $company = AdminService::getAdminBy('id', $res['ser_id'], ['company_name']);
        }
        $info = GoodsService::getGoodsByKey('pg_id', $res['goods_id'],['brand_name','pg_series','version']);
        $goods = $info['good_name'];
        $content = "添加供货价,门店：".$company."；商品：" . $goods . "，价格：" . $res['supply_price'];
        $this->insertingLog('添加', '', $content, '分销供货价管理', Request()->ip(), Request()->get('session_token')['admin_acc']);
    }

    /**
     * @api {post} /api/service/supplierPrice/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":[]}
     *
     */
//    public function edit(Request $request)
//    {
//        $id = $request->input('id');
//        $res = SupplierPriceService::getPrice($id);
//
//        return $this->success('获取成功', ['entity' => $res]);
//    }

    /**
     * @api {post} /api/service/supplierPrice/update 保存供货价
     * @apiGroup 供货价管理
     * @apiName 保存供货价
     * @apiVersion 1.0.0
     *
     * @apiDescription 保存供货价
     *
     * @apiParam {int} id     id
     * @apiParam {int} goods_id_new     商品id
     * @apiParam {int} ser_id_new       服务商id
     * @apiParam supply_price_new 供货价
     * @apiParam {string} remark_new       备注
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":[]}
     *
     */
    public function update(Request $request)
    {
        $id = $request->input('id');
        $input = $request->only('supply_price_new', 'remark','id','pt_type');
        if ($this->validateRules) {
            $validate = validator()
                ->make(
                    $input,
                    $this->validateRules['update_rules'],//字段规则
                    $this->validateRules['messages'],//规则说明
                    $this->validateRules['updat_attributes']//字段说明
                );
            if ($validate->fails()) {
                $error = CommonService::validatorToString($validate);
                return $this->error($error, ErrorInc::INVALID_PARAM);
            }
        }
        //判断数据存在性
        $entity = $this->dataService->find($id);
        if (!$entity) {
            return $this->error('数据不存在', ErrorInc::DATA_EMPTY);
        }

        //转译input内容到数据表字段内容
        $data = $this->_setUpdate($input);
        $data['gh_price_name'] = $request->get('session_token')['admin_name'];
        $data['create_time'] = date("Y-m-d H:i:s");

        $result = $this->dataService->update($data,$id);
        if ($result) {
            $this->_afterUpdate($data, $entity);

            return $this->success('修改成功');
        } else {
            return $this->error('修改失败', ErrorInc::MYSQL_FAILED);
        }
    }

    /**
     * 更新数据时转译input内容到数据表字段内容
     * @param (array) $input
     * @return mixed
     */
    private function _setUpdate($input)
    {
        $data = [];
        $data['pt_type'] = $input['pt_type'];
        $data['supply_price'] = $input['supply_price_new'];
        $data['remarks'] = $input['remark'];

        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * 供货价修改后钩子函数
     * @param mixed  $entity id号
     *
     * @author lixiaolin <2021-07-31>
     * |---------------------------------------------------------------------------------
     */
    public function _afterUpdate($entity, $beforeData)
    {
        if($beforeData['ser_id'] =='0'){
            $company = '统一价格';
        }else {
            $company = AdminService::getAdminBy('id', $beforeData['ser_id'], ['company_name']);
        }
        $content = "编辑供货价，编号：" . $beforeData['id'] . "；服务商：".$company."；商品：" . $beforeData['gh_gname'] . ",价格：" . $beforeData['supply_price'] . "->价格：" . $entity['supply_price'];
        $this->insertingLog('编辑，', '', $content, '分销供货价管理', Request()->ip(), Request()->get('session_token')['admin_acc']);
    }

    /**
     * @api {post} /api/service/supplierPrice/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":[]}
     *
     */

    /**|---------------------------------------------------------------------------------
     * 供货价删除后钩子函数操作
     * @param mixed  $entity   id号
     *
     * @author lixiaolin <2021-07-31>
     * |---------------------------------------------------------------------------------
     */
    public function _afterDestroy($entity)
    {
        if($entity->id =='0'){
            $company = '统一价格';
        }else {
            $company = AdminService::getAdminBy('id', $entity->ser_id, ['company_name']);
        }
        $content = "删除供货价，编号：" . $entity->id . ";服务门店：". $company. ";商品：" . $entity->gh_gname . "(" . $entity->supply_price . ")";
        $this->insertingLog('删除，', '', $content, '分销供货价管理', Request()->ip(), Request()->get('session_token')['admin_acc']);
    }
}
