<?php

namespace App\Http\Controllers\Api\MemberManage;

use App\Http\Controllers\Common\CommonController;
use App\Services\CommonService;
use Illuminate\Http\Request;
// use Illuminate\Support\Facades\Request;
use App\Http\Requests\Validators\Business\WashOrderValidator;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\MemberManage\VerifyMemberListController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\CashierDesk;
use App\Services\Business\WashOrderService;
use App\Services\ReceivablePay\ReceivablePayService;
use App\Services\WeChatApplet\Technician\MemberService;
use \PhpOffice\PhpSpreadsheet\IOFactory;
use App\Http\Models\Api\Export;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\Business\MemberLabelService;


class MemberListController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMemberListController;
        $error_message = $verify_data->indexValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => '参数错误', 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->adm_shop_id;
        $page_size = $request->input('show_count', 10);
        $search_data = $request->all();
        $list_data = DB::table('member')
            ->where('mem_cid', $user_info->adm_cid)
            ->where('mem_shop_id', $shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_4sname'])) {
                    $query->where('mem_4sname', 'like', '%' . $search_data['mem_4sname'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_name'])) {
                    $query->where('mem_name', 'like', '%' . $search_data['mem_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_car_num'])) {
                    $query->where('mem_car_num', 'like', '%' . $search_data['mem_car_num'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_phone'])) {
                    $query->where('mem_phone', 'like', '%' . $search_data['mem_phone'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_birthday'])) {
                    $query->where('mem_birthday', 'like', '%' . $search_data['mem_birthday'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_sex'])) {
                    $query->where('mem_sex', $search_data['mem_sex']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_source'])) {
                    $query->where('mem_source', 'like', '%' . $search_data['mem_source'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_create_time'])) {
                    $query->where('mem_create_time', $search_data['mem_create_time']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_state'])) {
                    $query->where('mem_state', $search_data['mem_state']);
                }
            })
            ->select('mem_id', 'mem_name', 'mem_sex', 'mem_phone', 'mem_birthday', 'mem_car_num', 'mem_car_series', 'mem_province', 'mem_city', 'mem_county', 'mem_address', 'mem_consume_money', 'mem_order_all', 'mem_retreat_trade', 'mem_bership', 'mem_source', 'mem_create_name', 'mem_create_id', 'mem_rec_banlance', 'mem_gift_banlance', 'mem_arrears','mem_salesman_id', 'mem_points', 'mem_level', 'mem_fid', 'mem_car_color', 'mem_state', 'mem_4sname')
            ->orderBy('mem_id', 'desc')
            ->paginate($page_size);
        $list_items = $list_data->items();
        $mem_id = array_column($list_items, 'mem_id');
        $admin_arr = array_column($list_items, 'mem_salesman_id');
        $level_arr = [0=>'普通会员',1=>'白银会员',2=>'黄金会员',3=>'铂金会员',4=>'钻石会员',5=>'黑钻会员'];
        // 获取当前列表下的按钮
        $list_button = getListButton($search_data['api_token'], $search_data['pri_id']);
        if ($mem_id) {
            $find_meca = DB::table('member_car')
                ->whereIn('meca_mem_id', $mem_id)
                ->pluck('meca_car_num', 'meca_mem_id')
                //->orderBy('meca_default', 'asc')
                ->toArray();
            if($admin_arr){
                $admin_arr = array_unique(array_filter($admin_arr));
                $find_admin = DB::table('admin')
                    ->whereIn('adm_id', $admin_arr)
                    ->pluck('adm_name', 'adm_id')
                    ->toArray();
            }
            //查找店铺会员标签
            $find_label = DB::table('member_label as ml')
                ->leftJoin('label as l', 'ml.melal_label_id', '=', 'l.mela_id')
                ->where('melal_cid', $user_info->adm_cid)
                ->where('melal_shop_id', $user_info->adm_shop_id)
                ->whereIn('melal_mem_id', $mem_id)
                ->where('mela_is_show', 1)
                ->get()->toArray();
            if(!empty($find_label)){
                foreach ($find_label as $key_label => $value_label){
                    $label[$value_label->melal_mem_id][] = ['id'=>$value_label->mela_id,'name'=>$value_label->mela_name];
                }
            }
            foreach ($list_data as $key => $value) {
                if (isset($find_meca[$value->mem_id]) && empty($value->mem_car_num)) {
                    $list_data[$key]->mem_car_num = $find_meca[$value->mem_id];
                }
                $list_data[$key]->mem_banlance = $value->mem_rec_banlance + $value->mem_gift_banlance;
                $list_data[$key]->mem_level_name = '';
//                if($value->mem_level > 0){
                    $list_data[$key]->mem_level_name = $level_arr[$value->mem_level];
//                }
                //按钮
                if ($value->mem_state == 1) {
                    $buttonData = ['info','edit', 'stop'];
                }
                if ($value->mem_state == 2) {
                    $buttonData[] = 'start';
                }
                $button = CommonService::getListButton($buttonData,$list_button);
                $list_items[$key]->button_one = $button['button_one']??[];
                $list_items[$key]->button_two = $button['button_two']??[];
                $list_items[$key]->button_three = $button['button_three']??[];
                if (empty($value->mem_salesman_id)) {
                    $list_items[$key]->mem_salesman_id = '';
                }
                $list_items[$key]->mem_salesman_name = $find_admin[$value->mem_salesman_id] ?? '';
                $list_items[$key]->mem_birthday_date = '';
                if($value->mem_birthday){
                    $list_items[$key]->mem_birthday_date = date("n月j日",strtotime("2023-".$value->mem_birthday));
                }
                if (!empty($value->mem_fid)) {
                    $fdata = DB::table('member')
                        ->where('mem_id', $value->mem_fid)
                        ->select('mem_name', 'mem_phone')
                        ->first();
                    if ($fdata) {
                        $list_items[$key]->mem_fname = $fdata->mem_name;
                        $list_items[$key]->mem_fphone = $fdata->mem_phone;
                    } else {
                        $list_items[$key]->mem_fphone = '';
                        $list_items[$key]->mem_fname = '';
                    }
                } else {
                    $list_items[$key]->mem_fphone = '';
                    $list_items[$key]->mem_fname = '';
                }
                $list_items[$key]->mem_points = DB::table('point_detail')
                    ->where('pode_mem_id', $value->mem_id)
                    ->where('pode_state', 1)
                    ->sum('pode_points');
                $list_data[$key]->mem_label_name = [];
                $list_data[$key]->mem_label_id = [];
                if(isset($label[$value->mem_id])){
                    foreach ($label[$value->mem_id] as $ka => $kv){
                        $mem_label_name[] = $kv['name'];
                        $mem_label_id[] = $kv['id'];
                    }
                    $list_data[$key]->mem_label_name = $mem_label_name;
                    $list_data[$key]->mem_label_id = $mem_label_id;
                }
                unset($mem_label_name);unset($mem_label_id);
            }
        }
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $page_size;       //一页显示多少个
        $data_info['data'] = $list_items;                //返回数据
        $sourceSet = DB::table('member_set')
            ->where("mbs_stats",'sourceSet')
            ->where("mbs_shop_id",$user_info->adm_shop_id)
            ->get();
        $sourceSet = CommonService::dataToArray($sourceSet);
        if($sourceSet){
            $sourceSet = CommonService::jointArrayKey($sourceSet, 'mbs_type');
            $data_info['source_state'] = $sourceSet[1]['mbs_state']??2;
            if(isset($sourceSet[2]['mbs_data'])){
                $data_info['source_date'] = json_decode($sourceSet[2]['mbs_data']);
            }else{
                $data_info['source_date'] = [];
            }
        }else {
            $data_info['source_state'] = 2;
            $data_info['source_date'] = [];
        }
        //获取top按钮
        $search_button = 'lead,export';
        $topdata = 'setMemberData';
        $top_button = CommonService::getTopButton($topdata,$search_button,$list_button);
        if ($list_data) {
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data_info, 'list_button' => $list_button, 'top_button'=>$top_button]);
        } else {
            return response()->json(['code' => 500, 'msg' => '暂无数据', 'data' => '暂无数据']);
        }
    }

    // 新增
    public function add(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMemberListController;
        $error_message = $verify_data->addValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => $error_message, 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 1. 判断手机号是否存在
        $find_mem = DB::table('member')
            ->where('mem_cid', $user_info->adm_cid)
            ->where('mem_superior_shop_id', $shop_id)
            ->where('mem_phone', $request['mem_phone'])
            ->where('mem_4sname', $request['mem_4sname'])
            ->first(['mem_id']);
        if ($find_mem) {
            return response()->json(['code' => 500, 'msg' => '当前手机号已存在', 'data' => '当前手机号已存在']);
        }
        // if ($request['mem_car_num']) {
        //     // 判断车牌号是否存在
        //     $find_meca = DB::table('member_car')
        //         ->where('meca_cid', $user_info->adm_cid)
        //         ->where('meca_superior_shop_id', $shop_id)
        //         ->where('meca_car_num', $request['mem_car_num'])
        //         ->first(['meca_id']);
        //     if ($find_meca) {
        //         return response()->json(['code' => 500, 'msg' => '当前车牌号已存在', 'data' => '当前车牌号已存在']);
        //     }
        // }
        // $mem_fid = 0;
        // if ($request['mem_fphone']) {
        //     $mem_fid = DB::table('member')
        //         ->where('mem_shop_id', $shop_id)
        //         ->where('mem_phone', $request['mem_fphone'])
        //         ->value('mem_id');
        //     if (!$mem_fid) {
        //         return response()->json(['code' => 500, 'msg' => '未查询到该推荐人', 'data' => '']);
        //     }
        // }

        DB::beginTransaction();
        // 2 新增一个会员信息
        $mem_add_data['mem_cid'] = $user_info->adm_cid;
        $mem_add_data['mem_shop_id'] = $user_info->adm_shop_id;
        $mem_add_data['mem_superior_shop_id'] = $shop_id;
        $mem_add_data['mem_name'] = $request['mem_name'];
        $mem_add_data['mem_4sname'] = $request['mem_4sname'];
        $mem_add_data['mem_create_name'] = $user_info->adm_name;
        $mem_add_data['mem_create_id'] = $user_info->adm_id;
        // $mem_add_data['mem_sex'] = $request['mem_sex'];
        // $mem_add_data['mem_fid'] = $mem_fid;
        $mem_add_data['mem_phone'] = $request['mem_phone'];
        // $mem_add_data['mem_birthday'] = $request['mem_birthday'] ? $request['mem_birthday'] : '';
        $mem_add_data['mem_car_num'] = str_replace(' ', '', $request['mem_car_num']);
        $mem_add_data['mem_car_series'] = $request['mem_car_series'] ? $request['mem_car_series'] : '';
        $mem_add_data['mem_car_color'] = $request['mem_car_color'] ? $request['mem_car_color'] : '';
        $mem_add_data['mem_car_model'] = $request['mem_car_model'] ? $request['mem_car_model'] : '';
        $mem_add_data['mem_province'] = $request['mem_province'] ? $request['mem_province'] : '';
        $mem_add_data['mem_city'] = $request['mem_city'] ? $request['mem_city'] : '';
        $mem_add_data['mem_county'] = $request['mem_county'] ? $request['mem_county'] : '';
        $mem_add_data['mem_address'] = $request['mem_address'] ? $request['mem_address'] : '';
        $mem_add_data['mem_bership'] = $request['mem_bership'];
        $mem_add_data['mem_source'] = $request['mem_source'] ? $request['mem_source'] : '';
        $mem_add_data['mem_salesman_id'] = $request['mem_salesman_id'] ? $request['mem_salesman_id'] : '0';;//业务员id
        $mem_id = MemberService::addMember($mem_add_data);
        // $mem_id =  DB::table('member')->insertGetId($mem_add_data);
        // $mem_id =  DB::table('member')->insertGetId($mem_add_data);
        // WashOrderService::addFestival($mem_id,$user_info);//新增节日提醒
        //添加会员标签
        // MemberLabelService::addLabelToMember($mem_id,$request['mem_label'],$user_info);

        // 3.新增一个车辆信息
        if ($request['mem_car_num']) {
            $meca_add_data['meca_cid'] = $user_info->adm_cid;
            $meca_add_data['meca_shop_id'] = $user_info->adm_shop_id;
            $meca_add_data['meca_superior_shop_id'] = $shop_id;
            $meca_add_data['meca_create_adm_id'] = $user_info->adm_id;
            $meca_add_data['meca_mem_id'] = $mem_id;
            $meca_add_data['meca_car_num'] = $request['mem_car_num'];
            $meca_add_data['meca_car_series'] = $request['mem_car_series'] ? $request['mem_car_series'] : '';
            $meca_add_data['meca_car_model'] = $request['mem_car_model'] ? $request['mem_car_model'] : '';
            $meca_res =  DB::table('member_car')->insert($meca_add_data);
        } else {
            $meca_res = true;
        }

        // // 查询手机号是否存在
        // $find_weixin_data = DB::table('weixin_user')
        //     ->where('weus_phone', $request['mem_phone'])
        //     ->select('weus_id', 'weus_phone', 'weus_nickmame', 'weus_headimgurl')
        //     ->first();
        // if (empty($find_weixin_data)) {
        //     // 不存在就新增用户
        //     $data['weus_phone'] = $request['mem_phone'];
        //     $data['weus_openid'] = $mem_id;
        //     $data['weus_nickmame'] = $request['mem_name'];
        //     $data['weus_follow'] = 1;
        //     $data['weus_sex'] = 0;
        //     $data['weus_province'] = $request['mem_province'] ? $request['mem_province'] : '';
        //     $data['weus_city'] = $request['mem_city'] ? $request['mem_city'] : '';
        //     $data['weus_headimgurl'] = '';
        //     $data['weus_update_time'] = date('Y-m-d H:i:s');
        //     $weus_id = DB::table('weixin_user')->insertGetId($data);
        //     if (!$weus_id) {
        //         return ['code' => 500, 'msg' => '新增失败', 'data' => ''];
        //     }
        //     unset($data['weus_update_time']);
        // } else {
        //     // 更新微信用户信息
        //     $edit_weus['weus_phone'] = $request['mem_phone'];
        //     $edit_weus['weus_nickmame'] = $request['mem_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_phone', $request['mem_phone'])
        //     ->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'] = 0;
        //     $ussh_data['ussh_shop_id'] = $user_info->adm_shop_id;
        //     $ussh_data['ussh_user_type'] = 1;
        //     $ussh_data['ussh_phone'] = $request['mem_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['mem_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);
        //     }
        // }

        if ($mem_id && $meca_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '会员列表', '新增', '新增会员：' . $request['mem_phone'] . '成功');
            $return_data['mem_id'] = $mem_id;
            return response()->json(['code' => 200, 'msg' => '新增会员成功', 'data' => '新增会员成功', 'return_data' => $return_data]);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => '新增会员失败', 'data' => '新增会员失败']);
        }
    }

    // 编辑
    public function edit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMemberListController;
        $error_message = $verify_data->editShowValidator($request->all()); //验证编辑id是否存在
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => $error_message, 'data' => '参数错误', 'error_message' => $error_message]);
        }

        $error_message = $verify_data->addValidator($request->all()); //验证除编辑id外的参数是否存在
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => $error_message, 'data' => '参数错误', 'error_message' => $error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 1. 判断手机号是否存在
        $find_mem = DB::table('member')
            ->where('mem_id', '<>', $request['mem_id'])
            ->where('mem_superior_shop_id', $shop_id)
            ->where('mem_phone', $request['mem_phone'])
            ->first(['mem_id']);
        if ($find_mem) {
            return response()->json(['code' => 500, 'msg' => '该手机号已存在', 'data' => '该手机号已存在']);
        }
        if ($request['mem_car_num']) {
            // 判断车牌号是否存在
            $find_meca = DB::table('member_car')
                ->where('meca_mem_id', '<>', $request['mem_id'])
                ->where('meca_cid', $user_info->adm_cid)
                ->where('meca_superior_shop_id', $shop_id)
                ->where('meca_car_num', $request['mem_car_num'])
                ->first(['meca_id']);
            if ($find_meca) {
                return response()->json(['code' => 500, 'msg' => '当前车牌号已存在', 'data' => '当前车牌号已存在']);
            }
        }

        // 2 编辑一个手机号与车牌号的绑定关系
        $mem_edit_data['mem_name'] = $request['mem_name'];
        $mem_edit_data['mem_4sname'] = $request['mem_4sname'];
        $mem_edit_data['mem_sex'] = $request['mem_sex'];
        $mem_edit_data['mem_phone'] = $request['mem_phone'];
        $mem_edit_data['mem_birthday'] = $request['mem_birthday'] ? $request['mem_birthday'] : '';
        $mem_edit_data['mem_province'] = $request['mem_province'] ? $request['mem_province'] : '';
        $mem_edit_data['mem_city'] = $request['mem_city'] ? $request['mem_city'] : '';
        $mem_edit_data['mem_county'] = $request['mem_county'] ? $request['mem_county'] : '';
        $mem_edit_data['mem_address'] = $request['mem_address'] ? $request['mem_address'] : '';
        $mem_edit_data['mem_bership'] = $request['mem_bership'];
        $mem_edit_data['mem_car_num'] = str_replace(' ', '', $request['mem_car_num']); //车牌号
        $mem_edit_data['mem_car_series'] = $request['mem_car_series'] ? $request['mem_car_series'] : ''; //车系
        $mem_edit_data['mem_car_color'] = $request['mem_car_color'] ? $request['mem_car_color'] : '';
        $mem_edit_data['mem_source'] = $request['mem_source'] ? $request['mem_source'] : ''; //客户来源
        $mem_edit_data['mem_salesman_id'] = $request['mem_salesman_id'] ? $request['mem_salesman_id'] : '0';;//业务员id
        $mem_edit_data['mem_update_time'] = date('Y-m-d H:i:s');
        $mem_res = DB::table('member')
            ->where('mem_id', $request['mem_id'])
            ->update($mem_edit_data);
        //添加会员标签
        // MemberLabelService::addLabelToMember($request['mem_id'],$request['mem_label'],$user_info);
        // 3.新增一个车辆信息
        if ($request['mem_car_num']) {
            $meca_add_data['meca_cid'] = $user_info->adm_cid;
            $meca_add_data['meca_shop_id'] = $user_info->adm_shop_id;
            $meca_add_data['meca_superior_shop_id'] = $shop_id;
            $meca_add_data['meca_create_adm_id'] = $user_info->adm_id;
            $meca_add_data['meca_mem_id'] = $request['mem_id'];
            $meca_add_data['meca_car_num'] = $request['mem_car_num'];
            $meca_add_data['meca_car_series'] = $request['mem_car_series'] ? $request['mem_car_series'] : '';
            $meca_add_data['meca_car_brand_series'] = $request['mem_car_series'] ? $request['mem_car_series'] : '';
            $meca_add_data['meca_car_model'] = $request['mem_car_model'] ? $request['mem_car_model'] : '';
            $meca_id = DB::table('member_car')
                ->where('meca_mem_id', $request['mem_id'])
                ->where('meca_car_num', $request['mem_car_num'])
                ->where('meca_cid', $user_info->adm_cid)
                ->where('meca_shop_id', $user_info->adm_shop_id)
                ->value('meca_id');
            if ($meca_id) {
                $meca_add_data['meca_update_time'] = date('Y-m-d H:i:s');
                $meca_res =  DB::table('member_car')
                    ->where('meca_id', $meca_id)
                    ->update($meca_add_data);
            } else {
                $meca_res =  DB::table('member_car')->insert($meca_add_data);
            }
        } else {
            $meca_res = true;
        }
        if ($mem_res && $meca_res) {
            Common::addLog($user_info, getRealIp($request), '会员列表', '编辑', '编辑会员：' . $request['mem_phone'] . '成功');
            return response()->json(['code' => 200, 'msg' => '编辑会员成功', 'data' => '编辑会员成功']);
        } else {
            return response()->json(['code' => 500, 'msg' => '编辑会员失败', 'data' => '编辑会员失败']);
        }
    }

    // 发送模板消息
    public function sendMessage(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMemberListController;
        $error_message = $verify_data->sendMessageValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => '参数错误', 'error_message' => $error_message]);
        }
        $client_data = json_decode($request['client_data'], true);
        $phone = array_column($client_data, 'phone');

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $find_openid = DB::table('member_weixin')
            ->where('mewe_binding_state', 1)
            ->whereIn('mewe_phone', $phone)
            ->select('mewe_openid', 'mewe_nickmame', 'mewe_phone')
            ->get()->toArray();
        $send_count = 0;
        $send_phone = []; //已发送手机号
        $CashierDesk = new CashierDesk();
        foreach ($find_openid as $key => $value) {
            // openid中存在有数据id情况，大于20位的
            // 判断是否为微信openid
            if (mb_strlen($value->mewe_openid) > 20) {
                // 发送微信消息
                $message['title'] = $request['title'];
                $message['message'] = $request['message'];
                $message['name'] = $value->mewe_nickmame;
                $message['phone'] = $value->mewe_phone;
                $message['openid'] = $value->mewe_openid;
                $CashierDesk->weixinMessageSend($message);
                $send_count++;
                $send_phone[] = $value->mewe_phone;
            }
        }

        foreach ($client_data as $key => $value) {
            $temp_data['wems_adm_id'] = $user_info->adm_id;
            $temp_data['wems_shop_id'] = $user_info->adm_shop_id;
            $temp_data['wems_mem_id'] = $value['mem_id'];
            $temp_data['wems_name'] = $value['name'];
            $temp_data['wems_phone'] = $value['phone'];
            $temp_data['wems_title'] = $request['title'];
            $temp_data['wems_message'] = $request['message'];
            if (in_array($value['phone'], $send_phone)) {
                $temp_data['wems_state'] = 2; //发送状态：1未发送消息2已发送消息
            } else {
                $temp_data['wems_state'] = 1;
            }
            $wems_data[] = $temp_data;
            unset($temp_data);
        }
        $wems_res = DB::table('weixin_message_send')->insert($wems_data);
        if ($wems_res) {
            Common::addLog($user_info, getRealIp($request), '会员列表', '发送消息', '发送消息成功');
            return response()->json(['code' => 200, 'msg' => '消息发送成功', 'data' => $send_count . '位客户消息发送成功']);
        } else {
            return response()->json(['code' => 500, 'msg' => '发送消息失败', 'data' => '发送消息失败']);
        }
    }

    // 微信消息发送记录
    public function sendRecord(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $list_data = DB::table('weixin_message_send as wms')
            ->leftjoin('admin as a', 'a.adm_id', '=', 'wms.wems_adm_id')
            ->where('wems_shop_id', $user_info->adm_shop_id)
            ->where('wems_mem_id', $request['mem_id'])
            ->select('wems_title', 'wems_message', 'wems_create_time', 'adm_name')
            ->orderBy('wems_id', 'desc')
            ->paginate($this->show_count);
        $list_items = $list_data->items();
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;       //一页显示多少个
        $data_info['data'] = $list_items;                //返回数据
        if ($list_data) {
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data_info]);
        } else {
            return response()->json(['code' => 500, 'msg' => '暂无数据', 'data' => '暂无数据']);
        }
    }

    /**
     * 充值
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-07-20
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function recharge(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $request['ord_source'] = 1;
        DB::beginTransaction();
        if (empty($request['type'])) {
            return response()->json(['code' => 500, 'msg' => '请选择会员类型', 'data' => '']);
        }
        if ($request['type'] == 1) {
            $result = WashOrderService::recharge($user_info, $request);
        } else {
            $result = WashOrderService::busRecharge($user_info, $request);
        }
        if ($result['code'] == 200) {
            DB::commit();
        } else {
            DB::rollBack();
        }
        return response()->json($result);
    }

    /**
     * 充值退款
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-07-20
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function refund(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $request['ord_source'] = 1;
        DB::beginTransaction();
        if (empty($request['type'])) {
            return response()->json(['code' => 500, 'msg' => '请选择会员类型', 'data' => '']);
        }
        if ($request['type'] == 1) {
            $result = WashOrderService::refund($user_info, $request);
            if ($result['code'] == 200) {
                $order_ret = DB::table('order as a')
                    ->leftJoin('order_client as b', 'a.ord_id', '=', 'b.orcl_ord_id')
                    ->where('ord_id', $result['data'])
                    ->select('ord_order_number','orcl_name','ord_actual_price','ord_type','ord_client_id')
                    ->first();
                $receivable['recpay_cid'] = $user_info->adm_cid;
                $receivable['recpay_shop_id'] = $user_info->adm_shop_id;
                $receivable['recpay_shop_superior_id'] = $user_info->adm_shop_id;
                $receivable['recpay_type'] = '2'; //类型：1.销售订单
                $receivable['recpay_original_id'] = $result['data']; //与类型所对应的id
                $receivable['recpay_original_number'] = $order_ret->ord_order_number; //与类型所对应的单号
                $receivable['recpay_client_type'] = $order_ret->ord_type; //客户类型：1.会员零售 2.来往单位 3.加盟店 4会员零售(工单代收）
                $receivable['recpay_client_id'] = $order_ret->ord_client_id; //会员id/来往单位id
                $receivable['recpay_client_name'] = $order_ret->orcl_name; //来往单位名称
                $receivable['recpay_receivable_price'] = 0; //应收金额
                $receivable['recpay_arrears_price'] = 0; //欠收金额
                $receivable['recpay_actual_price'] = '0'; //实收金额
                $receivable['recpay_cost_price'] = '0'; //成本价
                $receivable['recpay_receivable_pay'] = 0; //应付金额
                $receivable['recpay_actual_pay'] = 0; //实付金额
                $receivable['recpay_state'] = '1'; //状态：1未确认2已确认
                $receivable['recpay_order_state'] = '1'; //订单状态：1正常2退款3取消
                $receivable['recpay_plus_minus'] = '2'; //盈利正负：1正值2负值
                $receivable['recpay_profit'] = abs($order_ret->ord_actual_price); //盈利金额
                DB::table('receivable_pay')->insertGetId($receivable);
                DB::commit();
            } else {
                DB::rollBack();
            }
        } else {
            $result = WashOrderService::busRefund($user_info, $request);
            if ($result['code'] == 200) {
                $order_ret = DB::table('order as a')
                    ->leftJoin('order_client as b', 'a.ord_id', '=', 'b.orcl_ord_id')
                    ->where('ord_id', $result['data']['recpay_original_id'])
                    ->select('ord_order_number','orcl_name','ord_actual_price','ord_type','ord_client_id')
                    ->first();
                $receivable['recpay_cid'] = $user_info->adm_cid;
                $receivable['recpay_shop_id'] = $user_info->adm_shop_id;
                $receivable['recpay_shop_superior_id'] = $user_info->adm_shop_id;
                $receivable['recpay_type'] = '2'; //类型：1.销售订单
                $receivable['recpay_original_id'] = $result['data']['recpay_original_id']; //与类型所对应的id
                $receivable['recpay_original_number'] = $order_ret->ord_order_number; //与类型所对应的单号
                $receivable['recpay_client_type'] = $order_ret->ord_type; //客户类型：1.会员零售 2.来往单位 3.加盟店 4会员零售(工单代收）
                $receivable['recpay_client_id'] = $request['bucl_id']; //会员id/来往单位id
                $receivable['recpay_client_name'] = $result['data']['bucl_name']; //来往单位名称
                $receivable['recpay_receivable_price'] = 0; //应收金额
                $receivable['recpay_arrears_price'] = 0; //欠收金额
                $receivable['recpay_actual_price'] = '0'; //实收金额
                $receivable['recpay_cost_price'] = '0'; //成本价
                $receivable['recpay_receivable_pay'] = 0; //应付金额
                $receivable['recpay_actual_pay'] = 0; //实付金额
                $receivable['recpay_state'] = '1'; //状态：1未确认2已确认
                $receivable['recpay_order_state'] = '1'; //订单状态：1正常2退款3取消
                $receivable['recpay_plus_minus'] = '2'; //盈利正负：1正值2负值
                $receivable['recpay_profit'] = abs($order_ret->ord_actual_price); //盈利金额
                DB::table('receivable_pay')->insertGetId($receivable);
                DB::commit();
            } else {
                DB::rollBack();
            }
        }
        return response()->json($result);
    }

    /**
     * 充值/消费记录
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-07-20
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function reclog(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $result = WashOrderService::reclog($user_info, $request, $request['show_count']);
        if ($result) {
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => $result]);
        } else {
            return response()->json(['code' => 200, 'msg' => '暂无数据', 'data' =>[]]);
        }
    }

    /**
     * 获取会员余额
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-07-21
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function getBanlance(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if (!isset($request['type'])) {
            $request['type'] = 1;
            // return response()->json(['code' => 500, 'msg' => '请选择会员类型', 'data' => '']);
        }
        if (empty($request['mem_id']) && empty($request['keywords'])) {
            return response()->json(['code' => 500, 'msg' => '请选择会员', 'data' =>[]]);
        }
        if ($request['type'] != 2) {
            $result = WashOrderService::getBanlance($user_info, $request);
        } else {
            $result = WashOrderService::busBanlance($user_info, $request);
        }
        if ($result) {
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => $result]);
        } else {
            return response()->json(['code' => 200, 'msg' => '暂无此会员', 'data' =>'']);
        }
    }

    /*
     * @name 详情页
     * @param string 会员id
     * @retrun array
     * @author Ma 2023/8/31 9:33
     *
    */
    public function getInfo(Request $request){
        // 验证数据
        $verify_data = new VerifyMemberListController;
        $error_message = $verify_data->editShowValidator($request->all()); //验证编辑id是否存在
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => $error_message, 'data' => '参数错误', 'error_message' => $error_message]);
        }
        $input = $request->all();
        $data = DB::table('member')
            ->where('mem_id', $input['mem_id'])
            ->first();
        //查找店铺会员标签
        $find_label = DB::table('member_label as ml')
            ->leftJoin('label as l', 'ml.melal_label_id', '=', 'l.mela_id')
            /*->where('melal_cid', $user_info->adm_cid)
            ->where('melal_shop_id', $user_info->adm_shop_id)*/
            ->where('melal_mem_id', $input['mem_id'])
            ->where('mela_is_show', 1)
            ->get()->toArray();
        if(!empty($find_label)){
            foreach ($find_label as $key_label => $value_label){
                $label[$value_label->melal_mem_id][] = ['id'=>$value_label->mela_id,'name'=>$value_label->mela_name];
            }
        }
        if ($data) {
            $data->mem_bership_name = '';
            if($data->mem_sex == 1){$data->mem_sex_name = '男';}else if($data->mem_sex == 2){$data->mem_sex_name = '女';}else{$data->mem_sex_name = '未知';}
            if($data->mem_bership == 1){$data->mem_bership_name = '正式会员';}else if($data->mem_bership == 2){$data->mem_bership_name = '临时会员';}
            $data->mem_rec_banlance = $data->mem_rec_banlance / 100;
            $data->mem_consume_money = $data->mem_consume_money / 100;
            $data->mem_gift_banlance = $data->mem_gift_banlance / 100;
            $data->mem_rec_banlance = $data->mem_rec_banlance + $data->mem_gift_banlance;
            $data->mem_birthday_date = '';
            if($data->mem_birthday){
                $data->mem_birthday_date = date("n月j日",strtotime("2023-".$data->mem_birthday));
            }
            $data->mem_label_name = '';
            if(isset($label[$data->mem_id])){
                foreach ($label[$data->mem_id] as $ka => $kv){
                    $mem_label_name[] = $kv['name'];
                }
                $data->mem_label_name = implode(',',$mem_label_name);
            }
            $salesman_name = DB::table('admin')
                ->where('adm_id', $data->mem_salesman_id)
                ->value('adm_name');
            $data->mem_salesman_name = $salesman_name??'';
            $mem_consume_money = DB::table('order')
                ->where('ord_client_id', $input['mem_id'])
                ->where('ord_wor_state', '<>',11)
                ->sum('ord_actual_price');
            $data->mem_consume_money = $mem_consume_money/100;
            $update['mem_consume_money'] = $mem_consume_money/100;
            $mem_order_all =  DB::table('order')
                ->where('ord_client_id', $input['mem_id'])->count();
            $data->mem_order_all = $mem_order_all;
            $update['mem_order_all'] = $mem_order_all;
            $mem_first_time = DB::table('order')
                ->where('ord_client_id', $input['mem_id'])
                ->orderBy('ord_id','asc')
                ->value('ord_create_time');
            if($mem_first_time){
                $data->mem_first_time = $mem_first_time;
                if($mem_order_all == 1){
                    $data->mem_last_time = $mem_first_time;
                }else{
                    $mem_last_time = DB::table('order')
                        ->where('ord_client_id', $input['mem_id'])
                        ->orderBy('ord_id','desc')
                        ->value('ord_create_time');
                    if($mem_last_time){
                        $data->mem_last_time = $mem_last_time;
                    }else{
                        $data->mem_last_time = $mem_first_time;
                    }
                }
                $update['mem_last_time'] = $data->mem_last_time;
                $update['mem_first_time'] = $mem_first_time;
            }else{
                $data->mem_first_time = '暂无订单';
                $data->mem_last_time = '暂无订单';
            }
            DB::table('member')
                ->where('mem_id', $input['mem_id'])
                ->update($update);
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data]);
        } else {
            return response()->json(['code' => 500, 'msg' => '暂无数据', 'data' => '暂无数据']);
        }
    }

    /*
     * @name 给会员设置提醒节日
     * @param string ju_ordernum 订单单号
     * @retrun array
     * @author Ma 2023/8/31 14:04
     *
    */
    public function setRemind(Request $request){
        // 验证数据
        $verify_data = new VerifyMemberListController;
        $error_message = $verify_data->setRemindValidator($request->all()); //验证编辑id是否存在
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => $error_message, 'data' => '参数错误', 'error_message' => $error_message]);
        }
        $request = $request->all();
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;


        //$mem_id_arr = [951];//会员id
        //$fest_id_arr = [1,2];//节日id
        //会员
        if(isset($request['mefe_mem_id']) && !empty($request['mefe_mem_id'])){
            $mem_id_arr = [$request['mefe_mem_id']];//会员id
            //$mem_id_arr = [951];//会员id
        }else if((isset($request['mem_sex']) && !empty($request['mem_sex'])) || isset($request['mem_create_time']) || isset($request['mem_end_time'])){
            //根据条件搜索会员
            $mem_data = DB::table('member')
                ->where('mem_cid', $user_info->adm_cid)
                ->where('mem_superior_shop_id', $shop_id)
                ->where(function ($query) use ($request) {
                    if (!empty($request['mem_sex'])) {
                        $query->where('mem_sex', $request['mem_sex']);
                    }
                })
                ->where(function ($query) use ($request) {
                    if (!empty($request['mem_salesman_id'])) {
                        $query->where('mem_salesman_id', $request['mem_salesman_id']);
                    }
                })
                ->where(function ($query) use ($request) { //创建时间
                    // 如果选择开始时间并且选择结束时间
                    if (!empty($request['mem_create_time']) && !empty($request['mem_end_time'])) {
                        $query->whereBetween('mem_create_time', [$request['mem_create_time'], $request['mem_end_time'] . ' 23:59:59']);
                    } else {
                        // 如果选择开始时间
                        if (!empty($request['mem_create_time'])) {
                            $query->where('mem_create_time', '>=', $request['mem_create_time']);
                        } else {
                            // 如果选择结束时间
                            if (!empty($request['mem_end_time'])) {
                                $query->where('mem_create_time', '<=', $request['mem_end_time'] . ' 23:59:59');
                            }
                        }
                    }
                })
                ->get()->toArray();
            if($mem_data){
                foreach ($mem_data as $mem_key => $mem_value){
                    $mem_id_arr[] = $mem_value->mem_id;
                }
            }
        }
        if(isset($mem_id_arr)){
            $data = DB::table('member_festival')
                ->where('mefe_cid', $user_info->adm_cid)
                ->where('mefe_shop_id', $shop_id)
                ->whereIn('mefe_mem_id', $mem_id_arr)//会员id
                ->get()->toArray();
            if($data){
                foreach ($data as $d_key => $d_value){
                    $mefe_id[] = $d_value->mefe_id;
                    $mefe_fest_id[] = $d_value->mefe_fest_id;
                    if($d_value->mefe_fest_type == 1){//节日提醒
                        $festival[] = $d_value->mefe_fest_id;
                    }elseif($d_value->mefe_fest_type == 2){//生日提醒
                        $birthday[] = $d_value->mefe_fest_id;
                    }
                }
            }
        }

        if($request['type'] == 1){//获取已经设置的提醒
            $data_ret['birthday'] = $birthday??[];//生日
            $data_ret['festival'] = $festival??[];//节日
            if (isset($mefe_fest_id) && !empty($mefe_fest_id)) {
                return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data_ret]);
            } else {
                return response()->json(['code' => 200, 'msg' => '暂无数据', 'data' => ['birthday'=>[],'festival'=>[]]]);
            }
        }else{//设置提醒节日
            if(!empty($mefe_id)){
                $del_fe_res = DB::table('member_festival')
                    ->whereIN('mefe_id', $mefe_id)
                    ->delete();
            }
            if(isset($mem_id_arr)){
                foreach ($mem_id_arr as $key => $value){
                    $add_data['mefe_cid'] = $user_info->adm_cid;
                    $add_data['mefe_shop_id'] = $user_info->adm_shop_id;
                    $add_data['mefe_superior_shop_id'] = $shop_id;
                    $add_data['mefe_mem_id'] = $value;//客户id
                    $add_data['mefe_create_time'] = date('Y-m-d H:i:s');
                    $add_data['mefe_create_name'] = $user_info->adm_name;
                    $add_data['mefe_create_id'] = $user_info->adm_id;
                    //节日
                    if(isset($request['festival']) && !empty(array_filter($request['festival']))){
                        foreach (array_filter($request['festival']) as $fest_key => $fest_value){
                            $add_data['mefe_fest_id'] = $fest_value;//节日id
                            $add_data['mefe_fest_type'] = 1;
                            $data =  DB::table('member_festival')->insertGetId($add_data);
                        }
                    }
                    //生日
                    if(isset($request['birthday']) && !empty(array_filter($request['birthday']))){
                        foreach (array_filter($request['birthday']) as $bir_key => $bir_value){
                            $add_data['mefe_fest_id'] = $bir_value;//生日id
                            $add_data['mefe_fest_type'] = 2;
                            $data =  DB::table('member_festival')->insertGetId($add_data);
                        }
                    }
                }
            }
        }
        return response()->json(['code' => 200, 'msg' => '操作成功', 'data' => 'success']);
    }

    /*
     * @name 会员搜索下拉
     * @retrun array
     * @author Ma 2023/9/6 19:03
     *
    */
    public function searchList(Request $request){
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $search_data = $request->all();
        $list_data = DB::table('member')
            ->where('mem_cid', $user_info->adm_cid)
            ->where('mem_superior_shop_id', $shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_name']) && !is_numeric($search_data['mem_name'])) {
                    $query->where('mem_name', 'like', '%' . $search_data['mem_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (isset($search_data['mem_name']) && is_numeric($search_data['mem_name'])) {
                    $query->where('mem_phone', 'like', '%' . $search_data['mem_name'] . '%');
                }
            })
            ->select('mem_id', 'mem_name', 'mem_phone')
            ->orderBy('mem_id', 'desc')
            ->get()->toArray();
        $data_info['data'] = $list_data;                //返回数据
        if ($list_data) {
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data_info]);
        } else {
            return response()->json(['code' => 500, 'msg' => '暂无数据', 'data' => []]);
        }
    }

    /**
     * 会员欠款记录
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-09-06
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function arrearsRecord(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMemberListController;
        $error_message = $verify_data->arrearsRecordValidator($request->all()); //验证编辑id是否存在
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => $error_message, 'data' => '参数错误']);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $list_data = DB::table('order')
            ->where('ord_type', $request['type'])
            ->where('ord_client_id', $request['mem_id'])
            ->where('ord_state', [1,3])
            ->select('ord_order_number', 'ord_order_price', 'ord_actual_price', 'ord_banlance', 'ord_payment_way', 'ord_zero_price')
            ->orderBy('ord_id', 'desc')
            ->paginate($this->show_count);
        $list_items = $list_data->items();
        if ($list_items) {
            foreach ($list_items as $key => $value) {
                $list_items[$key]->arrears = $value->ord_order_price - $value->ord_actual_price -$value->ord_banlance - $value->ord_zero_price;
            }
        }
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;       //一页显示多少个
        $data_info['data'] = $list_items;                //返回数据
        if ($list_data) {
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data_info]);
        } else {
            return response()->json(['code' => 500, 'msg' => '暂无数据', 'data' => '暂无数据']);
        }
    }

    /*
     * @name 业务员替换
     * @param string ju_ordernum 订单单号
     * @retrun array
     * @author Ma 2023/10/9 15:11
     *
    */
    public function salesmanRep(Request $request){
        // 验证数据
        $verify_data = new VerifyMemberListController;
        $error_message = $verify_data->salesmanRepValidator($request->all()); //验证编辑id是否存在
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => '参数错误', 'data' => '参数错误']);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $admin_arr = [$request['old_salesman'],$request['new_salesman']];
        $find_admin = DB::table('admin')
            ->whereIn('adm_id', $admin_arr)
            ->get()->toArray();
        $new_admin_id = array_column($find_admin,'adm_id');
        if(!in_array($request['old_salesman'], $new_admin_id)){
            return response()->json(['code' => 500, 'msg' => '旧业务员不存在', 'data' => '']);
        }
        if(!in_array($request['new_salesman'], $new_admin_id)){
            return response()->json(['code' => 500, 'msg' => '新业务员不存在', 'data' => '']);
        }
        if($find_admin){
            foreach ($find_admin as $key => $value){
                if($value->adm_id == $request['new_salesman']){
                    if($value->adm_state == 2){
                        return response()->json(['code' => 500, 'msg' => '新业务员为离职状态，不能替换', 'data' => '']);
                    }
                }
            }
            if(isset($request['car_series']) && !empty($request['car_series'])){
                $request['car_series'] = explode(",",$request['car_series']);
            }
            //开始替换
            $ret = DB::table('member')
                ->where('mem_salesman_id', $request['old_salesman'])
                ->where(function ($query) use ($request) {
                    if (isset($request['sex']) && !empty($request['sex']) && $request['sex'] != 3) {
                        $query->where('mem_sex', $request['sex']);
                    }
                })
                ->where(function ($query) use ($request) {
                    if (isset($request['start_time']) && !empty($request['start_time'])) {
                        $query->where('mem_create_time','>=', $request['start_time']);
                    }
                })
                ->where(function ($query) use ($request) {
                    if (isset($request['end_time']) && !empty($request['end_time'])) {
                        $query->where('mem_create_time','<=', $request['end_time']. ' 23:59:59');
                    }
                })
                ->where(function ($query) use ($request) {
                    if (isset($request['car_series']) && !empty($request['car_series'])) {
                        foreach ($request['car_series'] as $key => $value){
                            if($key == 0){
                                $query->where('mem_car_series', 'like', $value.'%');
                            }else{
                                $query->orwhere('mem_car_series', 'like', $value.'%');
                            }
                        }
                    }
                })
                ->update(['mem_salesman_id' => $request['new_salesman']]);
            if ($ret) {
                return response()->json(['code' => 200, 'msg' => '替换成功', 'data' => '']);
            } else {
                return response()->json(['code' => 500, 'msg' => '没有可以替换的人', 'data' => '']);
            }
        }
    }

    // 导入-下载模板
    public function downTemplate(Request $request)
    {
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => config('apisystem.server_name_https') . '/storage/Template/MemberList.xlsx']);
    }

    /**
     * 批量新增会员导入
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-11-06
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    // 批量新增导入
    public function lead(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMemberListController;
        $error_message = $verify_data->leadValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => $error_message, 'data' => '参数错误']);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $file = $request->file('file');

        if ($file->isValid()) {
            // 获取表格的大小，限制上传表格的大小5M
            $file_size = $_FILES['file']['size'];
            if ($file_size > 5 * 1024 * 1024) {
                return response()->json(['code' => 500, 'msg' => '文件大小不能超过5M', 'data' => '文件大小不能超过5M']);
            }

            // 限制上传表格类型
            $ext = $file->getClientOriginalExtension(); //文件拓展名
            if ($ext != 'xlsx') {
                return response()->json(['code' => 500, 'msg' => '仅允许上传以xlsx结尾的后缀文件', 'data' => '仅允许上传以xlsx结尾的后缀文件']);
            }

            // 有Xls和Xlsx格式两种
            $objReader = IOFactory::createReader('Xlsx');
            $filename = $_FILES['file']['tmp_name'];
            $objPHPExcel = $objReader->load($filename);  //$filename可以是上传的表格，或者是指定的表格
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            if ($highestRow < 2) {
                return response()->json(['code' => 500, 'msg' => '未获取到会员数据', 'data' => '未获取到会员数据']);
            }
            if ($highestRow > 1501) {
                return response()->json(['code' => 500, 'msg' => '一次最多导入1500条数据', 'data' => '一次最多导入1500条数据']);
            }

            // 循环读取excel表格，整合成数组,如果是不指定key的二维,就用$data[i][j]表示。
            DB::beginTransaction();
            $a = 0;
            $error = 0;
            $melo_number = $user_info->adm_shop_id . time();
            for ($j = 2; $j <= $highestRow; $j++) {
                $message = '';
                $add_mem['mem_cid'] = $user_info->adm_cid; //所属企业id
                $add_mem['mem_shop_id'] = $user_info->adm_shop_id; //所属门店id
                $add_mem['mem_superior_shop_id'] = $shop_id; //所属门店id
                $add_mem['mem_create_time'] = date('Y-m-d H:i:s');

                $add_mem['mem_4sname'] = trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue());
                // 名称
                if (empty($add_mem['mem_4sname'])) {
                    $message = '第'.$j.'行会员名称必填';
                }
                $add_mem['mem_name'] = trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue());
                if (empty($add_mem['mem_name'])) {
                    $message = '第'.$j.'行会员名称必填';
                }
                
                // 手机号
                $add_mem['mem_phone'] = trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue());
                $find_mem = DB::table('member')
                    ->where('mem_shop_id', $user_info->adm_shop_id)
                    ->where('mem_phone', $add_mem['mem_phone'])
                    ->value('mem_id');
                if ($find_mem) {
                    if (empty($messages)) {
                        $message = '第'.$j.'行手机号已存在';
                    } else {
                        $message = $message.',第'.$j.'行手机号已存在';
                    }
                }
                // 省
                $add_mem['mem_province'] = trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue());
                // 市
                $add_mem['mem_city'] = trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue());
                // 县
                $add_mem['mem_county'] = trim($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue());
                // 详细地址
                $add_mem['mem_address'] = trim($objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue());
                $add_log_res =false;
                if ($message) {
                    $add_log['melo_state'] = 2;
                    if ($add_log_res) {
                        $message = '添加车辆信息成功;'.$message;
                        $add_log['melo_state'] = 1;
                    }
                    $add_log['melo_message'] = $message;
                    $add_log['melo_number'] = $melo_number;
                    $add_log['melo_create_time'] = date('Y-m-d H:i:s');
                    if (!$add_log_res) {
                        $error++;
                    }
                } else {
                    $add_res = DB::table('member')->insertGetId($add_mem);
                    $add_log['melo_state'] = 1;
                    $add_log['melo_message'] = '成功';
                    $add_log['melo_number'] = $melo_number;
                    $add_log['melo_create_time'] = date('Y-m-d H:i:s');
                }
                $add_log['melo_shop_id'] = $user_info->adm_shop_id;
                $add_log['melo_mem_name'] = $add_mem['mem_name'];
                $add_log['melo_mem_phone'] = $add_mem['mem_phone'];
                $log_res = DB::table('member_log')->insert($add_log);
            }
            Common::addLog($user_info, getRealIp($request), '会员列表', '导入', '导入会员成功');
            DB::commit();
            $msg = '上传'.($highestRow - 1).'条，失败'.$error.'条';
            return response()->json(['code' => 200, 'msg' => $msg, 'data' => $melo_number, 'num' => $highestRow - 1]);
        } else {
            return response()->json(['code' => 500, 'msg' => '上传有误，请重新上传！', 'data' => '上传有误，请重新上传！']);
        }
    }

    /**
     * 导出
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-11-07
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function export(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        DB::connection()->enableQueryLog();#开启执行日志
        $search_data = $request->all();
        $list_data = DB::table('member')
            ->where('mem_cid', $user_info->adm_cid)
            ->where('mem_shop_id', $shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_name'])) {
                    $query->where('mem_name', 'like', '%' . $search_data['mem_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_4sname'])) {
                    $query->where('mem_4sname', 'like', '%' . $search_data['mem_4sname'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_car_num'])) {
                    $query->where('mem_car_num', 'like', '%' . $search_data['mem_car_num'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_phone'])) {
                    $query->where('mem_phone', 'like', '%' . $search_data['mem_phone'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_birthday'])) {
                    $query->where('mem_birthday', 'like', '%' . $search_data['mem_birthday'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_sex'])) {
                    $query->where('mem_sex', $search_data['mem_sex']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_source'])) {
                    $query->where('mem_source', 'like', '%' . $search_data['mem_source'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_create_time'])) {
                    $query->where('mem_create_time', $search_data['mem_create_time']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_state'])) {
                    $query->where('mem_state', $search_data['mem_state']);
                }
            })
            ->select('mem_id', 'mem_name', 'mem_sex', 'mem_phone', 'mem_birthday', 'mem_car_num', 'mem_car_series', 'mem_province', 'mem_city', 'mem_county', 'mem_address', 'mem_consume_money', 'mem_order_all', 'mem_retreat_trade', 'mem_bership', 'mem_source', 'mem_create_name', 'mem_create_id', 'mem_rec_banlance', 'mem_gift_banlance', 'mem_arrears','mem_salesman_id', 'mem_points', 'mem_level', 'mem_fid', 'mem_4sname')
            ->orderBy('mem_id', 'desc')
            ->get()->toArray();
        $data['sqls'] = DB::getQueryLog()[0];
        $sqls = $data['sqls'];
        $excel = new CommonController();
        $amp_id = $search_data['amp_id']??0;
        return $excel->getExcelOut($amp_id,$user_info,$search_data['pri_id'], $sqls, $search_data['api_token'],200);
        if (!empty($list_data)) {
            // 将对象转化为数组
            $list_data = json_decode(json_encode($list_data), true);
            $level_arr = [0=>'普通会员',1=>'白银会员',2=>'黄金会员',3=>'铂金会员',4=>'钻石会员',5=>'黑钻会员'];
            foreach ($list_data as $key => $value) {
                $data[$key]['mem_name'] = $value['mem_name'];
                if ($value['mem_sex'] == 1) {
                    $data[$key]['mem_sex'] = '男';
                } elseif ($value['mem_sex'] == 2) {
                    $data[$key]['mem_sex'] = '女';
                } else {
                    $data[$key]['mem_sex'] = '未知';
                }
                $data[$key]['mem_phone'] = $value['mem_phone'];
                $data[$key]['mem_address'] = $value['mem_province'].$value['mem_city'].$value['mem_county'].$value['mem_address'];
                $data[$key]['mem_car_num'] = $value['mem_car_num'];
                $data[$key]['mem_car_series'] = $value['mem_car_series'];
                $data[$key]['mem_bership'] = $value['mem_bership'] == 1 ? '正式':'临时';
                $data[$key]['mem_level'] = $level_arr[$value['mem_level']];
                $data[$key]['mem_birthday'] = $value['mem_birthday'];
                $data[$key]['mem_source'] = $value['mem_source'];
                $data[$key]['mem_arrears'] = $value['mem_arrears']/100;
                $data[$key]['mem_banlance'] = ($value['mem_rec_banlance'] + $value['mem_gift_banlance'])/100;
                $data[$key]['mem_points'] = $value['mem_points'];

                $data[$key]['mem_create_id'] = DB::table('admin')
                    ->where('adm_id', $value['mem_create_id'])
                    ->value('adm_name');
                $data[$key]['mem_fid'] = DB::table('member')
                    ->where('mem_id', $value['mem_fid'])
                    ->value('mem_phone');
            }
        } else {
            return response()->json(['code'=>500, 'msg'=>'没有符合条件的数据', 'data'=>'没有符合条件的数据']);
        }
        $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
        // 创建文件夹
        if (!file_exists($pathName)) {
            mkdir($pathName, 0775, true);
            chmod($pathName, 0775);
        }

        $streamFileRand = '会员列表' . time() . rand(1000, 9999) . '.xls';
        // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
        $streamFilename = $pathName . '/' . $streamFileRand;

        $where['action_name'] = '会员列表';
        $where['field_name'] = ['会员姓名','性别','联系电话','联系地址','车牌号','品牌车系','会员级别','会员等级','生日','来源','欠款金额','余额','积分','创建人','邀请人'];

        // 调用导出的公共方法
        export::publicExport(
            $streamFilename, //路径
            $where,    //sheet名及其每一行的标题
            $data      //导出数据
        );

        // 判断文件是否存在 存在则成功  不存在则失败
        if (file_exists($streamFilename)) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'storage/excel/' . $streamFileRand]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'导出失败']);
        }
    }

    /**
     * 会员导入记录
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-11-10
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function memberLog(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $list_data = DB::table('member_log')
            ->where('melo_shop_id', $user_info->adm_shop_id)
            ->where(function ($query) use ($request) {
                if (!empty($request['melo_mem_name'])) {
                    $query->where('melo_mem_name', $request['melo_mem_name']);
                }
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['melo_mem_phone'])) {
                    $query->where('melo_mem_phone', $request['melo_mem_phone']);
                }
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['melo_state'])) {
                    $query->where('melo_state', $request['melo_state']);
                }
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['melo_create_time'])) {
                    $query->where('melo_create_time', 'like', $request['melo_create_time'].'%');
                }
            })
            ->orderBy('melo_id', 'desc')
            ->paginate(10);
        $list_items = $list_data->items();
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;        //一页显示多少个
        $data_info['data'] = $list_items;                        //返回数据

        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    /**
     * 停用启用
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-01-12
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function memState(Request $request) {
        // 验证数据
        $verify_data = new VerifyMemberListController;
        $error_message = $verify_data->editShowValidator($request->all()); //验证编辑id是否存在
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => $error_message, 'data' => '参数错误', 'error_message' => $error_message]);
        }
        $user_info = Common::getUserInfo($request['api_token']);
        $find_mem = DB::table('member')
            ->where('mem_id', $request['mem_id'])
            ->first();
        if (empty($find_mem)) {
            return response()->json(['code' => 500, 'msg' =>'会员不存在', 'data' => '']);
        }
        if (!in_array($request['mem_state'], [1,2])) {
            return response()->json(['code' => 500, 'msg' =>'参数错误', 'data' => '']);
        }
        $update_data['mem_state'] = $request['mem_state'];
        $update_data['mem_update_time'] = date('Y-m-d H:i:s');
        $update_res = DB::table('member')
            ->where('mem_id', $request['mem_id'])
            ->update($update_data);
        if ($update_res) {
            if ($request['mem_state'] == 1) {
                $hint = '启用';
            } else {
                $hint = '停用';
            }
            Common::addLog($user_info, getRealIp($request), '会员列表', '停启用会员', $hint.'会员' . $find_mem->mem_name . '成功');
            return response()->json(['code' => 200, 'msg' =>$hint.'成功', 'data' => '']);
        } else {
            return response()->json(['code' => 500, 'msg' =>'操作失败', 'data' => '']);
        }
    }
    
    /**|---------------------------------------------------------------------------------
     * @name 设置客户来源
     * @param string type 数据类型  1 查询 2编辑
     * @param string mbs_type 数据类型1操作设置2数据设置
     * @param string mbs_data 数据
     * @param string mbs_state 数据状态
     * @param string mbs_stats 属性 sourceSet：来源设置
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2025/3/6 17:20
     * |---------------------------------------------------------------------------------
    */
    public function setMemberData ( Request $request ){
        $input = $request->all();
        if(!$request->filled('mbs_stats') || !in_array($input['mbs_stats'], ['sourceSet'])){
            return response()->json(['code' => ErrorInc::INVALID_PARAM, 'msg' =>'属性错误', 'data' => '']);
        }
        if(!$request->filled('type') || !in_array($input['type'], [1,2])){
            return response()->json(['code' => ErrorInc::INVALID_PARAM, 'msg' =>'请求类型错误', 'data' => '']);
        }else{
            if(!$request->filled('mbs_type') || !in_array($input['mbs_type'], [0,1,2])){
                return response()->json(['code' => ErrorInc::INVALID_PARAM, 'msg' =>'数据类型错误', 'data' => '']);
            }else {
                $user_info = Common::getUserInfo($request['api_token']);
                $return = MemberService::setMemberData($input, $user_info, $request->ip());
                return response()->json(['code' => $return['code'], 'msg' =>$return['msg'], 'data' => $return['data']]);
            }
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 订单编辑用户信息
     * @param array $user_info 用户信息
     * @param array $request 请求信息
     * @retrun /multitype:array
     * @author dou 2025/3/28 16:38
     * |---------------------------------------------------------------------------------
     */
    public function editOrderMember ( Request $request ){
        if ($request['edit_type'] == 2) {
            // 验证数据
            $verify_data = new WashOrderValidator;
            $error_message = $verify_data->addMemberValidator($request->all());
            if ($error_message) {
                return response()->json(['code' => 500, 'msg' => $error_message, 'data' => '参数错误', 'error_message' => $error_message]);
            }
        }
        $user_info = Common::getUserInfo($request['api_token']);
        return MemberService::editOrderMember($user_info, $request, $request->ip());
    }

    /**|---------------------------------------------------------------------------------
     * @name 订单编辑保险公司
     * @param array $user_info 用户信息
     * @param array $request 请求信息
     * @retrun /multitype:array
     * @author 
     * |---------------------------------------------------------------------------------
     */
    public function editOrderBus ( Request $request ){
        if ($request['edit_type'] == 2) {
            // 验证数据
            $verify_data = new WashOrderValidator;
            $error_message = $verify_data->addBusinessAccValidator($request->all());
            if ($error_message) {
                return response()->json(['code' => 500, 'msg' => $error_message, 'data' => '参数错误', 'error_message' => $error_message]);
            }
        }
        $user_info = Common::getUserInfo($request['api_token']);
        return MemberService::editOrderBus($user_info, $request, $request->ip());
    }
}
