<?php
namespace App\Http\Controllers\DatasBase;
use App\Http\Controllers\BaseController;
use App\Http\Controllers\Common\CommonController;
use App\Models\PjGoods;
use App\Models\SendGoods;
use App\Services\BmmcService;
use App\Services\CommonService;
use App\Services\EventGiftService;
use App\Services\ExceloutService;
use App\Services\OrderService;
use App\Services\SendGoodsService;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Http\Request;
use App\Models\EventGift;
use App\Models\Orders;
use App\Models\OrderMsg;
use App\Models\User;
use App\Models\Pt;
use DB;
use Excel;


class EventGiftController extends BaseController
{

    //服务类型
//    const GOODS_INFO = [
//        ['lid' => 1, 'value' => '搭电服务'],
//        ['lid' => 2, 'value' => '延保服务'],
//        ['lid' => 3, 'value' => '终身免费'],
//        ['lid' => 4, 'value' => '送水服务'],
//        ['lid' => 5, 'value' => '检测服务'],
//        ['lid' => 6, 'value' => '车用吸尘器'],
//        ['lid' => 7, 'value' => '车用净化器'],
//        ['lid' => 8, 'value' => '车用加湿器'],
//        ['lid' => 9, 'value' => '车用手机支架'],
//        ['lid' => 10, 'value' => '车用旋转香薰手机支架'],
//        ['lid' => 11, 'value' => '车用腰枕'],
//        ['lid' => 12, 'value' => '扫地机器人'],
//        ['lid' => 13, 'value' => '米其林除味剂'],
//        ['lid' => 14, 'value' => '露营帐篷'],
//        ['lid' => 15, 'value' => '米其林车蜡'],
//        ['lid' => 16, 'value' => 'WD-40除锈剂'],
//        ['lid' => 17, 'value' => '迷你充电宝'],
//        ['lid' => 18, 'value' => '北欧风保温壶'],
//        ['lid' => 19, 'value' => '水果榨汁杯'],
//        ['lid' => 20, 'value' => '汽车清洁剂'],
//    ];

    //服务类型
//    const GOODS_NEED = [1 => '搭电服务', 2 => '延保服务', 3 => '终身免费', 4 => '送水服务', 5 => '检测服务', 6 => '车用吸尘器', 7 => '车用净化器', 8 => '车用加湿器', 9 => '车用手机支架', 10 => '车用旋转香薰手机支架', 11 =>'车用腰枕', 12 => '扫地机器人', 13 => '米其林除味剂', 14 => '露营帐篷', 15 => '米其林车蜡', 16 => 'WD-40除锈剂', 17 => '迷你充电宝', 18 => '北欧风保温壶', 19 => '水果榨汁杯', 20 => '汽车清洁剂'];

