<?php

namespace App\Services\Shop;

use Illuminate\Database\Eloquent\Model;
use App\Models\Shop\Goods;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Validators\Shop\GoodsValidator;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Support\Facades\Request;
use App\Models\Common;
use App\Services\Business\WashOrderService;

class GoodsService extends Service
{
    public static $instance;
    public $modelMain = null;
    public $mainValidator = null;

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

    /**
     * @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($user_info, $search_data, $show_count = 10)
    {
        // 商品列表
        $list_data = DB::table('package_items as p')
            ->leftJoin('goods_classification as g', 'g.gocl_id', '=', 'p.pait_classify_id')
            ->where('pait_cid', $user_info->adm_cid)
            ->where('pait_shop_id', $user_info->adm_shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['pait_number'])) {
                    $query->where('pait_number', 'like', '%' . $search_data['pait_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['pait_name'])) {
                    $query->where('pait_name', 'like', '%' . $search_data['pait_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['pait_state'])) {
                    $query->where('pait_state', $search_data['pait_state']);
                }
                if (!empty($search_data['pait_classify_id'])) {
                    $query->where('pait_classify_id', $search_data['pait_classify_id']);
                }
                if (!empty($search_data['pait_recommend_state'])) {
                    $query->where('pait_recommend_state', $search_data['pait_recommend_state']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['pait_composition'])) {
                    $query->where('pait_composition', 'like', '%' . $search_data['pait_composition'] . '%');
                }
            })
            ->select('pait_id', 'pait_number', 'pait_name', 'pait_classify_id', 'gocl_name', 'pait_composition', 'pait_saleable_quantity', 'pait_sell_number', 'pait_shop_price', 'pait_sell_price', 'pait_state', 'pait_sort', 'pait_create_time', 'pait_recommend_state','pait_pay_type','pait_appoint_num')
            ->orderBy('pait_sort', 'desc')
            ->orderBy('pait_create_time', 'desc')
            ->paginate($show_count);
        $list_items = $list_data->items();
        if ($list_items) {
            $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;
        } else {
            return [];
        }
    }

    // 商品详情
    public static function info($user_info, $request)
    {
        $list_data = DB::table('package_items as p')
            ->leftJoin('goods_classification as gocl', 'gocl.gocl_id', '=', 'p.pait_classify_id')
            ->leftJoin('warehouse as w', 'w.ware_id', '=', 'p.pait_ware_id')
            ->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_classify_id', 'gocl_name', 'pait_sort', 'pait_saleable_quantity', 'pait_sell_number', 'pait_create_adm_id', 'pait_update_adm_id', 'pait_create_time', 'pait_update_time', 'pait_number', 'ware_name', 'pait_recommend_state','pait_pay_type','pait_appoint_num')
            ->first();

        if ($list_data) {
            if ($list_data->pait_create_adm_id) {
                $list_data->pait_create_adm_name = DB::table('admin')
                    ->where('adm_id', $list_data->pait_create_adm_id)
                    ->value('adm_name');
            } else {
                $list_data->pait_create_adm_name = '';
            }
            if ($list_data->pait_update_adm_id) {
                $list_data->pait_update_adm_name = DB::table('admin')
                    ->where('adm_id', $list_data->pait_update_adm_id)
                    ->value('adm_name');
            } else {
                $list_data->pait_update_adm_name = '';
            }

            $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_id', 'goo_name', 'cogo_goo_quantity as goo_quantity', 'cogo_goo_unta_id as goo_unta_id', 'cogo_goo_type', 'cogo_goo_price as goo_price', 'cogo_goo_unit as goo_unit', 'cogo_wago_id as wago_id', 'goo_level', 'goo_fid')
                ->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_id as goo_id', 'sepr_name as goo_name', 'cogo_goo_quantity as goo_quantity', 'cogo_goo_unta_id as goo_unta_id', 'cogo_goo_type', 'cogo_goo_price as goo_price', 'cogo_goo_unit as goo_unit', 'sepr_work_type', 'cogo_wago_id as wago_id')
                ->get()->toArray();
            foreach ($goods_data1 as $key => $value) {
                if ($value->goo_level == 1 || ($value->goo_level == 2 && !empty($value->goo_fid))) {
                    $goods_data1[$key]->goo_change = 1;
                } else {
                    $goods_data1[$key]->goo_change = 2;
                }
            }
            $goods_data = array_merge($goods_data1, $goods_data2);
            $list_data->goods_data = $goods_data;
        }
        return $list_data;
    }

    // 分类列表
    public static function classificationIndex($user_info, $search_data, $show_count = 10, $field_columns = [])
    {
        // 判断是否传入查询字段
        if (empty($field_columns)) {
            // 查询字段
            $field_columns = ['gocl_id', 'gocl_name', 'gocl_sort', 'gocl_remark', 'gocl_state'];
        }
        // 商品分类列表
        $list_data = DB::table('goods_classification')
            ->where('gocl_cid', $user_info->adm_cid)
            ->where('gocl_shop_id', $user_info->adm_shop_id)
            ->where('gocl_is_del', 2)
            ->select($field_columns)
            ->orderBy('gocl_sort', 'asc')
            ->paginate($show_count);
        $list_items = $list_data->items();
        if ($list_items) {
            $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;                        //返回数据
            return ['code' => 200, 'msg' => 'success', 'data' => $data];
        } else {
            return ['code' => 4000, 'msg' => '暂无数据', 'data' => ''];
        }
    }

    // 获取分类
    public static function getClassification($user_info, $search_data)
    {
        // 我的会员卡管理表
        $list_data = DB::table('goods_classification')
            ->where('gocl_cid', $user_info->adm_cid)
            ->where('gocl_shop_id', $user_info->adm_shop_id)
            ->where('gocl_state', 1)
            ->where('gocl_is_del', 2)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['keywords'])) {
                    $query->where('gocl_name', 'like', '%' . $search_data['keywords'] . '%');
                }
            })
            ->select('gocl_id', 'gocl_name', 'gocl_state')
            ->orderBy('gocl_sort', 'asc')
            ->get()->toArray();
        if ($list_data) {
            return ['code' => 200, 'msg' => 'success', 'data' => $list_data];
        } else {
            return ['code' => 4001, 'msg' => '暂无数据', 'data' => ''];
        }
    }

    // 我的会员卡详情
    public static function myVipInfo($user_info, $request)
    {
        $info = DB::table('myvip')
            ->where('myvi_adm_id', $request['adm_id'])
            ->where('myvi_id', $request['myvi_id'])
            ->select('myvi_id', 'myvi_adm_id', 'myvi_num', 'myvi_create_adm_id', 'myvi_create_time', 'myvi_surplus_times', 'myvi_all_times', 'myvi_effective_date', 'myvi_state', 'myvi_carnum', 'myvi_name', 'myvi_sepr_id', 'myvi_sepr_name', 'myvi_long_term', 'myvi_vica_id', 'myvi_explain', 'myvi_end_time')
            ->first();
        if ($info->myvi_end_time != '0000-00-00 00:00:00') {
            $info->myvi_end_time = date('Y-m-d', strtotime($info->myvi_end_time));
        } else {
            $info = '';
        }
        return $info;
    }

    /**
     * 检查是不是存在同名内容
     * @param $name 考核项名称
     * @param $type 类型：1施工部位2整车3其他
     * @param int $id 排除这个id
     * @return mixed
     */
    public static function nameExists($user_info, $request, $id = 0)
    {
        if ($id == 0) {
            return DB::table('goods_classification')
                ->where('gocl_name', $request['gocl_name'])
                ->where('gocl_shop_id', $user_info->adm_shop_id)
                ->where('gocl_state', 1)
                ->where('gocl_is_del', 2)
                ->exists();
        } else {
            return DB::table('goods_classification')
                ->where('gocl_name', $request['gocl_name'])
                ->where('gocl_shop_id', $user_info->adm_shop_id)
                ->where('gocl_state', 1)
                ->where('gocl_is_del', 2)
                ->where('gocl_id', '<>', $id)
                ->exists();
        }
    }

