<?php
namespace App\Http\Controllers\Api\ProductManage;

use App\Http\Controllers\Api\Verify\MemberManage\VerifyMemberListController;
use App\Services\CommonService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\ProductManage\VerifyServiceProjectController;
use \PhpOffice\PhpSpreadsheet\IOFactory;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;

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

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyServiceProjectController;
        $error_message = $verify_data->indexValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', '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);
        $post['string'] = 'sepr_';
        $post['user_info'] = $user_info;
        $type = 3;
        $where_data = whereFunction($post,$type);
        $search_data = $request->all();
        $list_data = DB::table('service_project')
            ->where('sepr_cid', $user_info->adm_cid)
            ->whereIn($where_data['string'], $where_data['shop_id'])
            ->where('sepr_delete', 1)
            ->where(function($query) use($search_data) {
                if (!empty($search_data['sepr_name'])) {
                    $query->where('sepr_name', 'like', '%'.$search_data['sepr_name'].'%' );
                }
            })
            ->where(function($query) use($search_data) {
                if (!empty($search_data['sepr_state'])) {
                    $query->where('sepr_state', $search_data['sepr_state']);
                }
            })
            ->where(function($query) use($search_data) {
                if (!empty($search_data['sepr_order_type'])) {
                    $query->where('sepr_order_type', $search_data['sepr_order_type']);
                }
            })
            ->where(function($query) use($search_data) {
                if (!empty($search_data['sepr_show_location'])) {
                    $query->where('sepr_show_location', $search_data['sepr_show_location']);
                }
            })
            ->where(function($query) use($search_data) {
                if (!empty($search_data['sepr_work_type'])) {
                    $query->where('sepr_work_type', $search_data['sepr_work_type']);
                }
            })
            ->select('sepr_id', 'sepr_name', 'sepr_money', 'sepr_order_money', 'sepr_state', 'sepr_assign_price', 'sepr_assign_state','sepr_order_type','sepr_recycle','sepr_create_time','sepr_img','sepr_remark', 'sepr_check_car', 'sepr_show_location', 'sepr_work_type', 'sepr_sort', 'sepr_shop_id', 'sepr_code', 'sepr_class_id', 'sepr_class_name')
            ->orderBy('sepr_sort', 'desc')
            ->paginate($page_size);
        $list_items = $list_data->items();
        // if ($list_items) {
        //     foreach ($list_items as $key => $value) {
        //         $length = strlen(config('apisystem.server_name_https'));
        //         if (substr($value->sepr_img, 0,4) == 'http') {
        //             $list_items[$key]->sepr_img = substr($value->sepr_img, $length);
        //         }
        //     }
        // }
        $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;                //返回数据

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        //获取top按钮
        $sea_button_data = 'add,start,stop,delete';
        $sea_button_data = CommonService::getTopButton('',$sea_button_data,$list_button);
        if($list_items) {
            if ($list_button) {
                foreach ($list_items as $key => $value) {
                    $list_items[$key]->list_button_one[] = [];
                    $list_items[$key]->list_button_two[] = [];
                    foreach ($list_button as $key_b => $value_b) {
                        if ($user_info->adm_shop_id == $value->sepr_shop_id) {
                            if ($value_b['pri_operate_method'] == 'edit') {//编辑
                                $list_items[$key]->list_button_one[] = $value_b;
                            }
                            if ($value_b['pri_operate_method'] == 'stop' && $value->sepr_state == 1) {//停用
                                $list_items[$key]->list_button_two[] = $value_b;
                            }
                            if ($value_b['pri_operate_method'] == 'start' && $value->sepr_state == 2) {//启用
                                $list_items[$key]->list_button_two[] = $value_b;
                            }
                            if ($value_b['pri_operate_method'] == 'delete') {//删除
                                $list_items[$key]->list_button_two[] = $value_b;
                            }
                            $list_items[$key]->edit = 1;
                        }
                    }
                    if ($user_info->adm_shop_id != $value->sepr_shop_id) {
                        $list_items[$key]->edit = 2;
                    }
                }
            }
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info, 'list_button'=>$list_button, 'sea_button_data'=>$sea_button_data]);
        }else{
            return response()->json(['code'=>200, 'msg'=>'error', 'data'=>$data_info, 'list_button'=>$list_button, 'sea_button_data'=>$sea_button_data]);
        }
    }

    // 新增
    public function add(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyServiceProjectController;
        $error_message = $verify_data->addValidator($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;

        // 1. 判断服务项目名称是否存在
        $find_sepr = DB::table('service_project')
            ->where('sepr_delete', 1)
            ->where('sepr_cid', $user_info->adm_cid)
            ->where('sepr_superior_shop_id', $shop_id)
            ->where('sepr_name', $request['sepr_name'])
            ->select('sepr_id')
            ->first();
        if ($find_sepr) {
            return response()->json(["code"=>500,'msg'=>'服务项目已存在', 'data'=>'服务项目已存在']);
        }
        if (!empty($request['sepr_code'])) {
            // 1. 判断服务项目名称是否存在
            $find_sepr_code = DB::table('service_project')
                ->where('sepr_delete', 1)
                ->where('sepr_cid', $user_info->adm_cid)
                ->where('sepr_superior_shop_id', $shop_id)
                ->where('sepr_code', $request['sepr_code'])
                ->select('sepr_id')
                ->first();
            if ($find_sepr_code) {
                return response()->json(["code"=>500,'msg'=>'服务项目编号已存在', 'data'=>'服务项目编号已存在']);
            }
        }
        // 2 新增一个服务项目数据
        $sepr_add_data = [
            'sepr_cid'=>$user_info->adm_cid,
            'sepr_shop_id'=>$user_info->adm_shop_id,
            'sepr_superior_shop_id'=>$shop_id,
            'sepr_name'=>$request['sepr_name'],
            'sepr_code'=>$request['sepr_code'],
            'sepr_money'=>$request['sepr_money'] * 100,
            'sepr_order_money'=>$request['sepr_order_money'] * 100,
            'sepr_order_type'=>1,
            'sepr_sort'=>$request->input('sepr_sort', 0),
            'sepr_class_id'=>$request->input('sepr_class_id', 0),//分类
            'sepr_work_type'=>1,//流程分类1有工单2不生成工单
        ];
        $sepr_add_data['sepr_check_car'] = 1;//是否验件1是2否
        $sepr_add_data['sepr_class_id'] = $request->input('sepr_class_id', 0);//分类id
        $sepr_add_data['sepr_class_name'] = $request->input('sepr_class_name', '');//分类名称
        
        //sepr_pic_conf:[{"id":1,"show_word":"汽车名牌","must_state":1},{"id":2,"show_word":"车膜标签","must_state":1},{"id":3,"show_word":"膜桶标签","must_state":2},{"id":4,"show_word":"全车照片","must_state":1},{"id":5,"show_word":"全车视频","must_state":1}]
        
        // if (isset($request['sepr_img']) && !empty($request['sepr_img'])) {
        //     // 判断是否有新图片上传
        //     if (strpos($request['sepr_img'], 'data:image') === 0) {
        //         // 调用全局函数 上传图片
        //         $image_path = uploadBase64ImgFolder($shop_id, $value, 2);
        //         $sepr_add_data['sepr_img'] = $image_path; //新上传的图片路径
        //     } else {
        //         $sepr_add_data['sepr_img'] = $request['sepr_img'];
        //     }
        // }
        if (!empty($request['sepr_remark'])) {
            $sepr_add_data['sepr_remark'] = $request['sepr_remark']; //备注
        } else {
            $sepr_add_data['sepr_remark'] = '';
        }

        // 新增服务项目
        $sepr_res =  DB::table('service_project')->insertGetid($sepr_add_data);
        if (!empty($request['sepr_data_one'])) {
            foreach ($request['sepr_data_one'] as $key => $value) {
                $add_sepr_img[$key]['seim_imco_id'] = $value;
                $add_sepr_img[$key]['seim_sepr_id'] = $sepr_res;
                $add_sepr_img[$key]['seim_create_time'] = date('Y-m-d H:i:s');
                $add_sepr_img[$key]['seim_create_id'] = $user_info->adm_id;
            }
            $add_seim_res = DB::table('sepr_img')->insert($add_sepr_img);
        }
        if (!empty($request['sepr_data_two'])) {
            foreach ($request['sepr_data_two'] as $key => $value) {
                $add_sepr_img[$key]['seim_imco_id'] = $value;
                $add_sepr_img[$key]['seim_sepr_id'] = $sepr_res;
                $add_sepr_img[$key]['seim_create_time'] = date('Y-m-d H:i:s');
                $add_sepr_img[$key]['seim_create_id'] = $user_info->adm_id;
            }
            $add_seim_res = DB::table('sepr_img')->insert($add_sepr_img);
        }
        if ($sepr_res) {
            Common::addLog($user_info, getRealIp($request), '服务项目','新增','新增服务项目：'.$request['sepr_name'].'成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'新增服务项目：成功']);
        }else{
            return response()->json(["code"=>500,'msg'=>'error','data'=>'新增服务项目：失败']);
        }
    }

    // 编辑
    public function edit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyServiceProjectController;
        $error_message = $verify_data->editShowValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>$error_message, 'data'=>'']);
        }
        if ($request['type'] == 1) {
            $find_sepr = DB::table('service_project')
                ->where('sepr_id', $request['sepr_id'])
                ->select('sepr_id', 'sepr_name', 'sepr_img', 'sepr_order_money', 'sepr_check_car', 'sepr_money', 'sepr_show_location', 'sepr_remark', 'sepr_work_type', 'sepr_sort', 'sepr_code', 'sepr_class_id', 'sepr_class_name')
                ->first();
            $seim_data = DB::table('sepr_img')
                ->where('seim_sepr_id', $request['sepr_id'])
                ->select('seim_imco_id')
                ->get()->toArray();
            $seim_imco_id = array_column($seim_data, 'seim_imco_id');
            $data_one = DB::table('image_config')
                ->where('imco_type', 1)
                ->select('imco_id', 'imco_name')
                ->get()->toArray();
            $data_two = DB::table('image_config')
                ->where('imco_type', 2)
                ->select('imco_id', 'imco_name')
                ->get()->toArray();
            foreach ($data_one as $key => $value) {
                if (in_array($value->imco_id, $seim_imco_id)) {
                    $data_one[$key]->select = 1;
                } else {
                    $data_one[$key]->select = 2;
                }
            }
            foreach ($data_two as $key => $value) {
                if (in_array($value->imco_id, $seim_imco_id)) {
                    $data_two[$key]->select = 1;
                } else {
                    $data_two[$key]->select = 2;
                }
            }
            $find_sepr->data_one = $data_one;
            $find_sepr->data_two = $data_two;
            return response()->json(["code"=>200,'msg'=>'success','data'=>$find_sepr]);
        }
        // 验证数据
        $verify_data = new VerifyServiceProjectController;
        $error_message = $verify_data->editValidator($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;
        // 1. 判断服务项目名称是否存在
        $find_sepr = DB::table('service_project')
            ->where('sepr_id', '<>', $request['sepr_id'])
            ->where('sepr_delete', 1)
            ->where('sepr_cid', $user_info->adm_cid)
            ->where('sepr_superior_shop_id', $shop_id)
            ->where('sepr_name', $request['sepr_name'])
            ->select('sepr_id')
            ->first();
        if ($find_sepr) {
            return response()->json(["code"=>500,'msg'=>'服务项目已存在','data'=>'服务项目已存在']);
        }
        if (!empty($request['sepr_code'])) {
            // 1. 判断服务项目名称是否存在
            $find_sepr = DB::table('service_project')
                ->where('sepr_id', '<>', $request['sepr_id'])
                ->where('sepr_delete', 1)
                ->where('sepr_cid', $user_info->adm_cid)
                ->where('sepr_superior_shop_id', $shop_id)
                ->where('sepr_code', $request['sepr_code'])
                ->select('sepr_id')
                ->first();
            if ($find_sepr) {
                return response()->json(["code"=>500,'msg'=>'服务项目编号已存在','data'=>'服务项目编号已存在']);
            }
        }
        // 2 编辑服务项目数据
        $sepr_edit_data = [
            'sepr_name'=>$request['sepr_name'],
            'sepr_code'=>$request['sepr_code'],
            'sepr_money'=>$request['sepr_money'] * 100,
            'sepr_order_money'=>$request['sepr_order_money'] * 100,
            'sepr_order_type'=>1,
            'sepr_sort'=>$request->input('sepr_sort', 0),
            'sepr_show_location'=>$request->input('sepr_show_location', 0),//显示位置
            'sepr_work_type'=>1,//流程分类1有工单2不生成工单
            'sepr_update_time'=>date('Y-m-d H:i:s'),
        ];
        $sepr_edit_data['sepr_check_car'] = 1;//是否验车1是2否
        $sepr_edit_data['sepr_class_id'] = $request->input('sepr_class_id', 0);//分类id
        $sepr_edit_data['sepr_class_name'] = $request->input('sepr_class_name', '');//分类名称
        if (isset($request['sepr_img'])) {
            if (empty($request['sepr_img'])) {
                $sepr_edit_data['sepr_img'] = ''; //新上传的图片路径
            } else {
                // 判断是否有新图片上传
                if (strpos($request['sepr_img'], 'data:image') === 0) {
                    // 调用全局函数 上传图片
                    $image_path = uploadBase64ImgFolder($shop_id, $value, 2);
                    $sepr_edit_data['sepr_img'] = $image_path; //新上传的图片路径
                } else {
                    $sepr_edit_data['sepr_img'] = $request['sepr_img'];
                }
            }
        }
        if (!empty($request['sepr_remark'])) {
            $sepr_edit_data['sepr_remark'] = $request['sepr_remark']; //备注
        } else {
            $sepr_edit_data['sepr_remark'] = '';
        }

        // 编辑服务项目
        $sepr_res =  DB::table('service_project')
            ->where('sepr_id', $request['sepr_id'])
            ->update($sepr_edit_data);
        $delete = DB::table('sepr_img')
            ->where('seim_sepr_id', $request['sepr_id'])
            ->delete();
        if (!empty($request['sepr_data_one'])) {
            foreach ($request['sepr_data_one'] as $key => $value) {
                $add_sepr_img[$key]['seim_imco_id'] = $value;
                $add_sepr_img[$key]['seim_sepr_id'] = $request['sepr_id'];
                $add_sepr_img[$key]['seim_create_time'] = date('Y-m-d H:i:s');
                $add_sepr_img[$key]['seim_create_id'] = $user_info->adm_id;
            }
            $add_seim_res = DB::table('sepr_img')->insert($add_sepr_img);
        }
        if (!empty($request['sepr_data_two'])) {
            foreach ($request['sepr_data_two'] as $key => $value) {
                $add_sepr_imgs[$key]['seim_imco_id'] = $value;
                $add_sepr_imgs[$key]['seim_sepr_id'] = $request['sepr_id'];
                $add_sepr_imgs[$key]['seim_create_time'] = date('Y-m-d H:i:s');
                $add_sepr_imgs[$key]['seim_create_id'] = $user_info->adm_id;
            }
            $add_seim_res = DB::table('sepr_img')->insert($add_sepr_imgs);
        }

        if ($sepr_res) {
            Common::addLog($user_info, getRealIp($request), '服务项目','编辑','编辑服务项目：'.$request['sepr_name'].'成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'编辑服务项目：成功']);
        }else{
            return response()->json(["code"=>500,'msg'=>'error','data'=>'编辑服务项目：失败']);
        }
    }

    // 启用
    public function start(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyServiceProjectController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

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

        // 查询信息
        $find_sepr = DB::table('service_project')
                    ->whereIn('sepr_id',$request['sepr_id'])
                    ->select('sepr_name')
                    ->get();
        foreach ($find_sepr as $key => $value) {
            $sepr_name[] = $value->sepr_name;
        }

        // 启用
        $update_data['sepr_state'] = 1;//状态1启用2停用
        $update_data['sepr_update_time'] = date('Y-m-d H:i:s');
        $sepr_res = DB::table('service_project')
                    ->whereIn('sepr_id', $request['sepr_id'])
                    ->update($update_data);

        if($sepr_res) {
            Common::addLog($user_info, getRealIp($request), '服务项目','启用','服务项目：（'.implode(',', $sepr_name).'）启用成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'启用成功']);
        }else{
            return response()->json(["code"=>500,'msg'=>'error','data'=>'启用失败']);
        }
    }

    // 停用
    public function stop(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyServiceProjectController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

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

        // 查询信息
        $find_sepr = DB::table('service_project')
                    ->whereIn('sepr_id',$request['sepr_id'])
                    ->select('sepr_name')
                    ->get();
        foreach ($find_sepr as $key => $value) {
            $sepr_name[] = $value->sepr_name;
        }

        // 启用
        $update_data['sepr_state'] = 2;//状态1启用2停用
        $update_data['sepr_update_time'] = date('Y-m-d H:i:s');
        $sepr_res = DB::table('service_project')
                    ->whereIn('sepr_id', $request['sepr_id'])
                    ->update($update_data);

        if($sepr_res) {
            Common::addLog($user_info, getRealIp($request), '服务项目','停用','服务项目：（'.implode(',', $sepr_name).'）停用成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'停用成功']);
        }else{
            return response()->json(["code"=>500,'msg'=>'error','data'=>'停用失败']);
        }
    }

    // 删除
    public function delete(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyServiceProjectController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

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

        // 查询信息
        $find_sepr = DB::table('service_project')
                    ->whereIn('sepr_id',$request['sepr_id'])
                    ->select('sepr_name')
                    ->get();
        foreach ($find_sepr as $key => $value) {
            $sepr_name[] = $value->sepr_name;
        }

        // 删除
        $update_data['sepr_delete'] = 2;//是否删除：1正常2已删除
        $update_data['sepr_update_time'] = date('Y-m-d H:i:s');
        $sepr_res = DB::table('service_project')
                    ->whereIn('sepr_id', $request['sepr_id'])
                    ->update($update_data);

        if($sepr_res) {
            Common::addLog($user_info, getRealIp($request), '服务项目','删除','服务项目：（'.implode(',', $sepr_name).'）删除成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'删除成功']);
        }else{
            return response()->json(["code"=>500,'msg'=>'error','data'=>'删除失败']);
        }
    }

    // 搜索智配贴装系统服务项目
    public function zptzServiceProject(Request $request)
    {
        $param['sepr_name'] = ''; //服务项目名称
        if (isset($request['sepr_name']) && !empty($request['sepr_name'])) {
            $param['sepr_name'] = $request['sepr_name']; //服务项目名称
        }
        $param['token'] = config('apiconnect.ZPTZ_TOKEN');
        $url = config('apiconnect.ZPTZ_URL') . '/index.php/Supply/installLine';//智配贴装接口
        $post_return = Common::doPost($param, $url);
        $post_return = json_decode($post_return, true);
        if ($post_return['code'] != 200) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        } else {
            return response()->json(['code'=>200, 'msg'=>'error', 'data'=>$post_return]);
        }
    }

    // 绑定-与其他系统绑定
    public function binding(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyServiceProjectController;
        $error_message = $verify_data->bindingValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

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

        // 查询是否已绑定
        $find_sepr = DB::table('service_project_correlation_system')
                    ->where('spcs_shop_id',$user_info->adm_shop_id)
                    ->where('spcs_sepr_id',$request['spcs_sepr_id'])
                    ->where('spcs_other_sepr_id',$request['spcs_other_sepr_id'])
                    ->where('spcs_system_type',$request['spcs_system_type'])
                    ->where('spcs_shop_id',$user_info->adm_id)
                    ->select('spcs_id', 'spcs_state')
                    ->first();
        if ($find_sepr && $find_sepr->spcs_state == 2) {
            return response()->json(["code"=>200,'msg'=>'success','data'=>'当前服务项目已绑定']);
        }

        $spcs_data['spcs_shop_parent_id'] = $user_info->adm_shop_id;
        $spcs_data['spcs_shop_id'] = $user_info->adm_shop_id;
        $spcs_data['spcs_adm_id'] = $user_info->adm_id;
        $spcs_data['spcs_state'] = 2;
        $spcs_data['spcs_system_type'] = $request['spcs_system_type'];
        $spcs_data['spcs_sepr_id'] = $request['spcs_sepr_id'];
        $spcs_data['spcs_other_sepr_id'] = $request['spcs_other_sepr_id'];
        $spcs_data['sepr_other_sepr_name'] = $request['sepr_other_sepr_name'];
        $spcs_data['spcs_binding_time'] = date('Y-m-d H:i:s');
        $spcs_data['spcs_update_time'] = date('Y-m-d H:i:s');
        $sepr_res = DB::table('service_project_correlation_system')->insert($spcs_data);

        if($sepr_res) {
            Common::addLog($user_info, getRealIp($request), '服务项目','绑定','服务项目：（'.request['sepr_other_sepr_name'].'）绑定成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'绑定成功']);
        }else{
            return response()->json(["code"=>500,'msg'=>'error','data'=>'绑定失败']);
        }
    }

    // 订单外派-搜索服务项目
    public function assignSearch(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyServiceProjectController;
        $error_message = $verify_data->assignSearchValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $search_data = $request->all();
        $list_data = DB::table('service_project')
            ->where('sepr_shop_id', $request['shop_id'])
            ->where('sepr_assign_state', 2)
            ->where('sepr_delete', 1)
            ->where('sepr_state', 1)
            ->where(function($query) use($search_data) {
                if (!empty($search_data['sepr_name'])) {
                    $query->where('sepr_name', 'like', '%'.$search_data['sepr_name'].'%' );
                }
            })
            ->select('sepr_id', 'sepr_name', 'sepr_assign_price','sepr_ordertyp','sepr_recycle')
            ->orderBy('sepr_id', 'asc')
            ->paginate($this->show_count);
        $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_data->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   2023-08-21
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function getConimg(Request $request) {
        $data_com = DB::table('image_config')
            ->where('imco_type', 2)
            ->get()->toArray();
        $goods_data = DB::table('image_config')
            ->where('imco_type', 1)
            ->get()->toArray();
        $data['data_one'] = $goods_data;
        $data['data_two'] = $data_com;
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }
    
    /**|---------------------------------------------------------------------------------
     * @name 批量新增会员导入
     * @param string file 表格数据
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2024/3/19 15:05
     * |---------------------------------------------------------------------------------
    */
    // 批量新增导入
    public function lead(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMemberListController;
        $error_message = $verify_data->leadValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 201, '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' => 201, 'msg' => '文件大小不能超过5M', 'data' => '文件大小不能超过5M']);
            }

            // 限制上传表格类型
            $ext = $file->getClientOriginalExtension(); //文件拓展名
            if ($ext != 'xlsx') {
                return response()->json(['code' => 201, '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 < 3) {
                return response()->json(['code' => 201, 'msg' => '未获取到会员数据', 'data' => '未获取到会员数据']);
            }
            if ($highestRow > 1503) {
                return response()->json(['code' => 201, 'msg' => '一次最多导入1500条数据', 'data' => '一次最多导入1500条数据']);
            }

            // 循环读取excel表格，整合成数组,如果是不指定key的二维,就用$data[i][j]表示。
            DB::beginTransaction();
            $a = 0;
            $error = 0;
            $melo_number = $user_info->adm_shop_id . time();
            $num = 0;
            for ($j = 3; $j <= $highestRow; $j++) {
                $add_mem[$num]['sve_cid'] = $user_info->adm_cid; //所属企业id
                $add_mem[$num]['sve_shop_id'] = $user_info->adm_shop_id; //所属门店id
                $add_mem[$num]['sve_superior_shop_id'] = $shop_id; //所属门店id
                $add_mem[$num]['sve_servname'] = trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue());//服务名称
                if (empty($add_mem[$num]['sve_servname'])) {
                    DB::rollback();
                    $message = '第'.$j.'行服务名称未填写';
                    return response()->json(['code' => 201, 'msg' => '导入失败'.$message, 'data' => '导入失败']);
                }
                $add_mem[$num]['sve_lv_one'] = trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue());//服务一级分类
                $add_mem[$num]['sve_lv_two'] = trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue());//服务二级分类
                $add_mem[$num]['sve_price'] = trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue());//售价
                $add_mem[$num]['sve_check_car'] = trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue());//是否验车(是/否)
                if (empty($add_mem[$num]['sve_check_car'])) {
                    $add_mem[$num]['sve_check_car'] = '否';
                }else{
                    if ($add_mem[$num]['sve_check_car'] !='是' && $add_mem[$num]['sve_check_car'] !='否') {
                        DB::rollback();
                        $message = '第'.$j.'行E列请填写是或否';
                        return response()->json(['code' => 201, 'msg' => '导入失败'.$message, 'data' => '导入失败']);
                    }
                }
                $add_mem[$num]['sve_work_type'] = trim($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue());//是否生成工单(是/否)
                if (empty($add_mem[$num]['sve_work_type'])) {
                    $add_mem[$num]['sve_work_type'] = '否';
                }else{
                    if ($add_mem[$num]['sve_work_type'] !='是' && $add_mem[$num]['sve_work_type'] !='否') {
                        DB::rollback();
                        $message = '第'.$j.'行F列请填写是或否';
                        return response()->json(['code' => 201, 'msg' => '导入失败'.$message, 'data' => '导入失败']);
                    }
                }
                $add_mem[$num]['sve_note'] = trim($objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue());//备注
                $add_mem[$num]['sve_creact_id'] = $user_info->adm_id;//操作人id
                $add_mem[$num]['sve_creact_name'] = $user_info->adm_name;//导入人姓名
                $add_mem[$num]['sve_creact_time'] = date('Y-m-d H:i:s');//导入时间
                $add_mem[$num]['sve_update_time'] = date('Y-m-d H:i:s');//更新时间
                $num++;
            }
            $add_res = DB::table('service_leadhistry')->insert($add_mem);
            if(!$add_res) {
                DB::rollback();
                return response()->json(['code' => 201, 'msg' => '导入失败', 'data' => '导入失败']);
            }

            Common::addLog($user_info, getRealIp($request), '服务列表', '导入', '导入服务信息');
            DB::commit();
            $msg = '上传'.($highestRow - 2).'条，失败'.$error.'条';
            return response()->json(['code' => 200, 'msg' => $msg, 'data' => $melo_number, 'num' => $highestRow - 2]);
        } else {
            return response()->json(['code' => 201, 'msg' => '上传有误，请重新上传！', 'data' => '上传有误，请重新上传！']);
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 执行导入数据
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2024/3/20 16:45
     * |---------------------------------------------------------------------------------
    */
    public function executeLead ( Request $request ){
//        $request['api_token'] = 'dc2bd9541c326c6bcd11f84a37453a7dcb1cd1d2';
        // 获取当前操作账号信息
        $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;
        $leadhistry = DB::table('service_leadhistry')
            ->where('sve_state',1)
            ->where('sve_cid',$user_info->adm_cid)
            ->where('sve_superior_shop_id',$shop_id)
            ->first();
        if($leadhistry){
            DB::beginTransaction();
            $leadhistry = CommonService::dataToArray($leadhistry);
            //判定是否有一级分类
            if(!empty($leadhistry['sve_lv_one'])){
                $sec_id = DB::table('service_class')
                    ->where('sec_name',$leadhistry['sve_lv_one'])
                    ->where('sec_level',1)
                    ->where('sec_cid',$user_info->adm_cid)
                    ->where('sec_superior_shop_id',$shop_id)
                    ->value('sec_id');
                if(!$sec_id){
                    $service_class['sec_name'] = $leadhistry['sve_lv_one'];
                    $service_class['sec_parent_id'] = 0;
                    $service_class['sec_parent_name'] = "顶级分类";
                    $service_class['sec_level'] = 1;
                    $service_class['sec_cid'] = $user_info->adm_cid;
                    $service_class['sec_superior_shop_id'] = $shop_id;
                    $service_class['sec_shop_id'] = $user_info->adm_shop_id;
                    $service_class['sec_creact_id'] = $user_info->adm_id;
                    $service_class['sec_creact_name'] = $user_info->adm_name;
                    $service_class['sec_creact_time'] = date('Y-m-d H:i:s');
                    $service_class['sec_update_time'] = date('Y-m-d H:i:s');
                    $sec_id = DB::table('service_class')->insertGetId($service_class);
                    if(!$sec_id){
                        $addleadhistry['sve_state'] = 3;
                        $addleadhistry['sve_state_value'] = '添加一级分类失败';
                        $addleadhistry['sve_update_time'] = date("Y-m-d H:i:s");
                        $data = DB::table('service_leadhistry')
                            ->where("sve_id",$leadhistry['sve_id'])
                            ->update($addleadhistry);
                        if($data){
                            return response()->json(['code' => 200, 'msg' => '添加分类失败！', 'data' => []]);
                        }else{
                            DB::rollback();
                            return response()->json(['code' => 201, 'msg' => '执行失败请前往导入记录查看原因后继续执行', 'data' => '导入失败']);
                        }
                    }
                }
                $project['sepr_class_id_one'] = $sec_id;
                $sec_name = $leadhistry['sve_lv_one'];
                //判定是否有二级分类
                if(!empty($leadhistry['sve_lv_two'])){
                    $sec_idt = DB::table('service_class')
                        ->where('sec_name',$leadhistry['sve_lv_two'])
                        ->where('sec_level',2)
                        ->where('sec_cid',$user_info->adm_cid)
                        ->where('sec_superior_shop_id',$shop_id)
                        ->value('sec_id');
                    if(!$sec_idt){
                        $service_classt['sec_name'] = $leadhistry['sve_lv_two'];
                        $service_classt['sec_parent_id'] = $sec_id;
                        $service_classt['sec_parent_name'] = $sec_name;
                        $service_classt['sec_level'] = 2;
                        $service_classt['sec_cid'] = $user_info->adm_cid;
                        $service_classt['sec_superior_shop_id'] = $shop_id;
                        $service_classt['sec_shop_id'] = $user_info->adm_shop_id;
                        $service_classt['sec_creact_id'] = $user_info->adm_id;
                        $service_classt['sec_creact_name'] = $user_info->adm_name;
                        $service_classt['sec_creact_time'] = date('Y-m-d H:i:s');
                        $service_classt['sec_update_time'] = date('Y-m-d H:i:s');
                        $sec_idt = DB::table('service_class')->insertGetId($service_classt);
                        if(!$sec_idt){
                            $addleadhistry['sve_state'] = 3;
                            $addleadhistry['sve_state_value'] = '添加二级级分类失败';
                            $addleadhistry['sve_update_time'] = date("Y-m-d H:i:s");
                            $data = DB::table('service_leadhistry')
                                ->where("sve_id",$leadhistry['sve_id'])
                                ->update($addleadhistry);
                            if($data){
                                return response()->json(['code' => 200, 'msg' => '添加分类失败！', 'data' => []]);
                            }else{
                                DB::rollback();
                                return response()->json(['code' => 201, 'msg' => '执行异常请联系管理员', 'data' => '导入失败']);
                            }
                        }
                    }
                    $project['sepr_class_id_two'] = $sec_idt;
                }
            }
            $sepr_id = DB::table('service_project')
                ->where('sepr_name',$leadhistry['sve_servname'])
                ->where('sepr_cid',$user_info->adm_cid)
                ->where('sepr_superior_shop_id',$shop_id)
                ->value('sepr_id');
            if(empty($sepr_id)) {
                $project['sepr_cid'] = $user_info->adm_cid;
                $project['sepr_superior_shop_id'] = $shop_id;
                $project['sepr_shop_id'] = $user_info->adm_shop_id;
                $project['sepr_name'] = $leadhistry['sve_servname'];
                $project['sepr_money'] = $leadhistry['sve_price']*100;
                $project['sepr_order_money'] = $leadhistry['sve_price']*100;
                $project['sepr_remark'] = $leadhistry['sve_note'];
                if ($leadhistry['sve_check_car'] == '是') {
                    $project['sepr_check_car'] = 1;
                } else {
                    $project['sepr_check_car'] = 2;
                }
                if ($leadhistry['sve_work_type'] == '是') {
                    $project['sepr_work_type'] = 1;
                } else {
                    $project['sepr_work_type'] = 2;
                }
//                CommonService::startmysql();
                $rea = DB::table('service_project')->insertGetId($project);
//                $sql = CommonService::showmysql();
                if($rea){
                    $addleadhistry['sve_state'] = 2;
                    $addleadhistry['sve_state_value'] = '添加成功';
                    $addleadhistry['sve_update_time'] = date("Y-m-d H:i:s");
                    $data = DB::table('service_leadhistry')
                        ->where("sve_id",$leadhistry['sve_id'])
                        ->update($addleadhistry);
                    if($data){
                        DB::commit();
                        return redirect('/api/b1/ServiceProject/executeLead');
                        return response()->json(['code' => 200, 'msg' => '操作成功！', 'data' => []]);
                    }else{
                        DB::rollback();
                        return response()->json(['code' => 201, 'msg' => '执行异常请联系管理员', 'data' => '导入失败']);
                    }
                }else{
                    $addleadhistry['sve_state'] = 3;
                    $addleadhistry['sve_state_value'] = '添加服务失败';
                    $addleadhistry['sve_update_time'] = date("Y-m-d H:i:s");
                    $data = DB::table('service_leadhistry')
                        ->where("sve_id",$leadhistry['sve_id'])
                        ->update($addleadhistry);
                    if($data){
                        return response()->json(['code' => 200, 'msg' => '操作失败！', 'data' => []]);
                    }else{
                        DB::rollback();
                        return response()->json(['code' => 201, 'msg' => '执行异常请联系管理员', 'data' => '导入失败']);
                    }
                }
            }else{
                $addleadhistry['sve_state'] = 3;
                $addleadhistry['sve_state_value'] = '服务已存在';
                $addleadhistry['sve_update_time'] = date("Y-m-d H:i:s");
                $data = DB::table('service_leadhistry')
                    ->where("sve_id",$leadhistry['sve_id'])
                    ->update($addleadhistry);
                if($data){
                    return response()->json(['code' => 200, 'msg' => '服务已存在！', 'data' => []]);
                }else{
                    DB::rollback();
                    return response()->json(['code' => 201, 'msg' => '执行异常请联系管理员', 'data' => '导入失败']);
                }
            }
        }else{
            return response()->json(['code' => 202, 'msg' => '已执行完毕！', 'data' => []]);
        }
    }

    public function getClass(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;
        $data = DB::table('sepr_class')
            ->where('shop_id', $shop_id)
            ->get();
        return response()->json(['code' => 200, 'msg' => 'success', 'data' =>$data]);    
    }
}