    /**
     * @name 列表
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/9/10
     */
    public function index (Request $request)
    {
        $Db = (new EventGift())->with('admin');//模型关联
        if ($request->input('gift_state') == 1) {
            $Db = $Db->where('gift_state',1);
        } elseif ($request->input('gift_state') == 2) {
            $Db = $Db->where('gift_state',5);
        } elseif ($request->input('gift_state') == 0) {
        } elseif ($request->input('gift_state') == 3) {
            $Db = $Db->where('gift_state',50);
        }

        if ($request->filled('order_num')) { //订单单号
            $Db = $Db->where('order_num',$request->input('order_num'));
        }
        if ($request->filled('shr_phone')) { //客户电话
            $Db = $Db->where('shr_phone',$request->input('shr_phone'));
        }
        if ($request->filled('goods_info')) { //礼品信息
            $Db = $Db->where('goods_info',$request->input('goods_info'));
        }

        if ($request->filled('creatdate')) { //时间
            $creatdate = $request->input('creatdate');
            $creat = [$creatdate[0], $creatdate[1].' 23:59:59'];
            //print_r($creat);
            $Db = $Db->whereBetween('created_at', $creat);
        }

        $page_size = (int)$request->input('page_size',10);
        $page = (int)$request->input('page',1);
        if($page<1){
            $page = 1;
        }
        $offset = ($page-1)*$page_size;
        $count = $Db->count();
        if($request->input('is_excel')==1){
            DB::connection()->enableQueryLog();#开启执行日志
        }
        $list = $Db->orderBy('created_at','DESC')->offset($offset)->limit($page_size)->get();

//导出 start
        if ($request->input('is_excel') == 1) {
            $session = $request->get('session_token');
            $sqls = DB::getQueryLog()[0];
            $excel = new CommonController();
            return $excel->getExcelOut($request->input('Pri_id'), $sqls, $session);
        }
        //导出 end


        $wcl = (new EventGift())->where('gift_state',1)->count();
        $data['show_Menu'] = [
            ['showname'=>"全部",'status'=>'0','shownum'=>"--"],
            ['showname'=>"未处理",'status'=>'1','shownum'=>$wcl??0],
            ['showname'=>"已完成",'status'=>'2','shownum'=>"--"],
            ['showname'=>"已撤销",'status'=>'3','shownum'=>"--"],

        ];
        $all_button = BmmcService::whereButton($request->input('token'),$request->input('Pri_id'));
        $export = BmmcService::getTopButton('import,gift_add,export,sysGoodsCodeName,sysSendGoods','',$all_button);
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮

        $status_name = OrderService::getOrderStatusName();
        $send_status_names = EventGiftService::getSendStatus();
        if (!$list->isEmpty()) {
            $list = $list->toArray();
            $pts = Pt::pluck('pt_name','id')->toArray();
            $goods_need = EventGiftService::getGift(true);
            foreach ($list as $k => $v) {
                $buttonData = [];
                $sys_num = Orders::where('order_num',$v['order_num'])->value('sys_num');
                $list[$k]['sys_num'] = $sys_num??'';

                $list[$k]['send_status_name'] = $send_status_names[$v['send_status']];

                if ($v['admin'] != 'null') {
                    $list[$k]['company_name'] = $v['admin']['company_name'];
                } else {
                    $list[$k]['company_name'] = '暂无';
                }
                if (isset($pts[$v['pt_id']])) {
                    $list[$k]['pt_name'] = $pts[$v['pt_id']];
                } else {
                    $list[$k]['pt_name'] = '暂无';
                }

                if($v['type']==2){

                    $list[$k]['goods_info_name'] = $v['gift_name']??'';
                }else{
                    $list[$k]['goods_info_name'] = $goods_need[$v['goods_info']]??'未设定';
                }

                $list[$k]['order_status_name'] = $status_name[$v['order_status']];

                if ($v['gift_state'] == 1) {//礼品状态
                    $list[$k]['gift_state_name'] = '未处理';
                } elseif ($v['gift_state'] == 5) {
                    $list[$k]['gift_state_name'] = '已处理';
                } elseif ($v['gift_state'] == 50) {
                    $list[$k]['gift_state_name'] = '已撤销';
                }

                if ($v['gift_type'] == 1) {//礼品类型
                    $list[$k]['gift_type_name'] = '单品';
                } elseif ($v['gift_type'] == 2) {
                    $list[$k]['gift_type_name'] = '终身';
                } elseif ($v['gift_type'] == 3) {
                    $list[$k]['gift_type_name'] = '多次';
                }

                if($v['type']==2){
                    $list[$k]['type_name'] = '库房发货';
                }else{
                    $list[$k]['type_name'] = '非库房发货';
                }

                //??$v['express_num']."(".$v['expressage'].")"
                $list[$k]['express_num'] = $v['express_num'];
                unset($list[$k]['admin']);

                if ($v['gift_state'] == 1){
                    $buttonData[] = 'remarks,gift_revoke,gift_handle,gift_set';
                }elseif ($v['gift_state'] == 5){
                    $buttonData[] = 'remarks,gift_revoke,gift_set';
                } elseif ($v['gift_state'] == 50) {
                    $buttonData[] = 'remarks';
                }

                if($v['type']==2 && $v['send_type']==2 && $v['gift_state']!=50 && $v['send_status']!=3){
                    $buttonData[] = 'remarks,sysSendGoodsID';
                }
                if($v['type']==2 && $v['gift_state']!=50){
                    $buttonData[] = 'switchSendType';
                }
                $button = BmmcService::getListButton($buttonData,$all_button);
                $list[$k]['button_one'] = $button['button_one']??[];
                $list[$k]['button_two'] = $button['button_two']??[];
                $list[$k]['button_three'] = $button['button_three']??[];

            }
            $data['list'] = $list;
            $data['page'] = [
                'count' => $count,
                'page'  => $page,
                'page_size' => $page_size,
                'allPage'  => ceil($count/$page_size)
            ];
            return $this->success('获取成功', $data); exit;
        }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$data);exit;
        }

    }


    /**
     * @name 获取礼品服务信息
     * @return mixed
     * @author du
     * @date 2021/9/10
     */
    public function getGift ()
    {
        $data['data'] =  EventGiftService::getGift();
        return $this->success('获取成功', $data); exit;
    }


    /**
     * 获取礼品订单信息
     * @param int $param
     * return array
     */