    /**
     * 检查是不是存在同名内容
     * @param $name 考核项名称
     * @param $type 类型：1施工部位2整车3其他
     * @param int $id 排除这个id
     * @return mixed
     */
    public static function goodsnameExists($user_info, $request, $id = 0)
    {
        if ($id == 0) {
            return DB::table('package_items')
                ->where('pait_name', $request['pait_name'])
                ->where('pait_shop_id', $user_info->adm_shop_id)
                ->where('pait_state', 1)
                ->exists();
        } else {
            return DB::table('package_items')
                ->where('pait_name', $request['pait_name'])
                ->where('pait_shop_id', $user_info->adm_shop_id)
                ->where('pait_state', 1)
                ->where('pait_id', '<>', $id)
                ->exists();
        }
    }

    // 新增
    public static function add($user_info, $request)
    {
        $data['pait_cid'] = $user_info->adm_cid;
        $data['pait_shop_id'] = $user_info->adm_shop_id;
        $data['pait_name'] = $request['pait_name']; //商品名称
        $pait_number = 'SP' . time() . rand(10000, 99999);
        $data['pait_number'] = $pait_number; //商品编号
        $goods_data = json_decode($request['goods_data'], true);
        if (empty($goods_data)) {
            return ['code' => 500, 'msg' => '请选择商品', 'data' => '新增失败'];
        }
        $goods = '';
        foreach ($goods_data as $key => $value) {
            if (empty($goods)) {
                if ($value['goo_unta_id'] == 1) {
                    $goods = $value['goo_name'] . '*' . $value['goo_quantity'] . $value['goo_unit'] . '(' . $value['goo_quantity'] * $value['goo_unit_conversion'] . '米)';
                } else {
                    $goods = $value['goo_name'] . '*' . $value['goo_quantity'] . $value['goo_unit'];
                }
            } else {
                if ($value['goo_unta_id'] == 1) {
                    $goods = $goods . '、' . $value['goo_name'] . '*' . $value['goo_quantity'] . $value['goo_unit'] . '(' . $value['goo_quantity'] * $value['goo_unit_conversion'] . '米)';
                } else {
                    $goods = $goods . '、' . $value['goo_name'] . '*' . $value['goo_quantity'] . $value['goo_unit'];
                }
            }
        }
        $data['pait_type'] = 3; //商品类型1包含生成工单2只包含不生成工单服务3只包含商品
        foreach ($goods_data as $key1 => $value1) {
            if ($value1['goo_type'] == 2) {
                $data['pait_type'] = 2;
                if ($value1['sepr_work_type'] == 1) {
                    $data['pait_type'] = 1;
                    break;
                }
            }
        }
        $data['pait_composition'] = $goods; //组成
        $data['pait_classify_id'] = $request['pait_classify_id']; //分类id
        $data['pait_sort'] = $request['pait_sort']; //排序
        $data['pait_saleable_quantity'] = $request['pait_saleable_quantity']; //可售数量
        $data['pait_ware_id'] = $request['pait_ware_id'] ? $request['pait_ware_id'] : 0; //仓库id
        $data['pait_recommend_state'] = isset($request['pait_recommend_state']) ? $request['pait_recommend_state'] : 1; //推荐状态：1不推荐2推荐
        $data['pait_pic'] = $request['pait_pic']; //封面
        $data['pait_detail'] = $request['pait_detail']; //详情
        if ($request['pait_sell_price'] <= 0) {
            return ['code' => 500, 'msg' => '销售价需要大于0', 'data' => '销售价需要大于0'];
        }
        if ($request['pait_shop_price'] < $request['pait_sell_price']) {
            return ['code' => 500, 'msg' => '门市价不能小于零售价', 'data' => '门市价不能小于零售价'];
        }
        $data['pait_shop_price'] = $request['pait_shop_price'] * 100; //门店价格
        $data['pait_sell_price'] = $request['pait_sell_price'] * 100; //零售价
        $data['pait_create_adm_id'] = $user_info->adm_id;
        $data['pait_create_time'] = date('Y-m-d H:i:s');
        $data['pait_update_adm_id'] = $user_info->adm_id;
        $data['pait_pay_type'] = $request['pait_pay_type']??2;
        $data['pait_appoint_num'] = $request['pait_appoint_num']??0;
        $data['pait_update_time'] = date('Y-m-d H:i:s');
        $pait_id = DB::table('package_items')->insertGetId($data);
        foreach ($goods_data as $key => $value) {
            $add_data[$key]['cogo_pait_id'] = $pait_id;
            $add_data[$key]['cogo_goo_id'] = $value['goo_id'];
            $add_data[$key]['cogo_goo_quantity'] = $value['goo_quantity'];
            $add_data[$key]['cogo_goo_unta_id'] = $value['goo_unta_id'];
            $add_data[$key]['cogo_goo_unit'] = $value['goo_unit'];
            $add_data[$key]['cogo_goo_type'] = $value['goo_type'];
            $add_data[$key]['cogo_goo_price'] = $value['goo_price'] * 100;
            $add_data[$key]['cogo_wago_id'] = $value['wago_id'];
            $add_data[$key]['cogo_create_time'] = date('Y-m-d H:i:s');
        }
        $cogo_res = DB::table('correlation_goods')->insert($add_data);
        if ($cogo_res && $pait_id) {
            return ['code' => 200, 'msg' => '新增成功', 'data' => $pait_id];
        } else {
            return ['code' => 500, 'msg' => '新增失败', 'data' => '新增失败'];
        }
    }

