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

class SupplierPriceController extends BaseController
{
    public $dataService = null;  // CurdControllerMethod 必备参数
    protected $dataFields = ['goods_id', 'ser_id', 'supply_price', 'goods_name'];
    protected $validateRules = [
        'create_rules' => [
            'goods_id' => 'required|int',
            'ser_id' => 'required|int',
            'supply_price' => 'required',
            'remark' => 'max:50',
            '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 SupplierPriceService();
        $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":[]}
     *
     */
public function index(Request $request)
{

    $session = $request->get('session_token');
    $page = Request()->input('page', 1);
    if ($page < 1) {
        $page = 1;
    }
    $data = $this->dataService->search_s($request->all(), ['*'], $page, 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, $session, $request);
    }
    $data['service_type'][] = ['type'=>1,'name'=>'自营'];
    $data['service_type'][] = ['type'=>2,'name'=>'平台'];
    if (!empty($data['list'])) {

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


   // return SupplierPriceService::search_s($param, array('*'),1, 20,$session);
}

    /**
     * @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');

    //     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);
    //         }
    //     }
    //     $input['company_id'] = $request->get('session_token')['company_id'];
    //     //新增时直接查询是不是已经存在该服务商的指定商品签约价
    //     $exist = SupplierPriceService::checkExistPrice($input['ser_id'], $input['goods_id'],$input['company_id']);
    //     if ($exist) {
    //         return $this->error('选择的服务商已拥有该商品的供货价', ErrorInc::REPEAT_SUBMIT);
    //     }
    //     $data = $this->_setStore($input);
    //     $data['company_id'] = $request->get('session_token')['company_id'];
    //     $res = $this->dataService->create($data);
    //     if ($res) {
    //         $this->_afterStore($data);
    //         return $this->success('新增成功');
    //     } else {
    //         return $this->error('新增失败', ErrorInc::MYSQL_FAILED);
    //     }
    // }

    /**
     * 新增供货价
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-09-20
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function store(Request $request)
    {
        $session = $request->get('session_token');

        if ($session['admin_groupnew'] != 7) {
            $request['company_id'] = $session['company_id'];
        }
        if (empty($request['goods_data'])) {
            return $this->error('请选择商品', ErrorInc::REPEAT_SUBMIT);
        }
        DB::beginTransaction();
        foreach ($request['goods_data'] as $key => $value) {
            $poss['ser_id'] = $request['ser_id'];
            $poss['goods_id'] = $value['goods_id'];
            $poss['goods_name'] = $value['goods_name'];
            $poss['company_id'] = $request['company_id'];
            $poss['supply_price'] = $value['supply_price'];
            $poss['remark'] = $value['remark'];
            $poss['type'] = $request['type'];

            //新增时直接查询是不是已经存在该服务商的指定商品签约价
            $exist = SupplierPriceService::checkExistPrice($poss['ser_id'], $poss['goods_id'],$poss['company_id']);
            if ($exist) {
                return $this->error('选择的服务商已拥有该商品的供货价', ErrorInc::REPEAT_SUBMIT);
            }
            $data = $this->_setStore($poss);
            $res = $this->dataService->create($data);
            if ($res) {
                $this->_afterStore($data);
            } else {
                DB::rollback();
                return $this->error('新增失败', ErrorInc::MYSQL_FAILED);
            }
        }
        DB::commit();
        return $this->success('新增成功');
    }

    /**
     * 新增时转译input内容到数据表字段内容
     * @param (array) $input
     * @return mixed
     */
    private function _setStore($input)
    {
        $arr = [];
        $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'];
        $arr['company_id'] = $input['company_id'];
        $arr['type'] = $input['type'];

        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');
        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['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']);
    }

    /**|---------------------------------------------------------------------------------
     * @name 上传excel导入
     * @param file 文件名
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2025/4/11 15:03
     * |---------------------------------------------------------------------------------
    */
    public function uploadExcelImport ( Request $request ){
        try {
            $file = $request->file('file');
            $session = $request->get('session_token');
            $admin_acc = $session['admin_acc'];

            if ($session['admin_groupnew'] != 7) {//管理员可以看全部
                $company_id = $session['company_id'];
            }else{
                $company_id = $request->input('company_id')??1;
            }

            if (!$file){
                throw new ApiException("请选择文件");
            }
            $ext = $file->getClientOriginalExtension();// 获取扩展名
            if(!in_array($ext,['xls','xlsx','csv'])){//判断格式
                throw new ApiException("仅支持xls和xlsx结尾的excel文件");
            }
            //上传文件
            $file_name = date('YmdHis').rand(10,99).'.'.$ext;
            $urlname = public_path('excel');
            $file->move($urlname,$file_name);
            $filename = $urlname.'/'.$file_name;
            Excel::load($filename,function($reader)use($admin_acc,$company_id){
                $reader = $reader->getSheet(0);

                $data = $reader->toArray();
                if($data[0][0]!='商品编号' && $data[0][1]!='商品名称' && $data[0][2]!='服务商id' && $data[0][3]!='服务商名称' && $data[0][4]!='结算价格' && $data[0][5]!='生效日期' && $data[0][6]!='备注'){
                    throw new \Exception("excel格式错误,请检验表格");
                }
                unset($data['0']);
                $sql = "INSERT IGNORE INTO gone_gh_price_lead (gh_price_name,goods_id,ser_id,ser_name,create_time,remarks,supply_price,gh_gname,company_id,start_date,update_time,is_state,state_explain) VALUES ";
                $sqls = [];
                foreach ($data as $key => $val){
                    if($data[$key]['4']!='' && $data[$key]['4']!=0 && $data[$key]['0']!='' && $data[$key]['0']!=0) {
                        $sqls[] = "(
                        '" . $admin_acc . "',
                        '" . $this->restrict($data[$key]['0']) . "',
                        '" . $this->restrict($data[$key]['2']) . "',
                        '" . $this->restrict($data[$key]['3']) . "',
                        '" . date("Y-m-d H:i:s") . "',
                        '" . $this->restrict($data[$key]['6']) . "',
                        '" . $this->restrict($data[$key]['4']) . "',
                        '" . $this->restrict($data[$key]['1']) . "',
                        '" . $company_id . "',
                        '" . $this->restrict($data[$key]['5']) . "',
                        '" . date("Y-m-d H:i:s") . "',
                        '1',
                        '未处理'
                        )";
                    }
                }
                if(empty($sqls)){
                    throw new \Exception("无有效数据,请检验表格");
                }
                $sql.=implode(',',$sqls);
                DB::insert($sql);
            });
            if (file_exists($filename)){
                //echo 11;
                unlink($filename);
            }
            unset($data);
            $content = '导入了文件'.$filename;
            $this->insertingLog('导入，','',$content,'绑定sku',$request->ip(),$request->get('session_token')['admin_acc']);
            return $this->success('导入成功1');
        }catch(\Exception $e){
            return $this->error($e->getMessage(), ErrorInc::MYSQL_FAILED);
        }
    }
    //去除空格
    function restrict($str){
        $is_str=array(" ","　","\t","\n","\r","	");
        $is_str_er=array("","","","","","");
        return str_replace($is_str,$is_str_er,$str);
    }

