<?php
/**
 * 文件名称（礼品管理）
 * 文件简单描述（礼品管理操作权限）
 * @author DouBin
 * @Date: 2021/11/2
 * @Time: 16:54
 * @Email: db@sudianwang.com
 * @version 1.0
 * @copyright BlueCity
 */
namespace App\Services;
use App\Http\Controllers\BaseController;
use App\Models\EventGift;
use App\Models\OrderMsg;
use App\Models\Orders;
use App\Models\PjGoods;
use App\Models\SendGoods;
use App\Models\User;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Service\Service;
use DB;
class EventGiftService extends Service{
    /**|---------------------------------------------------------------------------------
     * @name 添加礼品
     * @param array $request 请求参数
     * @retrun /multitype:array
     * @author dou 2021/11/2 16:56
     * |---------------------------------------------------------------------------------
    */
    public static function giftAdd ( $request ){
        if (!$request->filled('order_num')) {
            return ['Data' => [], 'ErrorMessage' =>'平台单号不能为空', 'ErrorCode' => ErrorInc::FAILED_PARAM];
        }
        //获取商品和客户信息
        if ($request->input('type') == 1) {
            $orderinfo = Orders::where('order_num',$request->input('order_num'))->first(['sys_num','customer_id']);
            $goods_name = OrderMsg::where('sys_num',$orderinfo['sys_num'])->pluck('goods_name')->toArray();
            $goods_name = implode(',',$goods_name);
            $userinfo = User::where('id',$orderinfo['customer_id'])->first(['shr_phone','shr_name','shr_sheng','shr_shi','shr_xian','shr_adress']);
            if (isset($goods_name) && isset($userinfo['shr_phone']) && isset($userinfo['shr_name'])) {
                $data = [
                    'shr_phone' => $userinfo['shr_phone'],
                    'shr_name' => $userinfo['shr_name'],
                    'goods_name' => $goods_name,
                    'customer_id'=> $orderinfo['customer_id'],
                    'shr_sheng'=> $userinfo['shr_sheng'],
                    'shr_shi'=> $userinfo['shr_shi'],
                    'shr_xian'=> $userinfo['shr_xian'],
                    'shr_address'=> $userinfo['shr_adress'],
                ];
                return ['Data' => $data, 'ErrorMessage' =>'获取成功', 'ErrorCode' => 1];
            } else {
                return ['Data' => [], 'ErrorMessage' =>'暂无数据', 'ErrorCode' => ErrorInc::DATA_EMPTY];
            }

        } elseif ($request->input('type') == 2) {//执行添加
            $input = $request->only('goods_name','order_num','goods_info','gift_type','shr_phone','shr_name','shr_sheng','shr_shi','shr_xian','shr_address','customer_id','g_type','send_type','pg_id','service_num');

            $g_type = $request->input('g_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')??'0';

            /*if (!$request->filled('goods_info')) {
                return ['Data' => [], 'ErrorMessage' =>'礼品信息不能为空', 'ErrorCode' => ErrorInc::FAILED_PARAM];
            }
            if (!$request->filled('gift_type')) {
                return ['Data' => [], 'ErrorMessage' =>'礼品服务类型不能为空', 'ErrorCode' => ErrorInc::FAILED_PARAM];
            }*/
            if (!$request->filled(['goods_name','shr_phone','shr_name','customer_id'])) {
                return ['Data' => [], 'ErrorMessage' =>'参数错误1', 'ErrorCode' => ErrorInc::FAILED_PARAM];
            }
            /*if ($g_type==1 && (!is_numeric($input['goods_info']) || !is_numeric($input['gift_type']))) {
                return ['Data' => [], 'ErrorMessage' =>'参数错误2', 'ErrorCode' => ErrorInc::FAILED_PARAM];
            }*/
            $goods_info = $input['goods_info']??0;
            if ($g_type==1){
                $exit = EventGift::where('order_num',$input['order_num'])->where('goods_info',$goods_info)->where('gift_state',1)->first();
            }else{
                $exit = EventGift::where('order_num',$input['order_num'])->where('goods_code',$goods_code)->where('gift_state',1)->first();
            }

            if (isset($exit) && ($request->input('double_type') != 2)) {
                return ['Data' => [], 'ErrorMessage' =>'已存在该礼品,确定再次添加吗？', 'ErrorCode' => 31];
            }
            if (!$request->filled(['shr_sheng','shr_shi','shr_xian','shr_address'])) {
                $shr = User::where('id',$input['customer_id'])->first(['shr_sheng','shr_shi','shr_xian','shr_adress']);
                $shr_sheng = $shr['shr_sheng'];
                $shr_shi = $shr['shr_shi'];
                $shr_xian = $shr['shr_xian'];
                $shr_address = $shr['shr_adress'];
            } else {
                $shr_sheng = $input['shr_sheng'];
                $shr_shi = $input['shr_shi'];
                $shr_xian = $input['shr_xian'];
                $shr_address = $input['shr_address'];
            }

            $inf = Orders::where('order_num',$input['order_num'])->first(['p_id','ser_id','order_status','sys_num']);
            if (!isset($inf['p_id']) || !isset($inf['ser_id']) || !isset($inf['order_status'])) {
                return ['Data' => [], 'ErrorMessage' =>'参数错误3', 'ErrorCode' => ErrorInc::FAILED_PARAM];
            }

            $res = EventGift::insertGetId([
                'order_num' => $input['order_num'],
                'goods_name' => $input['goods_name'],
                'pt_id' => $inf['p_id'],
                'goods_info' => $goods_info,
                'shr_name' => $input['shr_name'],
                'shr_phone' => $input['shr_phone'],
                'shr_sheng' => $shr_sheng,
                'shr_shi' => $shr_shi,
                'shr_xian' => $shr_xian,
                'shr_address' => $shr_address,
                'ser_id' => $inf['ser_id'],
                'order_status' => $inf['order_status'],
                'gift_type' => $input['gift_type'],
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
                'type' => $g_type,
                'send_type' => $send_type,
                'goods_code' => $goods_code,
                'service_num' => $input['service_num']??0,
            ]);
            if ($res) {
                //同步发货
                $info = EventGift::where('id',$res)->first()->toarray();
                if($info['type']!=2 || $info['send_type']!=2 || $info['gift_state']==50|| $info['send_status']==3){
                }else{
                    $ret = self::sendGift($info, $request);
                    if($ret['ErrorCode'] != '1'){
                        return $ret;
                    }
                }
                $BaseController = new BaseController();
                $avtion = FunctionsService::getFunctionsBy('function_id', $request->input('Pri_id'), ['function_name']);
                $BaseController->insertingLog('添加礼品,', $inf['sys_num'], '添加活动礼品：'.$input['goods_info'], $avtion, $request->ip(), $request->get("session_token")['admin_acc']);
                return ['Data' => [], 'ErrorMessage' =>'操作成功', 'ErrorCode' => 1];
            } else {
                return ['Data' => [], 'ErrorMessage' =>'操作失败', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
            }
        }else{
            return ['Data' => [], 'ErrorMessage' =>'参数错误4', 'ErrorCode' => ErrorInc::FAILED_PARAM];
        }
    }

    /**|---------------------------------------------------------------------------------
     * 获取退单信息
     * @param string $key 查询键
     * @param string $value 查询值
     * @param array $select 需查询参数
     * @param string $type 查询类型
     * @retrun /multitype:array
     * @author dou 2021/11/5 16:16
     * |---------------------------------------------------------------------------------
    */
    public static function getInfoByKeyValue($key , $value , $select = [] , $type = 'get')
    {
        $db = new EventGift();
        if($key == 'id'){
            $type = 'first';
        }
        if($type == 'first' && count($select)=='1'){
            $type = 'value';
        }
        $list = CommonService::getMysqlData($db,[$key=>$value],$select,[],$type);
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取订单详情
     * @param string $order_num 订单单号
     * @retrun /multitype:array
     * @author dou 2021/11/5 15:57
     * |---------------------------------------------------------------------------------
     */
    public static function getDetailByOrder ( $order_num ){
        $list = self::getInfoByKeyValue('order_num', $order_num);
        if($list) {
            $goodinfo = self::getGift(true);
            foreach($list as $k => $v){
                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'] = '多次';
                }
                $list[$k]['good_infoname'] = $goodinfo[$v['goods_info']]??'未设定';
            }
        }
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取礼品信息
     * @retrun /multitype:array
     * @author dou 2021/11/10 14:19
     * |---------------------------------------------------------------------------------
    */
    public static function getGift ( $tyep = false ){
//        $goodinfo = array(array('lid' => 1, 'value' => '搭电服务'),);
        $goodinfo = [['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' => '汽车清洁剂'],
        ];
        if($tyep){
            $goodinfo = array_column($goodinfo, 'value','lid');
        }
        return $goodinfo;
    }

    /**
     * 获取发货状态
     * @return string[]
     * @author du
     * @date 2022/1/18
     */
    public static function getSendStatus(){
        $data = ['1'=>'未同步商品','2'=>'未发货', '3'=>'发货成功','4'=>'发货失败','5'=>'同步失败'];
        return $data;
    }

    /**
     * @name 礼品发送同步
     * @param $info
     * @param $request
     * @return array
     * @author du
     * @date 2022/2/15
     */
    public static function sendGift($info,$request){
        $afid = SendGoods::where('afid',$info['id'])->where('source',3)->where('reject','<',5)->value('id');
        if($afid){
            EventGift::where('id',$info['id'])->update(['send_status'=>3]);
            return  ['Data' => '','ErrorMessage'=>'已存在','ErrorCode'=>ErrorInc::MYSQL_FAILED];exit;
        }

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

        $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,'send_type'=>$info['send_type']]);
            DB::commit(); //提交
        }else{
            DB::rollback();//回滚
            EventGift::where('id',$info['id'])->update(['send_status'=>4]);
        }
        return $return;
    }



}