    // 新增分类
    public static function addClassification($user_info, $request)
    {
        $data['gocl_cid'] = $user_info->adm_cid; //公司id
        $data['gocl_shop_id'] = $user_info->adm_shop_id; //门店id
        $data['gocl_name'] = $request['gocl_name']; //分类名称
        $data['gocl_sort'] = $request['gocl_sort']; //排序
        $data['gocl_remark'] = !empty($request['gocl_remark']) ? $request['gocl_remark'] : ''; //备注
        $data['gocl_state'] = $request['gocl_state']; //1开启2关闭
        $data['gocl_create_time'] = date('Y-m-d H:i:s');
        $data['gocl_update_time'] = date('Y-m-d H:i:s');
        return DB::table('goods_classification')->insert($data);
    }

    // 编辑分类
    public static function editClassification($user_info, $request)
    {
        $data['gocl_cid'] = $user_info->adm_cid; //公司id
        $data['gocl_shop_id'] = $user_info->adm_shop_id; //门店id
        $data['gocl_name'] = $request['gocl_name']; //分类名称
        $data['gocl_sort'] = $request['gocl_sort']; //排序
        $data['gocl_remark'] = !empty($request['gocl_remark']) ? $request['gocl_remark'] : ''; //备注
        $data['gocl_state'] = $request['gocl_state']; //1开启2关闭
        $data['gocl_create_time'] = date('Y-m-d H:i:s');
        $data['gocl_update_time'] = date('Y-m-d H:i:s');
        return DB::table('goods_classification')->where('gocl_id', $request['gocl_id'])->update($data);
    }