    /**|---------------------------------------------------------------------------------
     * @name 同步绑定
     * @param string is_type 同步类型1指定同步2批量同步
     * @param int id 数据id
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2025/4/10 18:13
     * |---------------------------------------------------------------------------------
     */
    public function sysLeadData ( Request $request ){
        $session = $request->get('session_token');
        $input = $request->all();
        if (!$request->filled('is_type') || !in_array($input['is_type'], [1,2])){
            return $this->error('操作类型错误', ErrorInc::FAILED_PARAM, []);
        }
        if($input['is_type'] == 1) {
            if (!$request->filled('id')) {
                return $this->error('缺少数据id', ErrorInc::FAILED_PARAM, []);
            }
            $data = GhPriceLead::where('id',$input['id'])->where('is_state',1)->where('company_id',$session['company_id'])->first();
            if(empty($data)){
                return $this->error('数据状态错误', ErrorInc::REQUEST_FORBIDDEN);
            }
        }else{
            $data = GhPriceLead::where('is_state',1)->orderBy('id')->where('company_id',$session['company_id'])->first();
            if(empty($data)){
                return $this->error('无更多数据', ErrorInc::DATA_EMPTY);
            }
        }
        $data = CommonService::dataToArray($data);
        if($data['ser_id'] != 0 && $data['ser_name'] == '统一结算价'){
            $res = GhPriceLead::where('id',$data['id'])->where('is_state',1)->update(['is_state'=>'2','state_explain'=>'服务商异常','update_time'=>date("Y-m-d H:i:s")]);
        }else{
            $poss['gh_price_name'] = $data['gh_price_name'];
            $poss['goods_id'] = $data['goods_id'];
            $poss['remarks'] = $data['remarks'];
            $poss['supply_price'] = $data['supply_price'];
            $poss['gh_gname'] = $data['gh_gname'];
            $poss['start_date'] = $data['start_date'];
            if($data['ser_id'] > 0 && $data['ser_name']=='统一结算价'){
                $res = GhPriceLead::where('id',$data['id'])->where('is_state',1)->update(['is_state'=>'2','state_explain'=>'服务商id与服务商名称不符','update_time'=>date("Y-m-d H:i:s")]);
                return $this->error('操作失败', ErrorInc::MYSQL_STEP_FAILED, []);
            }else{
                $poss['ser_id'] = $data['ser_id'];
                if($data['ser_name']!='统一结算价'){
                    $ser_id = Admin::where("company_name",$data['ser_name'])->value("id");
                    if(empty($ser_id) || $data['ser_id']!=$ser_id){
                        $res = GhPriceLead::where('id',$data['id'])->where('is_state',1)->update(['is_state'=>'2','state_explain'=>'服务商id与服务商名称不符','update_time'=>date("Y-m-d H:i:s")]);
                        return $this->error('操作失败', ErrorInc::MYSQL_STEP_FAILED, []);
                    }
                }
            }
            $pg_goodsname = PjGoods::where("pg_id",$data['goods_id'])->where('is_delect',1)->value('pg_goodsname');
            if(empty($pg_goodsname)){
                $res = GhPriceLead::where('id',$data['id'])->where('is_state',1)->update(['is_state'=>'2','state_explain'=>'商品编号不存在','update_time'=>date("Y-m-d H:i:s")]);
                return $this->error('操作失败', ErrorInc::MYSQL_STEP_FAILED, []);
            }
            $list = GhPrice::where("goods_id",$poss['goods_id'])
                ->where("ser_id",$poss['ser_id'])
                ->where("company_id",$poss['company_id'])
                ->where("start_date",$poss['start_date'])
                ->value('supply_price');
            DB::beginTransaction();
            if(!$list) {
                $poss['create_time'] = date("Y-m-d H:i:s");
                $poss['company_id'] = $data['company_id'];
                $poss['type'] = $data['type'];
                $rea = GhPrice::insert($poss);
                $content = '添加商品:'.$poss['gh_gname'].'('.$poss['goods_id'].')：'.$poss['supply_price'];
            }else{
                $poss['update_time'] = date("Y-m-d H:i:s");
                $rea = GhPrice::where("goods_id",$poss['goods_id'])
                    ->where("ser_id",$poss['ser_id'])
                    ->where("start_date",$poss['start_date'])
                    ->where("company_id",$poss['company_id'])
                    ->uptate($poss);
                $content = '编辑商品:'.$poss['gh_gname'].'('.$poss['goods_id'].')：'.$list.'->'.$poss['supply_price'];
            }
            if($rea){
                $res = GhPriceLead::where('id',$data['id'])->where('is_state',1)->update(['is_state'=>'3','state_explain'=>'添加成功','update_time'=>date("Y-m-d H:i:s")]);
                if($res){
                    $this->insertingLog("同步结算价，",$poss['goods_id'],$content,"供货价格管理",$request->ip(),$request->get('session_token')['admin_acc']);//日志
                    DB::commit();
                    return $this->success('操作成功'); exit;
                }else{
                    DB::rollback();
                    return $this->error('操作失败', ErrorInc::MYSQL_STEP_FAILED, []);
                }
            }else{
                DB::rollback();
                $rea = JdBoundLead::where('id',$data['id'])->update(['is_state'=>2,'state_explain'=>'同步失败','update_time'=>date("Y-m-d H:i:s")]);
                return $this->error('操作失败', ErrorInc::MYSQL_STEP_FAILED, []);
            }
        }
    }
}
