<?php

namespace App\Services\WeChatApplet\User;

use App\Services\CommonService;
use App\Services\LoginUserService;
use Illuminate\Database\Eloquent\Model;
use App\Models\WeChatApplet\User\UserShop;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Models\Common;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Validators\WeChatApplet\User\UserShopValidator;
use BlueCity\Core\Inc\ErrorInc;

// 用户小程序-门店
class UserShopService extends Service
{
    public static $instance;
    public $modelMain = null;
    public $mainValidator = null;

    public function __construct()
    {
        $this->modelMain = new UserShop();
        $this->mainValidator = new UserShopValidator();
    }

    /**
     * @return mixed
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }

    /**
     * 根据条件搜索数据内容
     *按工单分类查询
     * @param array $param 条件
     * @param array $columns 内容
     * @param int $page 页码
     * @param int $pageSize 页容量
     * @return mixed
     */
    public function searchPage($search_data, $show_count = 10)
    {
        // 判断是否有用户id
        if (empty($search_data['weus_id'])) {
            if (empty($search_data['shop_id'])) {
                $data['data'] = [];                        //返回数据
                return $data;
            } else {
                // 没有用户id，查询门店表数据
                $list_data = DB::table('shop')
                    ->where('shop_type', 1)//类型：1总店2直营店3加盟店
                    ->where('shop_state', 1)//状态1营业2停业
                    ->where(function ($query) use ($search_data) { //门店id
                        if (!empty($search_data['shop_id'])) {
                            $query->where('shop_id', $search_data['shop_id']);
                        }
                    })
                    ->select('shop_id', 'shop_store_name', 'shop_phone', 'shop_province', 'shop_city', 'shop_county', 'shop_address', 'shop_image', 'shop_state', 'shop_longitude', 'shop_latitude', 'shop_opening_time', 'shop_service_scope')
                    ->orderBy('shop_id', 'asc')
                    ->paginate($show_count);
            }
        } else {
            // 扫门店二维码查看，更新门店的绑定时间，如果是第一次扫门店二维码，绑定门店
            if (isset($search_data['source']) && $search_data['source'] == 2 && !empty($search_data['shop_id']) ) {
                // 查询微信用户与门店的关系是否存在绑定关系
                $find_user_shop_data = DB::table('user_shop')
                    ->where('ussh_weus_id', $search_data['weus_id'])
                    ->where('ussh_shop_id', $search_data['shop_id'])
                    ->select('ussh_id', 'ussh_user_id', 'ussh_user_type', 'ussh_phone')
                    ->first();
                if (empty($find_user_shop_data)) {
                    // 没有查到当前微信用户与门店的绑定关系，添加门店绑定关系
                    // 查找当前微信用户的信息
                    $find_user_data = DB::table('weixin_user')
                        ->where('weus_id', $search_data['weus_id'])
                        ->select('weus_id', 'weus_phone', 'weus_nickmame', 'weus_sex')
                        ->first();
                    // 根据手机号查询当前门店用户的会员是否存在，不存在默认新增会员,与微信用户绑定
                    if (!empty($find_user_data->weus_phone)) {
                        $find_mem_data = DB::table('member')
                            ->where('mem_phone', $find_user_data->weus_phone)
                            ->where('mem_shop_id', $search_data['shop_id'])
                            ->select('mem_id', 'mem_name', 'mem_phone')
                            ->first();
                        if (empty($find_mem_data)) {
                            $find_shop_cid = DB::table('shop')
                                ->where('shop_id', $search_data['shop_id'])
                                ->value('shop_cid');
                            // 新增门店会员
                            $add_mem_data['mem_superior_shop_id'] = $search_data['shop_id'];
                            $add_mem_data['mem_cid'] = $find_shop_cid;
                            $add_mem_data['mem_shop_id'] = $search_data['shop_id'];
                            $add_mem_data['mem_name'] = $find_user_data->weus_nickmame;
                            $add_mem_data['mem_phone'] = $find_user_data->weus_phone;
                            $add_mem_data['mem_sex'] = $find_user_data->weus_sex;
                            $mem_id = DB::table('member')->insertGetId($add_mem_data);
                            $ussh_data['ussh_user_id'] = $mem_id;
                            unset($add_mem_data);
                        } else {
                            $ussh_data['ussh_user_id'] = $find_mem_data->mem_id;
                        }
                        $ussh_data['ussh_phone'] = $find_user_data->weus_phone;
                    }

                    // 用户没有与当前门店绑定，把用户与当前门店绑定
                    $ussh_data['ussh_weus_id'] = $search_data['weus_id'];
                    $ussh_data['ussh_shop_id'] = $search_data['shop_id'];
                    $ussh_data['ussh_user_type'] = 1;
                    $ussh_data['ussh_create_time'] = date('Y-m-d H:i:s');
                    $ussh_id = DB::table('user_shop')->insertGetId($ussh_data);
                    if (!$ussh_id) {
                        return ['code'=>500, 'msg'=>'门店扫码失败', 'data'=>''];
                    }
                } else {
                    // 已经存在绑定关系，更新时间
                    $edit_ussh['ussh_create_time'] = date('Y-m-d H:i:s');
                    $res = DB::table('user_shop')
                        ->where('ussh_weus_id', $search_data['weus_id'])
                        ->where('ussh_shop_id', $search_data['shop_id'])
                        ->update($edit_ussh);
                }
            }

            $list_data = DB::table('user_shop as a')
                ->leftJoin('shop as b', 'a.ussh_shop_id', '=', 'b.shop_id')
                ->where(function ($query) use ($search_data) { //门店id
                    if (!empty($search_data['shop_id'])) {
                        $query->where('ussh_shop_id', $search_data['shop_id']);
                    }
                })
                ->where('ussh_weus_id', $search_data['weus_id'])
                ->select('shop_id', 'shop_store_name', 'shop_phone', 'shop_province', 'shop_city', 'shop_county', 'shop_address', 'shop_image', 'shop_state', 'shop_longitude', 'shop_latitude', 'shop_opening_time', 'shop_service_scope')
                ->orderBy('ussh_create_time', 'desc')
                ->paginate($show_count);
        }
        $list_items = $list_data->items();
        if ($list_items) {
            foreach ($list_items as $key => $value) {
                // 查询评论总数，总分数
                $find_evaluate = DB::table('evaluate_part')
                    ->where('evpa_shop_id', $value->shop_id)
                    ->select(DB::raw('count(*) as count, sum(evpa_score1) as total_score1'))
                    ->first();
    
                $temp_data['score'] = 0;
                if ($find_evaluate->count) {
                    $temp_data['score'] = round($find_evaluate->total_score1 / $find_evaluate->count, 2);//店铺分数
                }
                $temp_data['total_number'] = $find_evaluate->count;//评论总数
                $temp_data['shop_id'] = $value->shop_id;
                $other_data[] = $temp_data;
                unset($temp_data);
            }
        } else {
            $other_data = [];
        }
        
        $data['current_page'] = $list_data->currentPage();  //当前页面页码
        $data['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data['total'] = $list_data->total();               //总数据个数
        $data['current_number'] = $show_count;        //一页显示多少个
        $data['data'] = $list_items;                        //返回数据
        $data['other_data'] = $other_data;                        //返回数据
        return $data;
    }

    // 详情
    public static function info($search_data)
    {
        // 判断是否有用户id
        // if (empty($search_data['weus_id'])) {
        //     return ['code'=>500, 'msg'=>'用户未登录', 'data'=>[]];
        // } else {
            // 扫门店二维码查看，更新门店的绑定时间，如果是第一次扫门店二维码，绑定门店
            // isset($search_data['source']) && $search_data['source'] == 2 && 
            // if (!empty($search_data['shop_id']) ) {
            //     // 查询微信用户与门店的关系是否存在绑定关系
            //     $find_user_shop_data = DB::table('user_shop')
            //         // ->where('ussh_weus_id', $search_data['weus_id'])
            //         ->where('ussh_shop_id', $search_data['shop_id'])
            //         ->select('ussh_id', 'ussh_user_id', 'ussh_user_type', 'ussh_phone')
            //         ->first();
            //     if (empty($find_user_shop_data)) {
            //         // 没有查到当前微信用户与门店的绑定关系，添加门店绑定关系
            //         // 查找当前微信用户的信息
            //         $find_user_data = DB::table('weixin_user')
            //             ->where('weus_id', $search_data['weus_id'])
            //             ->select('weus_id', 'weus_phone', 'weus_nickmame', 'weus_sex')
            //             ->first();
            //         // 根据手机号查询当前门店用户的会员是否存在，不存在默认新增会员,与微信用户绑定
            //         if (!empty($find_user_data->weus_phone)) {
            //             $find_mem_data = DB::table('member')
            //                 ->where('mem_phone', $find_user_data->weus_phone)
            //                 ->where('mem_shop_id', $search_data['shop_id'])
            //                 ->select('mem_id', 'mem_name', 'mem_phone')
            //                 ->first();
            //             if (empty($find_mem_data)) {
            //                 $find_shop_cid = DB::table('shop')
            //                     ->where('shop_id', $search_data['shop_id'])
            //                     ->value('shop_cid');
            //                 // 新增门店会员
            //                 $add_mem_data['mem_superior_shop_id'] = $search_data['shop_id'];
            //                 $add_mem_data['mem_cid'] = $find_shop_cid;
            //                 $add_mem_data['mem_shop_id'] = $search_data['shop_id'];
            //                 $add_mem_data['mem_name'] = $find_user_data->weus_nickmame;
            //                 $add_mem_data['mem_phone'] = $find_user_data->weus_phone;
            //                 $add_mem_data['mem_sex'] = $find_user_data->weus_sex;
            //                 $mem_id = DB::table('member')->insertGetId($add_mem_data);
            //                 $ussh_data['ussh_user_id'] = $mem_id;
            //                 unset($add_mem_data);
            //             } else {
            //                 $ussh_data['ussh_user_id'] = $find_mem_data->mem_id;
            //             }
            //             $ussh_data['ussh_phone'] = $find_user_data->weus_phone;
            //         }

            //         // 用户没有与当前门店绑定，把用户与当前门店绑定
            //         $ussh_data['ussh_weus_id'] = $search_data['weus_id'];
            //         $ussh_data['ussh_shop_id'] = $search_data['shop_id'];
            //         $ussh_data['ussh_user_type'] = 1;
            //         $ussh_data['ussh_create_time'] = date('Y-m-d H:i:s');
            //         $ussh_id = DB::table('user_shop')->insertGetId($ussh_data);
            //         if (!$ussh_id) {
            //             return ['code'=>500, 'msg'=>'门店扫码失败', 'data'=>''];
            //         }
            //     } else {
            //         // 已经存在绑定关系，更新时间
            //         $edit_ussh['ussh_create_time'] = date('Y-m-d H:i:s');
            //         $res = DB::table('user_shop')
            //             ->where('ussh_weus_id', $search_data['weus_id'])
            //             ->where('ussh_shop_id', $search_data['shop_id'])
            //             ->update($edit_ussh);
            //     }
            // }
        // }
        // $list_data = DB::table('user_shop as a')
        //     ->leftJoin('shop as b', 'a.ussh_shop_id', '=', 'b.shop_id')
        //     ->where(function ($query) use ($search_data) { //门店id
        //         if (!empty($search_data['shop_id'])) {
        //             $query->where('ussh_shop_id', $search_data['shop_id']);
        //         }
        //     })
        //     // ->where('ussh_weus_id', $search_data['weus_id'])
        //     ->select('shop_id', 'shop_store_name', 'shop_phone', 'shop_province', 'shop_city', 'shop_county', 'shop_address', 'shop_image', 'shop_state', 'shop_longitude', 'shop_latitude', 'shop_banner_img')
        //     ->orderBy('ussh_create_time', 'desc')
        //     ->first();
        $list_data = DB::table('shop')
            // ->where(function ($query) use ($search_data) { //门店id
            //     if (!empty($search_data['shop_id'])) {
            //         $query->where('ussh_shop_id', $search_data['shop_id']);
            //     }
            // })
            ->where('shop_id', $search_data['shop_id'])
            ->select('shop_id', 'shop_store_name', 'shop_phone', 'shop_province', 'shop_city', 'shop_county', 'shop_address', 'shop_image', 'shop_state', 'shop_longitude', 'shop_latitude', 'shop_banner_img', 'shop_service_scope', 'shop_opening_time', 'shop_service_scope_name')
            // ->orderBy('ussh_create_time', 'desc')
            ->first();
        if (!empty($list_data) && !empty($search_data['longitude']) && !empty($search_data['latitude'])) {
            // 计算两个地址之间的距离（千米）
            $distance = getDistance($search_data['latitude'], $search_data['longitude'], $list_data->shop_latitude, $list_data->shop_longitude);
        } else {
            $distance = 0;
        }
        if (!empty($list_data)) {
            if (empty($list_data->shop_banner_img)) {
                $list_data->shop_banner_img = $list_data->shop_image;
            }
        }

        // 查询评论总数，总分数
        $find_evaluate = DB::table('evaluate_part')
            ->where('evpa_shop_id', $search_data['shop_id'])
            ->select(DB::raw('count(*) as count, sum(evpa_score1) as total_score1'))
            ->first();

        if ($distance < 1) {
            $new_distance = $distance*1000;
            $new_distance = $new_distance.'米';
        } else {
            $new_distance = $distance.'公里';
        }
        $other_data['new_distance'] = $new_distance;//两点之间的距离（千米）
        $other_data['distance'] = $distance;//两点之间的距离（千米）
        $other_data['score'] = 0;
        if ($find_evaluate->count) {
            $other_data['score'] = round($find_evaluate->total_score1 / $find_evaluate->count, 2);//店铺分数
        }
        $other_data['total_number'] = $find_evaluate->count;//评论总数
        $shop_new_banner = DB::table('shop_banner')
            ->where('shba_shop_id', $search_data['shop_id'])
            ->where('shba_show', 1)
            ->orderBy('shba_sord', 'desc')
            ->get()->toArray();
        $list_data->shop_new_banner = $shop_new_banner;
        return ['code'=>200, 'msg'=>'success', 'data'=>$list_data, 'other_data'=>$other_data];
    }

    // 首页获取分类 
    public static function getClassification($request)
    {
        $list_data = DB::table('goods_classification')
            ->where('gocl_shop_id', $request['shop_id'])
            ->where('gocl_state', 1)
            ->where('gocl_is_del', 2)
            ->select('gocl_id', 'gocl_name')
            ->orderBy('gocl_sort', 'ASC')
            ->get()->toArray();
        return $list_data;
    }

    // 首页获取分类下商品
    public static function getGoods($request,$type,$show_count=10)
    {
        // if (empty($request['pait_classify_id'])) {
        //     $gocl_data = Db::table('goods_classification')
        //         ->where('gocl_shop_id', $request['shop_id'])
        //         ->where('gocl_state', 1)
        //         ->where('gocl_is_del', 2)
        //         ->select('gocl_id', 'gocl_name')
        //         ->first();
        //     if ($gocl_data) {
        //         $request['pait_classify_id'] = $gocl_data->gocl_id;
        //     } else {
        //         $request['pait_classify_id'] = 0;
        //     }
        // }
        $list_data = DB::table('package_items')
            ->where('pait_shop_id', $request['shop_id'])
            ->where(function ($query) use ($request) {
                if (!empty($request['pait_classify_id'])) {
                    $query->where('pait_classify_id', $request['pait_classify_id']);
                }
            }) //关键词搜索
            // ->where('pait_classify_id', $request['pait_classify_id'])
            ->where('pait_state', 1)
            ->where(function ($query) use ($request) {
                if (!empty($request['keywords'])) {
                    $query->where('pait_name', 'like', '%' . $request['keywords'] . '%')
                        ->orwhere('pait_number', 'like', '%' . $request['keywords'] . '%');
                }
            }) //关键词搜索
            ->select('pait_id', 'pait_name', 'pait_shop_price', 'pait_sell_price', 'pait_pic', 'pait_number', 'pait_type')
            ->orderBy('pait_sort', 'desc');
        $list_data1 = $list_data->get();
        if ($type == 1) {
            $list_data = $list_data->get()->toArray();
        } else {
            $list_data = $list_data->paginate($show_count);
        }
        $vip_data = [];

        foreach ($list_data1 as $key => $value) {
            $correlation_goods = DB::table('correlation_goods as cogo')
                ->leftJoin('service_project as sepr', 'sepr.sepr_id', '=', 'cogo.cogo_goo_id')
                ->where('cogo_pait_id', $value->pait_id)
                ->select('sepr_id', 'sepr_work_type', 'cogo_goo_type')
                ->get()->toArray();
            if(count($correlation_goods) != 1) {
                continue;
            }
            if ($correlation_goods) {
                foreach ($correlation_goods as $key1 => $value1) {
                    if ($value1->sepr_work_type !=2 || $value1->cogo_goo_type !=2) {
                        continue;
                    }
                    $find_vip_data = DB::table('vip_card')
                        ->where('vica_state', 1)
                        ->where('vica_sepr_id', $value1->sepr_id)
                        ->select('vica_id', 'vica_name', 'vica_price', 'vica_effective_date', 'vica_sepr_name', 'vica_num', 'vica_shop_price', 'vica_long_term')
                        ->get()->toArray();
                    if ($find_vip_data) {
                        foreach ($find_vip_data as $key2 => $value2) {
                            $vip_data[] = $value2;
                        }
                    }
                }
            }
        }
        foreach ($list_data as $key1 => $value1) {
            $list_data[$key1]->pait_evaluate_num = DB::table('evaluate_goods')
                ->where('evgo_goo_id', $value1->pait_id)
                ->where('evgo_goo_type', 3)
                ->count();
            if ($list_data[$key1]->pait_evaluate_num > 10000) {
                $list_data[$key1]->pait_evaluate_num = '1万+';
            }
            if ($value1->pait_pic) {
                $pait_pic = json_decode($value1->pait_pic, true);
                $list_data[$key1]->pait_pic_first = $pait_pic[0];
            } else {
                $list_data[$key1]->pait_pic_first = '';
            }
            unset($list_data[$key1]->pait_pic);
        }
        $vip_id = [];
        $new_vip_data = [];
        if (!empty($vip_data)) {
            foreach ($vip_data as $key => $value) {
                if (!in_array($value->vica_id,$vip_id)) {
                    $vip_id[] = $value->vica_id;
                    $new_vip_data[] = $value;
                }
            }
        }
        if ($type == 1) {
            // $data['list_data'] = array_slice($list_data, 0, 10);//获取前几条数据
            $data['list_data'] = $list_data;
            $data['vip_data'] = $new_vip_data;
        } else {
            $data['list_data'] = $list_data->items();
            $data['vip_data'] = $new_vip_data;
            $data['page']['current_page'] = $list_data->currentPage();  //当前页面页码
            $data['page']['last_page'] = $list_data->lastPage();        //表示最后一页的页码
            $data['page']['total'] = $list_data->total();               //总数据个数
            $data['page']['current_number'] = $show_count;        //一页显示多少个
        }
        return $data;
    }

    // 获取会员卡
    public static function getVip($request,$type,$show_count=10) {
        $list_data['vip_data'] = DB::table('vip_card')
            ->where('vica_shop_id', $request['shop_id'])//是否长期1是2否
            ->where('vica_state', 1)//是否长期1是2否
            ->where('vica_long_term', 2)
            ->select('vica_id', 'vica_name', 'vica_price', 'vica_effective_date', 'vica_sepr_name', 'vica_num', 'vica_shop_price', 'vica_long_term', 'vica_shop_id')
            ->get()->toArray();
        foreach ($list_data['vip_data'] as $key => $value) {
            $list_data['vip_data'][$key]->detail = DB::table('vip_card_detail')
                ->where('vicad_vcid', $value->vica_id)
                ->get()->toArray();
        }
        $list_data['long_vip'] = DB::table('vip_card')
            ->where('vica_shop_id', $request['shop_id'])//是否长期1是2否
            ->where('vica_state', 1)
            ->where('vica_long_term', 1)
            ->select('vica_id', 'vica_name', 'vica_price', 'vica_effective_date', 'vica_sepr_name', 'vica_num', 'vica_shop_price', 'vica_long_term', 'vica_shop_id')
            ->get()->toArray();
        foreach ($list_data['long_vip'] as $key => $value) {
            $list_data['long_vip'][$key]->detail = DB::table('vip_card_detail')
                ->where('vicad_vcid', $value->vica_id)
                ->get()->toArray();
        }
        return $list_data;
    }

    // 首页获取推荐商品
    public static function getRecommendGoods($request,$type,$show_count=10)
    {
        $list_data = DB::table('package_items')
            ->where('pait_shop_id', $request['shop_id'])
            ->where('pait_state', 1)
            ->where('pait_recommend_state', 2)//推荐状态：1不推荐2推荐
            ->where(function ($query) use ($request) {
                if (!empty($request['keywords'])) {
                    $query->where('pait_name', 'like', '%' . $request['keywords'] . '%')
                        ->orwhere('pait_number', 'like', '%' . $request['keywords'] . '%');
                }
            }) //关键词搜索
            ->select('pait_id', 'pait_name', 'pait_shop_price', 'pait_sell_price', 'pait_pic', 'pait_number', 'pait_type')
            ->orderBy('pait_sort', 'desc');
        $list_data1 = $list_data->get();
        if ($type == 1) {
            $list_data = $list_data->get()->toArray();
        } else {
            $list_data = $list_data->paginate($show_count);
        }
        $vip_data = [];

        foreach ($list_data1 as $key => $value) {
            $correlation_goods = DB::table('correlation_goods as cogo')
                ->leftJoin('service_project as sepr', 'sepr.sepr_id', '=', 'cogo.cogo_goo_id')
                ->where('cogo_pait_id', $value->pait_id)
                ->select('sepr_id', 'sepr_work_type', 'cogo_goo_type')
                ->get()->toArray();
            if(count($correlation_goods) != 1) {
                continue;
            }
            if ($correlation_goods) {
                foreach ($correlation_goods as $key1 => $value1) {
                    if ($value1->sepr_work_type !=2 || $value1->cogo_goo_type !=2) {
                        continue;
                    }
                    $find_vip_data = DB::table('vip_card')
                        ->where('vica_state', 1)
                        ->where('vica_sepr_id', $value1->sepr_id)
                        ->select('vica_id', 'vica_name', 'vica_price', 'vica_effective_date', 'vica_sepr_name', 'vica_num', 'vica_shop_price', 'vica_long_term')
                        ->get()->toArray();
                    if ($find_vip_data) {
                        foreach ($find_vip_data as $key2 => $value2) {
                            $vip_data[] = $value2;
                        }
                    }
                }
            }
        }
        foreach ($list_data as $key1 => $value1) {
            $list_data[$key1]->pait_evaluate_num = DB::table('evaluate_goods')
                ->where('evgo_goo_id', $value1->pait_id)
                ->where('evgo_goo_type', 3)
                ->count();
            if ($list_data[$key1]->pait_evaluate_num > 10000) {
                $list_data[$key1]->pait_evaluate_num = '1万+';
            }
            if ($value1->pait_pic) {
                $pait_pic = json_decode($value1->pait_pic, true);
                $list_data[$key1]->pait_pic_first = $pait_pic[0];
            } else {
                $list_data[$key1]->pait_pic_first = '';
            }
            unset($list_data[$key1]->pait_pic);
        }
        $vip_id = [];
        $new_vip_data = [];
        if (!empty($vip_data)) {
            foreach ($vip_data as $key => $value) {
                if (!in_array($value->vica_id,$vip_id)) {
                    $vip_id[] = $value->vica_id;
                    $new_vip_data[] = $value;
                }
            }
        }
        if ($type == 1) {
            // $data['list_data'] = array_slice($list_data, 0, 4);
            $data['list_data'] = $list_data;
            $data['vip_data'] = $new_vip_data;
        } else {
            $data['list_data'] = $list_data->items();
            $data['vip_data'] = $new_vip_data;
            $data['page']['current_page'] = $list_data->currentPage();  //当前页面页码
            $data['page']['last_page'] = $list_data->lastPage();        //表示最后一页的页码
            $data['page']['total'] = $list_data->total();               //总数据个数
            $data['page']['current_number'] = $show_count;        //一页显示多少个
        }
        return $data;
    }

    // 获取公司信息
    public static function companyProfile($request)
    {
        $find_data = DB::table('shop_info')
            ->where('shin_shop_id', $request['shop_id'])
            ->value('shin_company_profile');
        if ($find_data) {
            $find_data = json_decode($find_data, true);
        }
        return $find_data;
    }

    // 首页获取案例
    public static function getOrderWork($request,$type,$show_count=10)
    {
        $list_data1 = DB::table('order_works')
            ->where('orwo_shop_id', $request['shop_id'])
            ->where('orwo_delete', 2)
            ->select('orwo_id', 'orwo_title', 'orwo_create_time', 'orwo_type', 'orwo_cover')
            ->orderBy('orwo_create_time', 'desc');
        if ($type == 1) {
            $list_data = $list_data1->limit(4)->get()->toArray();
        } else {
            $list_data2 = $list_data1->paginate($show_count);
            $list_data['data'] = $list_data2->items();
            $list_data['page']['current_page'] = $list_data2->currentPage();  //当前页面页码
            $list_data['page']['last_page'] = $list_data2->lastPage();        //表示最后一页的页码
            $list_data['page']['total'] = $list_data2->total();               //总数据个数
            $list_data['page']['current_number'] = $show_count;        //一页显示多少个
        }

        return $list_data;
    }

    // 商品详情
    public static function goodsInfo($request,$user_info = NULL)
    {
        $list_data = DB::table('package_items')
            ->where('pait_id', $request['pait_id'])
            ->select('pait_id', 'pait_name', 'pait_shop_price', 'pait_sell_price', 'pait_pic', 'pait_detail', 'pait_state', 'pait_ware_id', 'pait_type', 'pait_number','pait_pay_type','pait_appoint_num')
            ->first();
        if ($list_data) {
            $edit_data['pait_type'] = 3;
            if (!empty($list_data->pait_pic)) {//封面图
                $pait_pic = json_decode($list_data->pait_pic, true);
                foreach ($pait_pic as $key => $value) {
                    $new_pait_pic[] = self::getImage($value);
                }
                $list_data->pait_pic = json_encode($new_pait_pic, true);
            }
            if (!empty($list_data->pait_detail)) {//详情图片
                $pait_detail = json_decode($list_data->pait_detail, true);
                $new_pait_detail = [];
                foreach ($pait_detail as $key_p => $value_p) {
                    if ($value_p['type'] == 2) {
                        $content = $value_p['content'];
                        if (!empty($content)) {
                            foreach ($content as $key => $value) {
                                $new_content[] = self::getImage($value);
                            }
                        } else {
                            $new_content = $content;
                        }
                        $data['content'] = $new_content;
                        $data['type'] = $value_p['type'];
                        $data['fileList'] = isset($value_p['fileList']) ? $value_p['fileList'] : '';
                        $new_pait_detail[] = $data;
                    } else {
                        $new_pait_detail[] = $value_p;
                    }
                }
                $list_data->pait_detail = json_encode($new_pait_detail, true);
            }
            //如果是会员，返回会员价格
            $meml_discount = 0;
            $list_data->is_mem_price = 2;//是否是会员价格：1是2否
            if(isset($user_info->ussh_user_id)){
                $level = DB::table('member')
                    ->where('mem_shop_id',$user_info->adm_shop_id)
                    ->where('mem_id', $user_info->ussh_user_id)
                    ->value('mem_level');
                if(isset($level) && $level > 0){
                    $meml_discount = DB::table('member_level')
                        ->where('meml_shop_id', $user_info->adm_shop_id)
                        ->where('meml_level', $level)
                        ->value('meml_discount');
                }
            }
            if($meml_discount > 0){
                $list_data->pait_sell_price =  $list_data->pait_sell_price * $meml_discount / 10;
                $list_data->is_mem_price = 1;//是否是会员价格：1是2否
            }
            $goods_data1 = DB::table('correlation_goods as cogo')
                ->leftJoin('goods as g', 'g.goo_id', '=', 'cogo.cogo_goo_id')
                ->where('cogo_pait_id', $list_data->pait_id)
                ->where('cogo_goo_type', 1)
                ->select('goo_name', 'goo_pic', 'goo_id', 'cogo_goo_unit', 'cogo_goo_quantity', 'cogo_goo_type')
                ->get()->toArray();
            $goods_data2 = DB::table('correlation_goods as cogo')
                ->leftJoin('service_project as sepr', 'sepr.sepr_id', '=', 'cogo.cogo_goo_id')
                ->where('cogo_pait_id', $list_data->pait_id)
                ->where('cogo_goo_type', 2)
                ->select('sepr_name as goo_name', 'sepr_img as goo_pic', 'sepr_work_type', 'sepr_id as goo_id', 'cogo_goo_type', 'cogo_goo_unit', 'cogo_goo_quantity')
                ->get()->toArray();

            if ($goods_data2) {
                foreach ($goods_data2 as $key => $value) {
                    if ($value->sepr_work_type == 1) {//生成工单
                        $edit_data['pait_type'] = 1;//商品类型1包含生成工单2只包含不生成工单服务3只包含商品
                        break;
                    }
                    if ($value->sepr_work_type == 2) {//生成工单
                        $edit_data['pait_type'] = 2;//商品类型1包含生成工单2只包含不生成工单服务3只包含商品
                    }
                }
                foreach ($goods_data2 as $key1 => $value1) {
                    if ($value1->goo_pic) {
                        $goo_pic4 =  substr($value1->goo_pic, 0, 4);
                        if ($goo_pic4 != 'http') {
                            $goods_data2[$key1]->goo_pic = config('apisystem.server_name').'/'.$value1->goo_pic;
                        }
                        $data_url1 = substr($goods_data2[$key1]->goo_pic, 0, -19);
                        $data_url2 = substr($goods_data2[$key1]->goo_pic, -19);
                        if (file_exists($data_url1 . 'original' .$data_url2)) {
                            $new_pait_pic[] = $data_url1 . 'original' .$data_url2;
                        } else {
                            $new_pait_pic[] = $value;
                        }
                    }
                }
            }
            if ($edit_data['pait_type'] != $list_data->pait_type) {
                $edit_data['pait_update_time'] = date('Y-m-d H:i:s');
                $update_res = DB::table('package_items')
                    ->where('pait_id', $request['pait_id'])
                    ->update($edit_data);
            }
            $list_data->pait_type = $edit_data['pait_type'];
            $goods_data = array_merge($goods_data1,$goods_data2);
            $list_data->goods_data = $goods_data;
            $copa_cpait_id = DB::table('correlation_package')
                ->where('copa_pait_id', $request['pait_id'])
                ->select('copa_cpait_id')
                ->orderBy('copa_id', 'desc')
                ->get()->toArray();
            $copa_pait_id = DB::table('correlation_package')
                ->where('copa_cpait_id', $request['pait_id'])
                ->select('copa_pait_id')
                ->orderBy('copa_id', 'desc')
                ->get()->toArray();
            $correlation_package = [];
            foreach ($copa_cpait_id as $key => $value) {
                $searchdata = DB::table('package_items')
                    ->where('pait_id', $value->copa_cpait_id)
                    ->select('pait_id', 'pait_name', 'pait_shop_price', 'pait_pic', 'pait_sell_price')
                    ->first();
                $pait_pic = json_decode($searchdata->pait_pic,true);
                if (!empty($pait_pic)) {
                    $searchdata->pait_pic = $pait_pic[0];
                } else {
                    $searchdata->pait_pic = '';
                }
                $correlation_package[] = $searchdata;
            }
            foreach ($copa_pait_id as $key => $value) {
                $searchdata = DB::table('package_items')
                    ->where('pait_id', $value->copa_pait_id)
                    ->select('pait_id', 'pait_name', 'pait_shop_price', 'pait_pic', 'pait_sell_price')
                    ->first();
                $pait_pic = json_decode($searchdata->pait_pic,true);
                if (!empty($pait_pic)) {
                    $searchdata->pait_pic = $pait_pic[0];
                } else {
                    $searchdata->pait_pic = '';
                }
                $correlation_package[] = $searchdata;
            }
            $list_data->correlation_package = $correlation_package;
        }
        
        return $list_data;
    }

    // 获取图片的原图路径
    public static function getImage($imgpath, $shop_id = 0)
    {
        // 最后一个/的位置
        $last_number = strrpos($imgpath, '/');
        // 图片名
        $image_name = substr($imgpath, $last_number+1);
        // 图片所在文件夹路径
        $file_path = substr($imgpath, 0,$last_number+1);
        // 分割图片名称前面的文件夹路径
        $part_path = explode('storage', $file_path);
        // 拼接服务器上的原图路径
        $new_url = storage_path().'/app/public'.$part_path[1].'original' .$image_name;
        // 判断原图是否存在
        if (file_exists($new_url)) {
            $new_pait_pic = $file_path . 'original' .$image_name;
        } else {
            $new_pait_pic = $imgpath;
        }
        return $new_pait_pic;
    }

    // 商品案例-订单作品
    public static function goodsOrderWork($request)
    {
        $order_work = DB::table('order_works as o')
                ->leftJoin('order_goods as orgo', 'orgo.orgo_ord_id', '=', 'o.orwo_ord_id')
                ->where('orgo_goo_type', 3)
                ->where('orwo_delete', 2)
                ->where('orwo_shop_id', $request['shop_id'])
                ->where('orgo_goo_id', $request['pait_id'])
                ->select('orwo_id', 'orwo_title', 'orwo_create_time', 'orwo_type', 'orwo_cover')
                ->orderBy('orwo_create_time', 'desc')
                ->paginate(4);
        $data = $order_work->items();
        return $data;
    }

    // 会员卡详情
    public static function vipCardInfo($request)
    {
        $vip_card = DB::table('vip_card')
            ->where('vica_id', $request['vica_id'])
            ->select('vica_state', 'vica_id', 'vica_name', 'vica_sepr_name', 'vica_num', 'vica_price', 'vica_effective_date', 'vica_instructions', 'vica_create_time', 'vica_long_term', 'vica_shop_price')
            ->first();
        $detail = DB::table('vip_card_detail')
            ->where('vicad_vcid', $vip_card->vica_id)
            ->get()->toArray();
        if (!empty($detail)) {
            foreach ($detail as $k => $v) {
                if ($v->vicad_type == 1) {
                    $goo_unit = DB::table('goods')
                        ->where('goo_id', $v->vicad_data_id)
                        ->value('goo_unit');
                } else {
                    $goo_unit = '';
                }
                if ($goo_unit) {
                    $detail[$k]->vicad_data_name = $v->vicad_data_name.'('.$goo_unit.')';
                }
            }
        }
        $vip_card->detail = $detail;
        return $vip_card;
    }

    // 数据验证
    public static function dataValidation($request)
    {
        if ($request['name'] == 1) {
            $find_data = DB::table('vip_card')
                ->where('vica_id', $request['id'])
                ->select('vica_state')
                ->first();
            if ($find_data->vica_state == 2) {
                return ['code'=>2001, 'msg'=>'会员卡已售罄', 'data'=>''];
            } else {
                return ['code'=>200, 'msg'=>'会员卡正常', 'data'=>''];
            }
        }

        if ($request['name'] == 2) {
            $find_data = DB::table('package_items')
                ->where('pait_id', $request['id'])
                ->select('pait_state')
                ->first();
            if ($find_data->pait_state == 2) {
                return ['code'=>2001, 'msg'=>'商品已售罄', 'data'=>''];
            } else {
                return ['code'=>200, 'msg'=>'商品正常', 'data'=>''];
            }
        }
        return ['code'=>2001, 'msg'=>'请上传验证数据', 'data'=>''];
    }

    /**
     * 积分设置-积分商品
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-09-19
     * @param  [type]           $data [description]
     * @return [type]                 [description]
     */
    public static function index($user_info,$request,$show_count)
    {
        $list_data = DB::table('point_gift_goods')
            ->where('pogg_shop_id', $user_info->adm_shop_id)
            ->where('pogg_state', 1)
            ->where(function ($query) use ($request) {
                $query->whereRaw("pogg_limited_time = 1 and pogg_start_time <= '".date('Y-m-d')."' and pogg_end_time >= '".date('Y-m-d')."'")
                    ->orWhereRaw("pogg_limited_time = 2");
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['keywords'])) {
                    $query->where('pogg_goo_name', 'like', '%' . $request['keywords'] . '%');
                }
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['pogg_goo_type'])) {
                    $query->where('pogg_goo_type', $request['pogg_goo_type']);
                }
            })
            ->select('pogg_id', 'pogg_goo_id', 'pogg_goo_name', 'pogg_goo_price', 'pogg_goo_num', 'pogg_goo_limitation', 'pogg_goo_point', 'pogg_goo_money', 'pogg_limited_time', 'pogg_start_time', 'pogg_end_time', 'pogg_goo_type', 'pogg_goo_type_name','pogg_pic')
            ->orderBy('pogg_id', 'desc')
            ->paginate($show_count);
        $list_items = $list_data->items();
        if ($list_items) {
            foreach ($list_items as $key => $value) {
                if ($value->pogg_goo_type == 1) {
                    $list_items[$key]->image = DB::table('service_project')
                        ->where('sepr_id', $value->pogg_goo_id)
                        ->value('sepr_img');
                }
                if ($value->pogg_goo_type == 2) {
                    $list_items[$key]->image = DB::table('goods')
                        ->where('goo_id', $value->pogg_goo_id)
                        ->value('goo_pic');
                    if (empty($list_items[$key]->image)) {
                       $list_items[$key]->image = config('apisystem.server_name_https').'/storage/image/default_goo_img.png';
                    }

                }
                if ($value->pogg_goo_type == 3) {
                    $list_items[$key]->image = '';
                }
                if($value->pogg_pic && !empty($value->pogg_pic)){
                    $pogg_pic = json_decode($value->pogg_pic,true);
                    if(isset($pogg_pic[0])){
                        $list_items[$key]->image = $pogg_pic[0];
                    }
                }
            }
        }
        $data['pages']['current_page'] = $list_data->currentPage();  //当前页面页码
        $data['pages']['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data['pages']['total'] = $list_data->total();               //总数据个数
        $data['pages']['current_number'] = $show_count;        //一页显示多少个
        $data['list'] = $list_items;                        //返回数据
        return $data;
    }

    /**
     * 积分设置-积分商品
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-09-19
     * @param  [type]           $data [description]
     * @return [type]                 [description]
     */
    public static function pointGoodsInfo($user_info,$request,$show_count)
    {
        $list_data = DB::table('point_gift_goods')
            ->where('pogg_id', $request['pogg_id'])
            ->select('pogg_id', 'pogg_goo_id', 'pogg_goo_name', 'pogg_goo_price', 'pogg_goo_num', 'pogg_goo_limitation', 'pogg_goo_point', 'pogg_goo_money', 'pogg_limited_time', 'pogg_start_time', 'pogg_end_time', 'pogg_goo_type', 'pogg_goo_type_name', 'pogg_exchange_person', 'pogg_exchange_day','pogg_detail_pic','pogg_pic')
            ->first();
        if ($list_data->pogg_goo_type == 1) {
            $list_data->image = DB::table('service_project')
                ->where('sepr_id', $list_data->pogg_goo_id)
                ->value('sepr_img');
        }
        if ($list_data->pogg_goo_type == 2) {
            $list_data->image = DB::table('goods')
                ->where('goo_id', $list_data->pogg_goo_id)
                ->value('goo_pic');
            if (empty($list_data->image)) {
               $list_data->image = config('apisystem.server_name_https').'/storage/image/default_goo_img.png';
            }
            if($list_data->pogg_pic){
                $pogg_pic = json_decode($list_data->pogg_pic,true);
                if(isset($pogg_pic[0])){
                    $list_data->image = $pogg_pic[0] ;
                }
            }
            $list_data->detail = '';
            if($list_data->pogg_detail_pic){
                $list_data->detail = config('apisystem.server_name_https').$list_data->pogg_detail_pic;
            }
        }
        if ($list_data->pogg_goo_type == 3) {
            $list_data->image = '';
        }
        return $list_data;
    }
    /**
     * 获取可预约数量
     * @authors dou
     * @date   2023-09-26
     * @param  [type]           $data [description]
     * @return [type]                 [description]
     */
    public static function getAppointNum($user_info,$request)
    {
        $user_info = CommonService::dataToArray($user_info);
        $pait_appoint_num = DB::table('package_items')->where('pait_id',$request['pait_id'])->value('pait_appoint_num');
        $time = $request['day_time'];
        $time1 = date('Y-m-d', strtotime('+1 day',strtotime($time)));
        $data = DB::table('order_client as a')
            ->leftJoin('order as b', 'a.orcl_ord_id' , '=' , 'b.ord_id')
            ->leftJoin('order_goods as c', 'a.orcl_ord_id' , '=' , 'c.orgo_ord_id')
            ->where('orgo_goo_type',3)
            ->where('orgo_goo_id',$request['pait_id'])
            ->whereBetween('orcl_appoint_time', [$time,$time1])
            ->where("ord_delete",1)
            ->where("ord_shop_id",$user_info['adm_shop_id'])
            ->select('orcl_appoint_time')->get();
        $appoint_num = [];
        if($data){
            $data = CommonService::dataToArray($data);
            foreach($data as $k => $v){
                $H = explode(':',explode(' ', $v['orcl_appoint_time'])[1])[0];
                if(isset($appoint_num[$H])){
                    $appoint_num[$H] = $appoint_num[$H]+1;
                }else{
                    $appoint_num[$H] = 1;
                }
            }
        }
        $return = [];
        $k = 0;
        for($i=8;$i<=20;$i++){
            if($i<10){
                $num = '0'.$i;
            }else{
                $num = $i;
            }
            $return[$k]['hour'] = $num.":00";
            $return[$k]['num'] = $appoint_num[$num]??0;
            if($pait_appoint_num == 0){
                $return[$k]['type'] = true;
            }else{
                if($return[$k]['num']< $pait_appoint_num){
                    $return[$k]['type'] = true;
                }else{
                    $return[$k]['type'] = false;
                }
            }
            $k++;
        }
        return $return;
    }
}