    // 新增-添加会员卡订单
    public static function addOrder($user_info, $request, $type = 1)
    {
        // 获取唯一字符串标识
        $ord_unique_string = md5(md5($user_info->adm_id . $user_info->adm_shop_id . date('Y-m-d H:i:s') . rand(10000, 99999)) . rand(10000, 99999));
        $ord_order_number = Common::numberRule($user_info, 1);
        $data['ord_is_split'] = 1;
        $data['ord_cid'] = $user_info->adm_cid;
        $data['ord_superior_shop_id'] = $user_info->adm_shop_id;
        $data['ord_shop_id'] = $user_info->adm_shop_id;
        $data['ord_create_id'] = $user_info->adm_id;
        $data['ord_client_id'] = $request['ord_client_id'];
        $data['ord_address'] = Db::table('shop')->where('shop_id', $user_info->adm_shop_id)->value('shop_store_name');
        $data['ord_address_id'] = $user_info->adm_shop_id;
        $data['ord_address_type'] = 1;
        $data['ord_order_number'] = $ord_order_number;
        $data['ord_type'] = 1; //买家类型：1门店零售2企业客户
        $data['ord_service_type'] = 3; //订单类型：1服务单 2洗车单3商品单
        $data['ord_classify'] = 2; //订单分类：1蓄电池2洗美店3易损件
        $data['ord_payment_way'] = 1; //结算方式1账期2现结
        $data['ord_state'] = 2; //结算状态1未结算2已结算
        $data['ord_wor_state'] = 4; //4已完成
        $data['ord_order_price'] = $request['vica_price']; //订单金额（前端传过来的金额单位是分，这里不*100）
        $data['ord_actual_price'] = $request['vica_price']; //订单金额
        $data['ord_update_time'] = date('Y-m-d H:i:s');
        $data['ord_unique_string'] = $ord_unique_string;
        $ord_id = DB::table('order')->insertGetId($data);

        // 查询手机号是否存在
        $find_weixin_data = DB::table('weixin_user')
            ->where('weus_phone', $request['orcl_phone'])
            ->select('weus_id', 'weus_phone', 'weus_nickmame', 'weus_headimgurl')
            ->first();
        // 选择的客户id，对应的订单数量增加
        if ($request['ord_client_id']) {
            if ($request['ord_type'] == 1) { //买家类型：1会员零售
                // 零售，会员表
                $client_res = DB::table('member')
                    ->where('mem_id', $request['ord_client_id'])
                    ->increment('mem_order_all');
                $weus_id = $find_weixin_data->weus_id;
            } else {
                $client_res = true;
            }
        } else {
            if ($request['ord_type'] == 2) { //买家类型：2企业客户
                // 1. 判断企业客户账号名称是否存在
                $find_buac = DB::table('business_account')
                    ->where('buac_bucl_id', $request['orcl_business_id'])
                    ->where('buac_name', $request['orcl_name'])
                    ->first(['buac_id']);
                if ($find_buac) {
                    return ['code' => 500, 'msg' => 'success', 'data' => '客户名称已存在，生成订单失败'];
                }

                // 2 新增一个企业会员账号
                $add_buac_data['buac_shop_id'] = $user_info->adm_shop_id;
                $add_buac_data['buac_cid'] = $user_info->adm_cid;
                $add_buac_data['buac_name'] = $request['orcl_name'];
                $add_buac_data['buac_phone'] = $request['orcl_phone'];
                $add_buac_data['buac_bucl_id'] = $request['orcl_business_id'];
                $add_buac_data['buac_create_adm_id'] = $user_info->adm_id;
                $add_buac_data['buac_create_time'] = date('Y-m-d H:i:s');
                $buac_res =  DB::table('business_account')->insertGetId($add_buac_data);
            } else {
                $eme['mem_cid'] = $user_info->adm_cid;
                $eme['mem_superior_shop_id'] = $user_info->adm_shop_id;
                $eme['mem_shop_id'] = $user_info->adm_shop_id;
                $eme['mem_create_id'] = $user_info->adm_id;
                $eme['mem_create_name'] = $user_info->adm_name;
                $eme['mem_name'] = $request['orcl_name'] ? $request['orcl_name'] : '';
                $eme['mem_bership'] = 2;
                $eme['mem_sex'] = 3;
                if (!empty($request['orcl_phone'])) {
                    $find_mem = DB::table('member')
                        ->where('mem_cid', $user_info->adm_cid)
                        ->where('mem_shop_id', $user_info->adm_shop_id)
                        ->where('mem_phone', $request['orcl_phone'])
                        ->first(['mem_id']);
                    if ($find_mem) {
                        return ["code" => 500, 'msg' => 'error', 'data' => '当前手机号已存在'];
                    }
                }
                $eme['mem_phone'] = $request['orcl_phone'] ? $request['orcl_phone'] : '';
                $eme['mem_source'] = $request['orcl_mem_source'] ? $request['orcl_mem_source'] : ''; //来源
                $eme['mem_car_num'] = $request['orcl_car_num'] ? $request['orcl_car_num'] : '';
                $eme['mem_order_all'] = 1; //订单数
                $mem_id = DB::table('member')->insertGetId($eme);
                WashOrderService::addFestival($mem_id,$user_info);//新增节日提醒
                if (!$mem_id) {
                    return ['code' => 500, 'msg' => 'success', 'data' => '新增会员失败'];
                }
                $request['ord_client_id'] = $mem_id;
                $client_res = true;

                if (empty($find_weixin_data)) {
                    // 不存在就新增用户
                    $weus_data['weus_openid'] = $mem_id;
                    $weus_data['weus_phone'] = $request['orcl_phone'];
                    $weus_data['weus_nickmame'] = $request['orcl_name'];
                    $weus_data['weus_follow'] = 1;
                    $weus_data['weus_sex'] = 0;
                    $weus_data['weus_province'] = '';
                    $weus_data['weus_city'] = '';
                    $weus_data['weus_headimgurl'] = '';
                    $weus_data['weus_update_time'] = date('Y-m-d H:i:s');
                    $weus_id = DB::table('weixin_user')->insertGetId($weus_data);
                    if (!$weus_id) {
                        return ['code' => 500, 'msg' => '新增失败', 'data' => ''];
                    }
                    unset($weus_data['weus_update_time']);
                } else {
                    // 更新微信用户信息
                    $edit_weus['weus_phone'] = $request['orcl_phone'];
                    $edit_weus['weus_nickmame'] = $request['orcl_name'];
                    if (!empty($request['weus_headimgurl'])) {
                        $edit_weus['weus_headimgurl'] = $request['weus_headimgurl'];
                    }
                    $edit_weus['weus_update_time'] = date('Y-m-d H:i:s');
                    $edit_weus_res = DB::table('weixin_user')
                        ->where('weus_id', $find_weixin_data->weus_id)
                        ->update($edit_weus);
                    unset($edit_weus);
                    $weus_id = $find_weixin_data->weus_id;
                }

                // 查询微信用户与门店的关系是否存在绑定关系
                $find_user_shop_data = DB::table('user_shop')
                    ->where('ussh_weus_id', $weus_id)
                    ->where('ussh_shop_id', $user_info->adm_shop_id)
                    ->select('ussh_id', 'ussh_user_id', 'ussh_user_type', 'ussh_phone')
                    ->first();

                if (empty($find_user_shop_data)) {
                    // 用户没有与当前门店绑定，把用户与当前门店绑定
                    $ussh_data['ussh_user_id'] = $mem_id;
                    $ussh_data['ussh_weus_id'] = $weus_id;
                    $ussh_data['ussh_shop_id'] = $user_info->adm_shop_id;
                    $ussh_data['ussh_user_type'] = 1;
                    $ussh_data['ussh_phone'] = $request['orcl_phone'];
                    $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' => '新增失败2', 'data' => ''];
                    }
                } else {
                    if (empty($find_user_shop_data->ussh_user_id)) {
                        $ussh_data['ussh_user_type'] = 1;
                        $ussh_data['ussh_phone'] = $request['orcl_phone'];
                        $ussh_data['ussh_create_time'] = date('Y-m-d H:i:s');
                        $ussh_id = DB::table('user_shop')
                            ->where('ussh_id', $find_user_shop_data->ussh_id)
                            ->update($ussh_data);
                    }
                }
            }
        }