/*    private function info (int $param) {
        $info = EventGift::where('id',$param)->first([
            'order_num','goods_name','goods_info','shr_name','shr_sheng','shr_shi','shr_xian','shr_address'
        ]);
        $goods = self::GOODS_INFO;
        $goods_info = [];
        foreach ($goods as $k => $v ) {
            $goods_info[$v['lid']] = $v['value'];
        }
        $info['goods_info_name'] = $goods_info[$info['goods_info']];
        return $info;
    }*/

    /**
     * @name  撤销
     * @param id       数据id
     * @param content  备注内容
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/9/10
     */
    public function giftRevoke (Request $request)
    {
        if ($request->filled('id')&&$request->filled('content')) {
            $token = $request->get('session_token');
            $order_num = EventGift::where('id',$request->input('id'))->value('order_num');
            $sys_num = Orders::where('order_num',$order_num)->value('sys_num');
            if(!$order_num||!$sys_num){
                return $this->error('订单号不存在',ErrorInc::MYSQL_FAILED);exit;
            }
            if ($request->filled('content')) {
                $content = $request->input('content');
                $rest = CommonService::accMe($sys_num,'活动礼品','撤销：'.$content,$order_num,1,$token['admin_groupnew'],$token['admin_acc'],$token['id']);
                if (!$rest) {
                    return $this->error('备注添加失败', ErrorInc::MYSQL_FAILED);exit;
                }
            }
            $res = EventGift::where('id',$request->input('id'))->update([
                'gift_state' => 50,
                'updated_at' => date('Y-m-d H:i:s')
            ]);

            if ($res) {
                $this->insertingLog('撤销，',$sys_num,'数据id：'.$request->input('id'),'活动礼品',$request->ip(),$request->get('session_token')['admin_acc']);
                return $this->success('操作成功');exit;
            } else {
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
            }
        } else {
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
        }
    }


    /**|---------------------------------------------------------------------------------
     * @name  处理
     * @param id           数据id
     * @param express_num  执行单号
     * @return \Illuminate\Http\JsonResponse
     * @author he <2019/10/29>
     * |---------------------------------------------------------------------------------
     */
    /**
     * @name  处理
     * @param id           数据id
     * @param express_num  执行单号
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/9/10
     */
    public function giftHandle (Request $request)
    {
        if ($request->filled('id')&&$request->filled('express_num')) {
            $express_num = $request->input('express_num');
            $token = $request->get('session_token');
            $id = intval($request->input('id'));
            $gift = EventGift::where('id',$id)->first(['gift_state','order_num']);
            if ($gift['gift_state'] != 1) {
                return $this->error('该单状态错误', ErrorInc::MYSQL_FAILED);exit;
            }
            $res = EventGift::where('id',$id)->update([
                'gift_state' => 5,
                'express_num' => $express_num,
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
            if ($res) {
                //日志
                $this->insertingLog('处理，',$gift['order_num'],'处理：'.$gift['order_num'],'活动礼品',$request->ip(),$token['admin_acc']);
                return $this->success('操作成功');exit;
            } else {
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
            }
        } else {
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
        }
    }

    /**
     * @name  类型设置
     * @param id  数据id
     * @param gift_type  礼品状态；1：单品；2：终身；3：多次
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/9/10
     */
    public function giftSet (Request $request)
    {
        if ($request->filled('id')&&$request->filled('gift_type')) {
            $gift_type = $request->input('gift_type');
            $token = $request->get('session_token');
            $info = EventGift::where('id',$request->input('id'))->first(['order_num','gift_type']);
            if ($gift_type == $info['gift_type']) {
                return $this->error('操作失败，类型未更改', ErrorInc::MYSQL_FAILED);exit;
            }
            if ($gift_type == 3) {
                $service_num = $request->input('service_num');
            } else {
                $service_num = 1;
            }
            $res = EventGift::where('id',$request->input('id'))->update([
                'gift_type' => $gift_type,
                'service_num' => $service_num
            ]);
            if ($res) {
                //日志
                $this->insertingLog('类型设置，',$info['order_num'],'类型设置：'.$info['order_num'],'活动礼品',$request->ip(),$token['admin_acc']);
                return $this->success('操作成功');exit;
            } else {
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
            }
        } else {
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
        }
    }


    /**
     * @name  添加
     * @param type        1:获取客户信息；2：添加
     * @param order_num   平台单号
     * @param goods_info  礼品信息
     * @param gift_type   数据类型（单品，多次，终身）
     * @param shr_phone   客户电话
     * @param shr_name    客户姓名
     * @param shr_sheng   地址省
     * @param shr_shi     地址市
     * @param shr_xian    地址县
     * @param shr_address 详细地址
     * @param customer_id 用户id
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/9/10
     */
    public function giftAdd (Request $request)
    {
        return EventGiftService::giftAdd($request);
    }

    /**
     * @name  导入订单
     * @param goods_info 礼品信息类型ID
     * @param Request $request
     * @return mixed
     * @throws \Exception
     * @author du
     * @date 2021/9/10
     */
    public function giftImport (Request $request)
    {
        try{
            if(!$request->filled('type')){
                return $this->error('参数错误type或商品ID必传', ErrorInc::FAILED_PARAM);exit;
            }
            $file = $request->file('file');
            $goods_info = $request->input('goods_info')??0;
            $type = $request->input('type')??1; //类型： 1 服务； 2 商品
            $send_type = $request->input('send_type')??1;//1 非库房发货； 2 库房发货

            $goods_id = intval($request->input('pg_id'));//商品ID
            $goods_code = DB::table('pj_goodcode')->where('pgc_pgid',$goods_id)->value('pgc_code');



            $admin_acc = $request->get('session_token')['admin_acc'];
            if (!$file){
                return $this->error('请选择文件', ErrorInc::FAILED_PARAM, []);exit;
            }
            $ext = $file->getClientOriginalExtension();     // 扩展名
            if(!in_array($ext,['xls','xlsx'])){
                throw new \Exception("仅支持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($goods_info,$admin_acc,$type,$send_type,$goods_code){
                $reader = $reader->getSheet(0);
                $data = $reader->toArray();

                $list = $data;
                if($list[0][0]!='平台单号' || $list[0][1]!='服务总次数' || $list[0][2]!='数据类型' || $list[0][3]!='快递单号'|| $list[0][4]!='快递公司'){
	                throw new \Exception('excel格式错误');
                }
                $order_nums = [];
                foreach ($list as $k => $v) {
                    if (($k > 0) && ($v[0] != null)) {
                        $order_nums[] = trim($v[0]);
                    }
                }
                if ($order_nums == []) {
                    throw new \Exception('excel格式错误');
                }
                $shrArr = Orders::leftJoin('user','orders.customer_id','=','user.id')->whereIn('order_num',$order_nums)
                    ->select('order_num','goods_name','customer_id','shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress','p_id','ser_id','order_status')
                    ->get()->toArray();

                $marin = [];

                foreach ($shrArr as $ks => $vs) {
                      $marin[$vs['order_num']] = $vs;
                }
                if ($marin == []) {
                    throw new \Exception('单号在系统中不存在');
                }
                $arr = [];
                foreach ($data as $key => $val){
	                $num = trim($val[0]);
                    $exit = EventGift::where('order_num',$num)->first();
                    if ($exit) {
                        throw new \Exception('该单号已存在');
                    }
	                if(!isset($marin[$num]) && $key != 0){
	                    //$order[] = $num.' 单号不存在';
		                DB::table('event_history')->insert([
		                    'order_num'   => $num,
                            'results'     => '单号不存在',
                            'creact_time' => date('Y-m-d H:i:s'),
                            'creacter'    => $admin_acc
                        ]);
	                }
                    if (isset($marin[$num]) && $key >0) {
                        $arr[$key]['order_num']  = preg_replace('/[^0-9a-zA-Z\_\-]+$/','',$val[0]);//$val[0];//单号

                        $arr[$key]['type']  = $type;
                        $arr[$key]['send_type']  = $send_type;
                        $arr[$key]['goods_info']  = $goods_info;
                        if ($val[2] == '单品') {
                            $arr[$key]['gift_type']  = 1;
                        } elseif ($val[2] == '终身') {
                            $arr[$key]['gift_type']  = 2;
                        } elseif ($val[2] == '多次') {
                            $arr[$key]['gift_type']  = 3;
                        }else{
	                        $arr[$key]['gift_type']  = 1;
                        }

                        $arr[$key]['service_num']  = $val[1];//服务总次数
                        $arr[$key]['exec_num']  = '0';//执行次数
                        $arr[$key]['express_num']  = $val[3]??'';//快递号/执行单号
                        if($val[3]!=''){
	                        $arr[$key]['gift_state']= 5;//礼品状态；1：未处理；5：已处理；50：已撤销
                        	$arr[$key]['exec_num']  = '1';//执行次数
                        }
						$arr[$key]['expressage']  = $val[4];//快递公司
                        $arr[$key]['goods_code']  = $goods_code;//$val[5];//商品编号gone_pj_goodcode
                        $arr[$key]['goods_name']  = $marin[$num]['goods_name'];//商品名称
                        $arr[$key]['pt_id']  = $marin[$num]['p_id'];//平台id
                        $arr[$key]['shr_name']  = $marin[$num]['shr_name'];//客户姓名
                        $arr[$key]['shr_phone']  = $marin[$num]['shr_phone'];//客户电话
                        $arr[$key]['shr_sheng']  = $marin[$num]['shr_sheng'];//省
                        $arr[$key]['shr_shi']  = $marin[$num]['shr_shi'];//市
                        $arr[$key]['shr_xian']  = $marin[$num]['shr_xian'];//县
                        $arr[$key]['shr_address']  = $marin[$num]['shr_adress'];//详细地址
                        $arr[$key]['shr_address']  = $marin[$num]['shr_adress'];//详细地址
                        $arr[$key]['ser_id'] = $marin[$num]['ser_id'];
                        $arr[$key]['order_status'] = $marin[$num]['order_status'];
                        $arr[$key]['created_at']  = date('Y-m-d H:i:s');//添加时间
                        $arr[$key]['updated_at']  = date('Y-m-d H:i:s');//添加时间
                        $even = EventGift::insert($arr[$key]);
                        if ($even) {
                            DB::table('event_history')->insert([
                                'order_num'   => $num,
                                'results'     => '回传成功',
                                'creact_time' => date('Y-m-d H:i:s'),
                                'creacter'    => $admin_acc
                            ]);
                        } else {
                            DB::table('event_history')->insert([
                                'order_num'   => $num,
                                'results'     => '回传失败',
                                'creact_time' => date('Y-m-d H:i:s'),
                                'creacter'    => $admin_acc
                            ]);
                        }
                    }
                }

            });
            if (file_exists($filename)){
                unlink($filename);
            }
            unset($data);
            return $this->success('导入成功');
        }catch(\Exception $e){
            return response()->json(['Data'=>[],'ErrorCode'=>2,'ErrorMessage'=>$e->getMessage()]);
           // return $this->error( $e->getMessage(), ErrorInc::MYSQL_FAILED);
        }
    }


    /**
     * @name  礼品信息
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/9/10
     */
 /*   public function giftData (Request $request)
    {
        $list = DB::table('giftdata')->get()->toArray();
        if ($list != []) {
            return $this->success('获取成功',$list);
        }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY);
        }
    }*/

    /**
     * @name  添加礼品信息类型
     * @param gift_name 礼品信息名称
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2021/9/10
     */
   /* public function addGiftData (Request $request)
    {
        if ($request->filled('gift_name')) {
            $res = DB::table('giftdata')->insert([
                'gift_name' => $request->input('gift_name')
            ]);
            if ($res) {
                return $this->success('操作成功');exit;
            } else {
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
            }
        }else{
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);
        }
    }*/

    /**
     * @name  回传记录
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/9/10
     */
    public function event_history (Request $request)
    {
        $Db = DB::table('event_history');
        if ($request->filled('order_num')) {
            $Db = $Db->where('order_num', $request->input('order_num'));
        }
        $page_size = (int)$request->input('page_size',20);
        $page = (int)$request->input('page',1);
        if ($page < 1) {
            $page = 1;
        }
        $offset = ($page-1)*$page_size;
        $count = $Db->count();
        $list = $Db->orderBy('creact_time','DESC')->offset($offset)->limit($page_size)->get()->toArray();
        if ($list && $list != []) {
            $data['list'] = $list;
            $data['page'] = [//页码信息
                'page' => $request->input('page',1),
                'page_size' => $page_size,
                'count' => $count,
                'allPage' => ceil($count/$page_size)
            ];
            return $this->success('获取成功', $data); exit;
        }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY);exit;
        }
    }

    /**
     * 批量更新
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/1/18
     */
    public function sysGoodsCodeName(Request $request){
        $info = EventGift::where('send_status',1)->where('type',2)->select('id','goods_code')->first();
        if(empty($info)){
            return $this->error('更新完成', ErrorInc::MYSQL_FAILED);
        }
        $id = $info['id'];
        $pj_id = DB::table('pj_goodcode')->where('pgc_code',$info['goods_code'])->value('pgc_pgid');
        if(!$pj_id){
            $ret = EventGift::where('id',$id)->update(['send_status'=>5]);
        }else {
            $gift_name = PjGoods::where('pg_id', $pj_id)->value('pg_goodsname');
            if (!$gift_name) {
                $ret = EventGift::where('id', $id)->update(['send_status' => 5]);
            } else {
                $ret = EventGift::where('id', $id)->update(['send_status' => 2, 'gift_name' => $gift_name]);
            }
        }
        if($ret){
            return $this->success('更新成功'); exit;
        }else{
            return $this->error('更新中断', ErrorInc::MYSQL_FAILED);
        }
    }

    /**
     * 同步发货单
     * @param Request $request
     * @return array|mixed
     * @author du
     * @date 2022/1/18
     * gift_state 1：未处理；5：已处理；50：已撤销
     * type:1 服务； 2 商品
     * send_status 1 未同步商品； 2 未发货 3 发货成功； 4 发货失败，5 同步失败
     * send_type 1 非库房发货； 2 库房发货
     */
    public function sysSendGoods(Request $request){
        if($request->filled('id')){
           // return $this->error('参数错误ID必传', ErrorInc::FAILED_PARAM);
            $id = intval($request->input('id'));
            $info = EventGift::where('id',$id)->first();
            if(empty($info)){
                return $this->error('无此数据', ErrorInc::MYSQL_FAILED);
            }
            if($info['type']!=2 || $info['send_type']!=2 || $info['gift_state']==50|| $info['send_status']==3){
                return $this->error('不是发货商品', ErrorInc::MYSQL_FAILED);exit;
            }
        }else{
            $info = EventGift::where('type',2)->where('send_type',2)->where('send_status',2)->where('gift_state','!=',50)->first();
            if(empty($info)){
                return $this->error('已完成', ErrorInc::MYSQL_FAILED);
            }
        }
        $ret = EventGiftService::sendGift($info, $request);

        return $ret;

       /* $afid = SendGoods::where('afid',$info['id'])->where('source',3)->value('id');
        if($afid){
            EventGift::where('id',$info['id'])->update(['send_status'=>3]);
            return $this->success('已存在');exit;
        }

        $pj_id = DB::table('pj_goodcode')->where('pgc_code',$info['goods_code'])->value('pgc_pgid');
        if(!$pj_id){
            return $this->error('不存在商品', ErrorInc::MYSQL_FAILED);
        }

        $datas['order_num'] = $info['order_num'];
        $datas['sys_num'] = OrderService::getOrderBy('order_num', $info['order_num'],['sys_num']);

        $data['0']['goods_id'] = $pj_id;//商品ID
        $data['0']['goods_name'] = PjGoods::where('pg_id', $pj_id)->value('pg_goodsname');
        $data['0']['msg_id'] = 0;
        $data['0']['goods_num'] = $info['service_num'];//数量
        $datas['data'] = $data;
        $datas['send_type'] = 2;//发货类型:1自有门店2库房
        $datas['collect_type'] = 2;//收货人类型 1门店发货  2客户收货
        $datas['delivery_store'] = 4;//天津仓
        $datas['send_time'] = date('Y-m-d H:i:s',strtotime('+3 day'));
        $datas['name'] = $info['shr_name'];
        $datas['telephone'] = $info['shr_phone'];
        $datas['shr_sheng'] = $info['shr_sheng'];
        $datas['shr_shi'] = $info['shr_shi'];
        $datas['shr_xian'] = $info['shr_xian'];
        $datas['address'] = $info['shr_address'];
        $datas['note'] = '礼品单发货同步';
        $datas['source'] = 3;//数据来源1无来源2售后3礼品
        $datas['after_id'] = $info['id'];//关联ID
        $request->merge($datas);

        DB::beginTransaction();
        $return = SendGoodsService::sendGoods($request,true);
        if($return['ErrorCode'] == '1'){
            EventGift::where('id',$info['id'])->update(['send_status'=>3]);
            DB::commit(); //提交
        }else{
            DB::rollback();//回滚
            EventGift::where('id',$info['id'])->update(['send_status'=>4]);
        }
        return $return;*/
    }


    /**
     * @name 修改发货类型
     * send_type类型： 1 非库房发货； 2 库房发货
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/3/22
     */
   /* public function updateSendtype(Request $request)
    {
        if (!$request->filled('id') || !$request->filled('send_type')) {
            return $this->error('参数错误ID和发货类型必传', ErrorInc::FAILED_PARAM);
        }
        $id = intval($request->input('id'));
        $send_type = intval($request->input('send_type'));
        $info = EventGift::where('id', $id)->first();
        if (empty($info)) {
            return $this->error('无此数据', ErrorInc::MYSQL_FAILED);
        }
        //gift_state 礼品状态；1：未处理；5：已处理；50：已撤销',
        $nowtime = date("Y-m-d H:i:s");

        $res = EventGift::where('id', $id)->update(['send_type' => $send_type, 'updated_at' => $nowtime]);
        if ($res) {
            //日志
            $this->insertingLog('修改发货类型，', $info['order_num'], '发货类型由：' . $info['send_type'] . 'w修改为' . $send_type, '活动礼品', $request->ip(), $request->get('session_token')['admin_acc']);
            return $this->success('操作成功');
            exit;
        } else {
            return $this->error('操作失败', ErrorInc::MYSQL_FAILED);
            exit;
        }
    }*/


    /**|---------------------------------------------------------------------------------
     * @name 切换发货类型
     * @param int id 数据id
     * @param int send_type 发货类型1 非库房发货； 2 库房发货
     * @retrun /multitype:array
     * @author dou 2022/3/22 15:05
     * |---------------------------------------------------------------------------------
     */
    public function switchSendType ( Request $request ){
        if($request->filled('id') && $request->filled('send_type')) {
            $id = intval($request->input('id'));
            $send_type = intval($request->input('send_type'));
            $info = EventGift::where('id', $id)->first();
            if (empty($info)) {
                return $this->error('无此数据', ErrorInc::MYSQL_FAILED);
            }
            if ($info['type'] != 2) {
                return $this->error('不是发货商品', ErrorInc::MYSQL_FAILED);
                exit;
            }
            $nowtime = date("Y-m-d H:i:s");
            if($send_type == '1'){
                DB::beginTransaction();
                $rea = EventGift::where('id',$info['id'])->update(['send_type'=>$send_type]);
                if($rea) {
                    $sendOrder = SendGoodsService::getSendGoodBy(['afid' => $info['id'], 'source' => 3, 'reject_searchlt' => 5], ['id', 'send_num', 'order_num'], 'first');
                    if ($sendOrder) {
                        $db = Db::table('send_goods');
                        $sendGoods = CommonService::getMysqlData($db, ['pid' => $sendOrder['id'], 'reject' => 1], ['id', 'goods_name'], [], 'first');
                        $data = SendGoodsService::reject($sendGoods['id'], $sendOrder['send_num'], $sendOrder['order_num'], $sendGoods['goods_name'], $sendOrder['id'], 2, $request->get('session_token'), $request->ip());
                        if ($data['ErrorCode'] != 1) {
                            DB::rollback();
                            return $this->error($data['ErrorMessage'], $data['ErrorCode']);exit;
                        }
                    }

                    //日志
                    $this->insertingLog('修改发货类型，', $info['order_num'], '发货类型由：' . $info['send_type'] . 'w修改为' . $send_type, '活动礼品', $request->ip(), $request->get('session_token')['admin_acc']);

                    DB::commit();
                    $this->success('操作成功');exit;
                }else{
                    DB::rollback();
                    return $this->error('操作失败1', ErrorInc::MYSQL_FAILED);
                }
            }elseif ($send_type == '2'){
                //切换为库房发货
                $info['send_type'] = $send_type;
                $ret = EventGiftService::sendGift($info, $request);
                return $ret;
            }else{
                return $this->error('发货类型错误', ErrorInc::INVALID_PARAM);
            }
        }else{
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);
        }

    }

}