        // 添加订单客户表数据
        $orcl_data = [
            'orcl_ord_id' => $ord_id,
            'orcl_client_id' => isset($request['ord_client_id']) ? $request['ord_client_id'] : 0, //选择客户id
            'orcl_name' => $request['orcl_name'],
            'orcl_phone' => $request['orcl_phone'],
            'orcl_car_num' => isset($request['orcl_car_num']) ? $request['orcl_car_num'] : '',
            'orcl_province' => isset($request['orcl_province']) ? $request['orcl_province'] : '',
            'orcl_city' => isset($request['orcl_city']) ? $request['orcl_city'] : '',
            'orcl_county' => isset($request['orcl_county']) ? $request['orcl_county'] : '',
            'orcl_address' => isset($request['orcl_address']) ? $request['orcl_address'] : '',
            'orcl_shipment_party' => isset($request['orcl_shipment_party']) ? $request['orcl_shipment_party'] : 1, //出货方1自营仓库2直营店3加盟店4虚拟加盟店5我的门店(运营中心派单给门店)
            'orcl_update_time' => date('Y-m-d H:i:s'),
        ];

        $orcl_id = DB::table('order_client')->insertGetId($orcl_data);

        $goods_data = $request['goods_data'];
        if (!empty($goods_data)) {
            $goo_all_price = 0; //商品总金额
            $goo_all_quantity = 0; //商品总数量
            // 新增订单商品数据
            foreach ($goods_data as $key => $value) {
                if (!isset($value['goo_type'])) {
                    $value['goo_type'] = 3; //1商品2服务3会员卡
                    $goods_data[$key]['goo_type'] = 3;
                }
                if (!isset($value['goo_state'])) {
                    $value['goo_state'] = 4;
                    $goods_data[$key]['goo_state'] = 4;
                }
                $orgo_data['orgo_ord_id'] = $ord_id;
                $orgo_data['orgo_order_number'] = $ord_order_number;
                $orgo_data['orgo_goo_name'] = $value['goo_name'];
                $orgo_data['orgo_goo_type'] = $value['goo_type'];
                $orgo_data['orgo_state'] = $value['goo_state'];
                $orgo_data['orgo_goo_quantity'] = 1;
                $orgo_data['orgo_goo_unit'] = '张';
                $orgo_data['orgo_goo_unta_id'] = 7;
                $orgo_data['orgo_update_time'] = date('Y-m-d H:i:s');
                $orgo_id = DB::table('order_goods')->insertGetId($orgo_data);
                $goods_data[$key]['orgo_id'] = $orgo_id; //立即派单使用
                $goo_all_quantity += 1; //商品总数量

                $order_items[$key]['orit_shop_id'] = $user_info->adm_shop_id;
                $order_items[$key]['orit_ord_id'] = $ord_id;
                $order_items[$key]['orit_orgo_id'] = isset($orgo_id) ? $orgo_id : '';
            }
            $orit_res = DB::table('wash_order_items')->insert($order_items);
        } else {
            $orit_res = true;
        }
        $ord_edit_data['ord_orcl_id'] = $orcl_id;
        $ord_edit_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_edit_res = DB::table('order')->where('ord_id', $ord_id)->update($ord_edit_data);

        if ($ord_id && $orcl_id && $ord_edit_res && $orit_res) {
            $return_data['ord_id'] = $ord_id; //订单id
            $return_data['ord_order_number'] = $ord_order_number; //订单单号
            $return_data['goods_data'] = json_encode($goods_data); //商品信息
            $return_data['ord_type'] = $request['ord_type']; //买家类型1.会员零售2.企业客户
            $return_data['ord_client_id'] = isset($request['ord_client_id']) ? $request['ord_client_id'] : 0; //选择的客户id,会员id/单位id
            return ['code' => 200, 'msg' => 'success', 'data' => $return_data];
        } else {
            return ['code' => 500, 'msg' => 'error', 'data' => '新增失败'];
        }
    }

    // 编辑
    public static function edit($user_info, $request)
    {
        $del_cogo_res = DB::table('correlation_goods')
            ->where('cogo_pait_id', $request['pait_id'])
            ->delete();
        $data['pait_name'] = $request['pait_name']; //商品名称
        if (empty($request['goods_data'])) {
            return ['code' => 500, 'msg' => '请选择商品', 'data' => '新增失败'];
        }
        $goods_data = json_decode($request['goods_data'], true);
        $goods = '';
        foreach ($goods_data as $key => $value) {
            $value['goo_unit_conversion'] = Db::table('goods')
                ->where('goo_id', $value['goo_id'])
                ->value('goo_unit_conversion');
            if (empty($goods)) {
                if ($value['goo_unta_id'] == 1) {
                    $goods = $value['goo_name'] . '*' . $value['goo_quantity'] . $value['goo_unit'] . '(' . $value['goo_quantity'] * $value['goo_unit_conversion'] . '米)';
                } else {
                    $goods = $value['goo_name'] . '*' . $value['goo_quantity'] . $value['goo_unit'];
                }
            } else {
                if ($value['goo_unta_id'] == 1) {
                    $goods = $goods . '、' . $value['goo_name'] . '*' . $value['goo_quantity'] . $value['goo_unit'] . '(' . $value['goo_quantity'] * $value['goo_unit_conversion'] . '米)';
                } else {
                    $goods = $goods . '、' . $value['goo_name'] . '*' . $value['goo_quantity'] . $value['goo_unit'];
                }
            }
        }
        $data['pait_type'] = 3; //商品类型1包含生成工单2只包含不生成工单服务3只包含商品
        foreach ($goods_data as $key1 => $value1) {
            if ($value1['cogo_goo_type'] == 2) {
                $data['pait_type'] = 2;
                if ($value1['sepr_work_type'] == 1) {
                    $data['pait_type'] = 1;
                    break;
                }
            }
        }
        $data['pait_composition'] = $goods; //组成
        $data['pait_classify_id'] = $request['pait_classify_id']; //分类id
        $data['pait_sort'] = $request['pait_sort']; //排序
        $data['pait_saleable_quantity'] = $request['pait_saleable_quantity']; //可售数量
        $data['pait_ware_id'] = $request['pait_ware_id']; //仓库id
        $data['pait_pic'] = $request['pait_pic']; //封面
        $data['pait_detail'] = $request['pait_detail']; //详情
        $data['pait_recommend_state'] = isset($request['pait_recommend_state']) ? $request['pait_recommend_state'] : 1; //推荐状态：1不推荐2推荐
        if ($request['pait_sell_price'] <= 0) {
            return ['code' => 500, 'msg' => '零售价需要大于0', 'data' => ''];
        }
        if ($request['pait_shop_price'] < $request['pait_sell_price']) {
            return ['code' => 500, 'msg' => '门店价不能小于销售价', 'data' => '门店价不能小于销售价'];
        }
        $data['pait_shop_price'] = $request['pait_shop_price'] * 100; //门店价格
        $data['pait_sell_price'] = $request['pait_sell_price'] * 100; //零售价
        $data['pait_create_adm_id'] = $user_info->adm_id;
        $data['pait_create_time'] = date('Y-m-d H:i:s');
        $data['pait_update_adm_id'] = $user_info->adm_id;
        $data['pait_update_time'] = date('Y-m-d H:i:s');
        $data['pait_pay_type'] = $request['pait_pay_type']??2;
        $data['pait_appoint_num'] = $request['pait_appoint_num']??0;
        $pait_id = DB::table('package_items')->where('pait_id', $request['pait_id'])->update($data);
        foreach ($goods_data as $key => $value) {
            $add_data[$key]['cogo_pait_id'] = $request['pait_id'];
            $add_data[$key]['cogo_goo_id'] = $value['goo_id'];
            $add_data[$key]['cogo_goo_quantity'] = $value['goo_quantity'];
            $add_data[$key]['cogo_goo_unta_id'] = $value['goo_unta_id'];
            $add_data[$key]['cogo_goo_unit'] = $value['goo_unit'];
            $add_data[$key]['cogo_goo_type'] = $value['cogo_goo_type'];
            $add_data[$key]['cogo_goo_price'] = $value['goo_price'] * 100;
            $add_data[$key]['cogo_wago_id'] = $value['wago_id'];
            $add_data[$key]['cogo_create_time'] = date('Y-m-d H:i:s');
        }
        $cogo_res = DB::table('correlation_goods')->insert($add_data);
        if ($cogo_res && $pait_id) {
            return ['code' => 200, 'msg' => '编辑成功', 'data' => ''];
        } else {
            return ['code' => 500, 'msg' => '编辑失败', 'data' => '编辑失败'];
        }
    }

    // 更改分类状态
    public static function editState($ids, $state)
    {
        $data['gocl_state'] = $state;
        $data['gocl_update_time'] = date('Y-m-d H:i:s');
        return DB::table('goods_classification')->whereIn('gocl_id', $ids)
            ->update($data);
    }

    // 更改商品上架状态
    public static function goodseditState($ids, $state)
    {
        $data['pait_state'] = $state;
        $data['pait_update_time'] = date('Y-m-d H:i:s');
        return DB::table('package_items')->whereIn('pait_id', $ids)
            ->update($data);
    }

    // 更改状态
    public static function claDelete($id)
    {
        $data['gocl_is_del'] = 1;
        $data['gocl_update_time'] = date('Y-m-d H:i:s');
        // return DB::table('goods_classification')->where('gocl_id', $id)
        return DB::table('goods_classification')->where('gocl_id', $id)
            ->delete();
    }
    
    // 补货
    public static function replenishment($user_info, $request)
    {
        $find_data = DB::table('package_items')
            ->where('pait_id', $request['pait_id'])
            ->value('pait_saleable_quantity');
        $data['pait_saleable_quantity'] = $find_data + $request['number'];
        $data['pait_update_time'] = date('Y-m-d H:i:s');
        $data['pait_update_adm_id'] = $user_info->adm_id;
        $res = DB::table('package_items')
            ->where('pait_id', $request['pait_id'])
            ->update($data);
        if ($res) {
            return ['code' => 200, 'msg' => '编辑成功', 'data' => ''];
        } else {
            return ['code' => 500, 'msg' => '编辑失败', 'data' => ''];
        }
    }

    // 会员卡使用明细
    public static function detailIndex($user_info, $search_data, $show_count = 10, $field_columns = [])
    {
        // 判断是否传入查询字段
        if (empty($field_columns)) {
            // 查询字段
            $field_columns = ['vcre_id', 'vcre_myvi_id', 'vcre_user_id', 'vcre_ord_num', 'vcre_ord_id', 'vcre_create_time', 'vcre_car_adm_name', 'vcre_car_adm_phone', 'vcre_myvi_num', 'myvi_name', 'vcre_num_change', 'vcre_log', 'orcl_car_num', 'myvi_surplus_times'];
        }
        // 会员卡明细表
        $list_data = DB::table('vip_card_record as v')
            ->leftJoin('myvip as m', 'm.myvi_id', '=', 'v.vcre_myvi_id')
            ->leftJoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'v.vcre_ord_id')
            ->where('vcre_user_id', $search_data['mem_id'])
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['myvi_id'])) {
                    $query->where('myvi_id', $search_data['myvi_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['vcre_myvi_num'])) {
                    $query->where('vcre_myvi_num', 'like', '%' . $search_data['vcre_myvi_num'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //创建时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                    $query->whereBetween('vcre_create_time', [$search_data['create_time_start'], $search_data['create_time_end'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['create_time_start'])) {
                        $query->where('vcre_create_time', '>=', $search_data['create_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['create_time_end'])) {
                            $query->where('vcre_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->select($field_columns)
            ->orderBy('vcre_id', 'desc')
            ->paginate($show_count);
        $list_items = $list_data->items();
        $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;                        //返回数据
        return $data;
    }

    // 操作记录
    public static function paitLogIndex($user_info, $search_data, $show_count = 10)
    {
        // 商品操作记录
        $list_data = DB::table('pait_log as p')
            ->leftJoin('admin as a', 'a.adm_id', '=', 'p.palo_create_id')
            ->where('palo_cid', $user_info->adm_cid)
            ->where('palo_shop_id', $user_info->adm_shop_id)
            ->where('palo_pait_id', $search_data['pait_id'])
            ->select('palo_content', 'adm_name', 'adm_phone', 'palo_create_time', 'palo_remark')
            ->paginate($show_count);
        $list_items = $list_data->items();
        if ($list_items) {
            $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;
        } else {
            return [];
        }
    }

    /**
     * 关联推荐商品套餐
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-10-23
     * @param  [type]           $user_info [description]
     * @param  [type]           $request   [description]
     * @return [type]                      [description]
     */
    public static function correlation($user_info, $request) {
        $pait_count = DB::table('correlation_package')
            ->where('copa_shop_id', $user_info->adm_shop_id)
            ->where(function ($query) use ($request) {
                if (!empty($request['pait_id'])) {
                    $query->where('copa_pait_id', $request['pait_id'])
                        ->orWhere('copa_cpait_id', $request['pait_id']);
                }
            })
            ->count();
        if ($pait_count >= 6) {
            return ['code' => 500, 'msg' => '此套餐已关联六个商品', 'data' => ''];
        }
        $copa_cpait_count = DB::table('correlation_package')
            ->where('copa_shop_id', $user_info->adm_shop_id)
            ->where(function ($query) use ($request) {
                if (!empty($request['copa_cpait_id'])) {
                    $query->where('copa_pait_id', $request['copa_cpait_id'])
                        ->orWhere('copa_cpait_id', $request['copa_cpait_id']);
                }
            })
            ->count();
        if ($copa_cpait_count >= 6) {
            return ['code' => 500, 'msg' => '关联失败：您选择的套餐已关联6个商品', 'data' => ''];
        }
        $find_data = DB::table('correlation_package')
            ->where('copa_shop_id', $user_info->adm_shop_id)
            ->whereRaw("(`copa_pait_id` = ".$request['pait_id']." and `copa_cpait_id` = ".$request['copa_cpait_id'].") or (`copa_pait_id` = ".$request['pait_id']." and `copa_pait_id` = ".$request['copa_cpait_id'].")")
            ->get()->toArray();
        if ($find_data) {
            return ['code' => 500, 'msg' => '已关联，请勿重复添加', 'data' => ''];
        }
        $add_data['copa_shop_id'] = $user_info->adm_shop_id;
        $add_data['copa_create_id'] = $user_info->adm_id;
        $add_data['copa_pait_id'] = $request['pait_id'];
        $add_data['copa_cpait_id'] = $request['copa_cpait_id'];
        $add_data['copa_create_time'] = date('Y-m-d H:i:s');
        $add_res = DB::table('correlation_package')
            ->insertGetId($add_data);
        if ($add_res) {
            return ['code' => 200, 'msg' => '关联成功', 'data' => ''];
        } else {
            return ['code' => 500, 'msg' => '关联失败', 'data' => ''];
        }
    }

    /**
     * 关联推荐商品列表
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-10-23
     * @param  [type]           $user_info [description]
     * @param  [type]           $request   [description]
     * @return [type]                      [description]
     */
    public static function colist($user_info, $request) {
        $find_data = DB::table('correlation_package')
            ->leftJoin('package_items', 'copa_cpait_id', '=', 'pait_id')
            ->where('copa_shop_id', $user_info->adm_shop_id)
            ->whereRaw("(`copa_pait_id` = ".$request['pait_id']." or `copa_cpait_id` = ".$request['pait_id'].")")
            ->select('pait_name', 'copa_cpait_id', 'pait_pic', 'copa_id')
            ->orderBy('copa_id', 'desc')
            ->get()->toArray();
        foreach ($find_data as $key => $value) {
            if ($value->copa_cpait_id == $request['pait_id']) {
                $find_data[$key] = DB::table('correlation_package')
                    ->leftJoin('package_items', 'copa_pait_id', '=', 'pait_id')
                    ->where('copa_id', $value->copa_id)
                    ->select('pait_name', 'pait_id as copa_cpait_id', 'pait_pic', 'copa_id')
                    ->first();
            }
            $pait_pic = json_decode($value->pait_pic, true);
            if (!empty($pait_pic)) {
                $find_data[$key]->pait_pic = $pait_pic[0];
            } else {
                $find_data[$key]->pait_pic = '';
            }
        }
        return ['code' => 200, 'msg' => 'success', 'data' =>$find_data];
    }

    /**
     * 搜索商品
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-10-23
     * @param  [type]           $user_info [description]
     * @param  [type]           $request   [description]
     * @return [type]                      [description]
     */
    public static function package($user_info, $request) {
        $list_data = DB::table('package_items')
            ->where('pait_shop_id', $user_info->adm_shop_id)
            ->where('pait_state', 1)
            ->where(function ($query) use ($request) {
                if (!empty($request['pait_id'])) {
                    $query->where('pait_id', '<>', $request['pait_id']);
                }
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['pait_name'])) {
                    $query->where('pait_name', 'like', '%' . $request['pait_name']. '%');
                }
            })
            ->select('pait_id', 'pait_name', 'pait_pic', 'pait_sell_price', 'pait_composition')
            ->get()->toArray();
        foreach ($list_data as $key => $value) {
            $pait_pic = json_decode($value->pait_pic, true);
            if (!empty($pait_pic)) {
                $list_data[$key]->pait_pic = $pait_pic[0];
            } else {
                $list_data[$key]->pait_pic = '';
            }
        }
        return ['code' => 200, 'msg' => 'success', 'data' =>$list_data];
    }

    /**
     * 解除关联套餐
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-10-23
     * @param  [type]           $user_info [description]
     * @param  [type]           $request   [description]
     * @return [type]                      [description]
     */
    public static function delCorrelation($user_info, $request) {
        $find_data = DB::table('correlation_package')
            ->where('copa_shop_id', $user_info->adm_shop_id)
            ->whereRaw("(`copa_pait_id` = ".$request['pait_id']." and `copa_cpait_id` = ".$request['copa_cpait_id'].") or (`copa_pait_id` = ".$request['copa_cpait_id']." and `copa_cpait_id` = ".$request['pait_id'].")")
            ->delete();
        return ['code' => 200, 'msg' => '解除关联', 'data' => ''];
    }
}
