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

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\ChannelManage\VerifyVisitListsController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;

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

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyVisitListsController;
        $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->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $search_data = $request->all();
        $list_data = DB::table('visit')
            ->where('vis_cid', $user_info->adm_cid)
            ->where('vis_superior_shop_id', $shop_id)
            ->where('vis_delete', 1)
            ->where(function ($query) use ($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                    $query->whereBetween('vis_create_time', [$search_data['start_time'],$search_data['end_time'].' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['start_time'])) {
                        $query->where('vis_create_time', '>=', $search_data['start_time']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['end_time'])) {
                            $query->where('vis_create_time', '<=', $search_data['end_time'].' 23:59:59');
                        }
                    }
                }
            }) //创建时间
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['vis_name'])) {
                    $query->where('vis_name', 'like', '%'.$search_data['vis_name'].'%');
                }
            })//名称
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['vis_number'])) {
                    $query->where('vis_number', 'like', '%'.$search_data['vis_number'].'%');
                }
            })//编号
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['vis_executor_adm_id'])) {
                    $query->where('vis_executor_adm_id', $search_data['vis_executor_adm_id']);
                }
            })//业务员
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['vis_visvity_nature'])) {
                    $query->where('vis_visvity_nature', $search_data['vis_visvity_nature']);
                }
            })//性质1一次性2周期性
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['vis_state'])) {
                    $query->where('vis_state', $search_data['vis_state']);
                }
            })//状态1未开始2已开始3未完成4已完成
            ->select('vis_id', 'vis_name', 'vis_number', 'vis_executor_adm_id', 'vis_visvity_nature', 'vis_start_time', 'vis_end_time', 'vis_days', 'vis_cycle_number', 'vis_plan_quantity', 'vis_actual_quantity', 'vis_content', 'vis_state', 'vis_create_id', 'vis_create_time')
            ->orderBy('vis_id', 'desc')
            ->paginate($this->show_count);
        
        $data = $list_data->items();
        if ($data) {
            // 获取创建人id
            $executor_adm_id = array_column($data, 'vis_executor_adm_id');//获取业务员id
            $create_id = array_column($data, 'vis_create_id');//获取创建人id
            $adm_id = array_unique(array_merge($executor_adm_id, $create_id));
            // 查询账号信息
            $find_admin = DB::table('admin')
                ->whereIn('adm_id', $adm_id)
                ->select('adm_id', 'adm_name')
                ->get();
            $data_info['admin'] = $find_admin;
            $data_info['executor_adm_id'] = $find_admin;
            // 拜访id
            $vis_id = array_column($data, 'vis_id');
            // 拜访模板内容
            foreach ($data as $key => $value) {
                if ($value->vis_content) {
                    $value->vis_content = json_decode($value->vis_content, true);
                }
            }
            // 查询客户单位信息
            $find_vici = DB::table('visit_clients as vicl')
                ->leftjoin('channel_unit as chun', 'chun.chun_id', '=', 'vicl.vicl_chun_id')
                ->whereIn('vicl_vis_id', $vis_id)
                ->select('vicl_id', 'vicl_chun_id', 'chun_unit_name', 'vicl_plan_quantity', 'vicl_actual_quantity')
                ->get();
            $data_info['visit_clients'] = $find_vici;
        }

        $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'] = $data;                //返回数据

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info, 'list_button'=>$list_button]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

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

        // 判断名称是否存在
        $find_vis_id = DB::table('visit')
            ->where('vis_cid', $user_info->adm_cid)
            ->where('vis_superior_shop_id', $shop_id)
            ->where('vis_delete', 1)
            ->where('vis_name', $request['vis_name'])
            ->select('vis_id')
            ->first();
        if ($find_vis_id) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'拜访名称已存在']);
        }

        // 新增拜访计划
        $vis_data['vis_cid'] = $user_info->adm_cid;
        $vis_data['vis_shop_id'] = $user_info->adm_shop_id;
        $vis_data['vis_superior_shop_id'] = $shop_id;
        $vis_data['vis_create_id'] = $user_info->adm_id;
        $vis_data['vis_number'] = 'BF' . rand(10, 99) . date('mdHis') . rand(100000, 999999); //编号;
        $vis_data['vis_name'] = $request['vis_name']; //名称;
        $vis_data['vis_executor_adm_id'] = $request['vis_executor_adm_id'];//业务员
        $vis_data['vis_visvity_nature'] = $request['vis_visvity_nature'];//性质1一次性2周期性
        if ($request['vis_visvity_nature'] == '1') {//性质1一次性
            if (empty($request['vis_start_time']) || empty($request['vis_end_time'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'开始时间和结束时间必填']);
            }
            $vis_data['vis_start_time'] = $request['vis_start_time'];//开始时间
            $vis_data['vis_end_time'] = $request['vis_end_time'];//截止时间
        } else {//周期性
            if (empty($request['vis_start_time']) || empty($request['vis_days']) || !is_numeric($request['vis_days'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'开始时间和天数必填']);
            }
            $vis_data['vis_start_time'] = $request['vis_start_time'];//开始时间
            $vis_data['vis_days'] = $request['vis_days'];//天数
        }
        /**
         * 处理表单数据
         *  表单json数据字段说明
            {
                "key":"商品编号",//信息名称
                "value":"6922266440090",//信息内容
                "tips":"请输入文章",//信息提示
                "type":"1",//类型1普通文本2多行文本3上传图片
                "show":"1",//1显示2隐藏
                "required":"1",//是否必填1必填2选填
            }
         */
        foreach ($request['info_name'] as $key => $value) {
            if (empty($value) || !in_array($request['info_show'][$key], [1,2]) || !in_array($request['info_required'][$key], [1,2]) || !in_array($request['info_type'][$key], [1,2,3])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'信息项存在空项']);
            }
            $table_content[$key]['key'] = $value;
            $table_content[$key]['value'] = $request['info_content'][$key];//内容
            $table_content[$key]['tips'] = $request['info_tips'][$key];//提示
            $table_content[$key]['type'] = $request['info_type'][$key];
            $table_content[$key]['show'] = $request['info_show'][$key];
            $table_content[$key]['required'] = $request['info_required'][$key];
        }
        $vis_data['vis_content'] = json_encode($table_content);
        
        DB::beginTransaction();
        $vis_id =  DB::table('visit')->insertGetId($vis_data);

        // 性质2周期性,修改周期序号
        if ($request['vis_visvity_nature'] == '2') {
            $time = date('Y-m-d H:i:s');
            $expire_time = date('Y-m-d', strtotime($request['vis_start_time'] . ' + ' . $request['vis_days'] . ' day'));
            $vis_data['vis_end_time'] = $expire_time;
            $vis_data['vis_update_time'] = date('Y-m-d H:i:s');
            if ($time > $expire_time) {
                DB::table('visit')
                    ->where('vis_id', $vis_id)
                    ->increment('vis_cycle_number', 1, $vis_data);
            } else {
                $vis_data['vis_cycle_number'] = 1; //周期序号
                $vis_data['vis_end_time'] = date('Y-m-d', strtotime($request['vis_start_time'] . ' + ' . $request['vis_days'] . ' day'));
                $vis_data['vis_update_time'] = date('Y-m-d H:i:s');
                DB::table('visit')
                    ->where('vis_id', $vis_id)
                    ->update($vis_data);
            }
        }
        // 2 新增拜访客户
        $updata_data['vis_plan_quantity'] = 0;//计划拜访总次数
        foreach ($request['vicl_chun_id'] as $kk => $vv) {
            if (empty($vv) || !is_numeric($request['vicl_plan_quantity'][$kk])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'信息项存在空项']);
            }
            $vicl_data[$kk]['vicl_vis_id'] = $vis_id;
            $vicl_data[$kk]['vicl_chun_id'] = $vv;
            $vicl_data[$kk]['vicl_plan_quantity'] = $request['vicl_plan_quantity'][$kk];
            $updata_data['vis_plan_quantity'] += $request['vicl_plan_quantity'][$kk];//计划拜访总次数
            $updata_data['vis_update_time'] = date('Y-m-d H:i:s');
        }

        $vis_updata_data = DB::table('visit')
            ->where('vis_id', $vis_id)
            ->update($updata_data);

        $vicl_id =  DB::table('visit_clients')->insert($vicl_data);
        
        if ($vis_id && $vicl_id && $vis_updata_data) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '拜访列表', '新增', '新增拜访计划：'.$request['vis_name'].'成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'新增拜访计划成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'新增拜访计划失败']);
        }
    }

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

        if ($request['type'] == '1') {
            $find_vis = DB::table('visit')
                ->where('vis_id', $request['vis_id'])
                ->select('vis_id', 'vis_name', 'vis_executor_adm_id', 'vis_visvity_nature', 'vis_start_time', 'vis_end_time', 'vis_days', 'vis_cycle_number', 'vis_content')
                ->first();
            // 获取业务员名称
            $find_vis->adm_name = DB::table('admin')
                ->where('adm_id', $find_vis->vis_executor_adm_id)
                ->value('adm_name');
            $find_vis->vis_content = json_decode($find_vis->vis_content, true);
            // 获取拜访客户信息
            $find_vicl = DB::table('visit_clients as vicl')
                ->leftjoin('channel_unit as chun', 'chun.chun_id', '=', 'vicl.vicl_chun_id')
                ->where('vicl_vis_id', $request['vis_id'])
                ->select('vicl_id', 'vicl_chun_id', 'chun_unit_name', 'vicl_plan_quantity')
                ->get();
            $data['visit'] = $find_vis;
            $data['visit_clients'] = $find_vicl;
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }

        // 验证数据
        $verify_data = new VerifyVisitListsController;
        $error_message = $verify_data->addValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 判断移动端任务是否进行中,是,不允许编辑
        $webapp = DB::table('visit_record')
            ->where('vire_vis_id', $request['vis_id'])
            ->where('vire_state', '!=', 4)
            ->select('vire_content')
            ->get()
            ->toArray();
        if (!empty($webapp)) {
            return response()->json(['code'=>500, 'msg'=>'error', '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;

        // 判断名称是否存在
        $find_vis_id = DB::table('visit')
            ->where('vis_id', '<>', $request['vis_id'])
            ->where('vis_cid', $user_info->adm_cid)
            ->where('vis_superior_shop_id', $shop_id)
            ->where('vis_delete', 1)
            ->where('vis_name', $request['vis_name'])
            ->select('vis_id')
            ->first();
        if ($find_vis_id) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'拜访名称已存在']);
        }

        // 编辑拜访计划
        $vis_data['vis_name'] = $request['vis_name'];//名称
        $vis_data['vis_executor_adm_id'] = $request['vis_executor_adm_id'];//业务员
        $vis_data['vis_visvity_nature'] = $request['vis_visvity_nature'];//性质1一次性2周期性
        $vis_data['vis_plan_quantity'] = 0;
        if ($request['vis_visvity_nature'] == '1') {//性质1一次性
            $vis_data['vis_start_time'] = $request['vis_start_time'];//开始时间
            $vis_data['vis_end_time'] = $request['vis_end_time'];//截止时间
        } else {//周期性
            $vis_data['vis_start_time'] = $request['vis_start_time'];//开始时间
            $vis_data['vis_days'] = $request['vis_days'];//天数
        }
        /**
         * 处理表单数据
         *  表单json数据字段说明
            {
                "key":"商品编号",//信息名称
                "value":"6922266440090",//信息内容
                "tips":"请输入文字",//信息提示
                "type":"1",//类型1普通文本2多行文本3上传图片
                "show":"1",//1显示2隐藏
                "required":"1",//是否必填1必填2选填
            }
         */
        foreach ($request['info_name'] as $key => $value) {
            if (empty($value) || !in_array($request['info_show'][$key], [1,2]) || !in_array($request['info_required'][$key], [1,2]) || !in_array($request['info_type'][$key], [1,2,3])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'信息项存在空项']);
            }
            $table_content[$key]['key'] = $value;
            $table_content[$key]['value'] = $request['info_content'][$key];
            $table_content[$key]['tips'] = $request['info_tips'][$key];//提示
            $table_content[$key]['type'] = $request['info_type'][$key];
            $table_content[$key]['show'] = $request['info_show'][$key];
            $table_content[$key]['required'] = $request['info_required'][$key];
        }
        $vis_data['vis_content'] = json_encode($table_content);
        $vis_data['vis_update_time'] = date('Y-m-d H:i:s');
        
        DB::beginTransaction();

        $vis_id =  DB::table('visit')
            ->where('vis_id', $request['vis_id'])
            ->update($vis_data);
        
        // 性质2周期性,修改周期序号
        if ($request['vis_visvity_nature'] == '2') {
            $time = date('Y-m-d H:i:s');
            $expire_time = date('Y-m-d', strtotime($request['vis_start_time'] . ' + ' . $request['vis_days'] . ' day'));
            $vis_data['vis_end_time'] = $expire_time;
            $vis_data['vis_update_time'] = date('Y-m-d H:i:s');
            if ($time > $expire_time) {
                DB::table('visit')
                    ->where('vis_id', $request['vis_id'])
                    ->increment('vis_cycle_number', 1, $vis_data);
            } else {
                $update['vis_cycle_number'] = 1; //周期序号
                $update['vis_end_time'] = date('Y-m-d', strtotime($request['vis_start_time'] . ' + ' . $request['vis_days'] . ' day'));
                $update['vis_update_time'] = date('Y-m-d H:i:s');
                DB::table('visit')
                    ->where('vis_id', $request['vis_id'])
                    ->update($update);
            }
        }

        // 2 编辑拜访客户
        // 查询出原来拜访客户实际次数
        $actual_quantity = DB::table('visit_clients')
            ->where('vicl_vis_id', $request['vis_id'])
            ->select('vicl_actual_quantity')
            ->get()
            ->toArray();
        $quantity = array_column($actual_quantity, 'vicl_actual_quantity');
        $vis_plan_quantity = 0;//计划拜访总次数
        foreach ($request['vicl_chun_id'] as $kk => $vv) {
            if (empty($vv) || !is_numeric($request['vicl_plan_quantity'][$kk])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'信息项存在空项']);
            }
            $vicl_data[$kk]['vicl_vis_id'] = $request['vis_id'];
            $vicl_data[$kk]['vicl_chun_id'] = $vv;
            $vicl_data[$kk]['vicl_plan_quantity'] = $request['vicl_plan_quantity'][$kk];
            if (isset($quantity[$kk])) {
                $vicl_data[$kk]['vicl_actual_quantity'] = $quantity[$kk];
            } else {
                $vicl_data[$kk]['vicl_actual_quantity'] = 0;
            }
            $vicl_data[$kk]['vicl_update_time'] = date('Y-m-d H:i:s');
            $vis_plan_quantity += $request['vicl_plan_quantity'][$kk];//计划拜访总次数
        }
        // 修改拜访表数据
        $sql = 'UPDATE `faster_visit` SET ';
        $plan_quantity_sql = '';
        $time_sql = '';
        $ids = '';
        // 计划拜访次数更改
        if ($vis_plan_quantity) {
            $plan_quantity_sql = $plan_quantity_sql.' WHEN '.$request['vis_id'].' THEN `vis_plan_quantity` + '.$vis_plan_quantity;
            $time_sql = $time_sql.' WHEN '.$request['vis_id'].' THEN "'.date('Y-m-d H:i:s').'"';
        
            $ids = $ids . $request['vis_id'].',';
            $sql = $sql .' `vis_plan_quantity`=  CASE `vis_id` '.$plan_quantity_sql.' END,';
        }
        
        $sql = $sql .' `vis_update_time`=  CASE `vis_id` '.$time_sql.' END';
        $sql = $sql . ' WHERE `vis_id` = '.trim($ids, ',');
        $update_res = DB::update($sql);
        if (!$update_res) {
            DB::rollback();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'编辑失败2']);
        }
        // 删除原来的拜访客户
        $vicl_del_id =  DB::table('visit_clients')
            ->where('vicl_vis_id', $request['vis_id'])
            ->delete();

        // 新增拜访客户
        $vicl_id = DB::table('visit_clients')->insert($vicl_data);

        if ($vis_id && $vicl_id && $vicl_del_id) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '拜访列表', '编辑', '编辑拜访计划：'.$request['vis_name'].'成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'编辑拜访计划成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'编辑拜访计划失败']);
        }
    }

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

        // 查询信息
        $find_vis = DB::table('visit')
            ->where('vis_id', $request['vis_id'])
            ->select('vis_name', 'vis_state')
            ->first();

        // 未完成的都可以删除
        if ($find_vis->vis_state != '5') {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前拜访尚未终止,无法删除']);
        }

        // 删除
        $update_data['vis_delete'] = 2;//是否删除1正常2删除
        $update_data['vis_update_time'] = date('Y-m-d H:i:s');
        $vis_res = DB::table('visit')
            ->where('vis_id', $request['vis_id'])
            ->update($update_data);

        if ($vis_res) {
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            Common::addLog($user_info, getRealIp($request), '拜访列表', '删除', '计划名称：（'.$find_vis->vis_name.'）删除成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'删除成功']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'删除失败']);
        }
    }

    // 终止
    public function terminate(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyVisitListsController;
        $error_message = $verify_data->deleteValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 查询信息
        $find_vis = DB::table('visit')
            ->where('vis_id', $request['vis_id'])
            ->select('vis_name', 'vis_state')
            ->first();

        $update_data['vis_state'] = 5;//状态1未开始2已开始3未完成4已完成5终止
        $update_data['vis_update_time'] = date('Y-m-d H:i:s');

        $vire_update_data['vire_state'] = 5;//状态1出发2抵达3结束打卡4提交数据5终止
        $vire_update_data['vire_update_time'] = date('Y-m-d H:i:s');

        DB::beginTransaction();
        // 修改拜访状态值
        $vis_res = DB::table('visit')
            ->where('vis_id', $request['vis_id'])
            ->update($update_data);

        // 修改拜访记录状态值
        $vire_ids = DB::table('visit_record')
            ->where('vire_vis_id', $request['vis_id'])
            ->select('vire_id')
            ->get()
            ->toArray();
        if (!empty($vire_ids)) {
            $vire_id = DB::table('visit_record')
                ->where('vire_vis_id', $request['vis_id'])
                ->update($vire_update_data);
            if (!$vire_id) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'终止失败']);
            }
        }

        if ($vis_res) {
            DB::commit();
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            Common::addLog($user_info, getRealIp($request), '拜访列表', '终止', '计划名称：（'.$find_vis->vis_name.'）终止成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'终止成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'终止失败']);
        }
    }

    // 详情
    public function info(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyVisitListsController;
        $error_message = $verify_data->deleteValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $find_vis = DB::table('visit')
            ->where('vis_id', $request['vis_id'])
            ->select(
                'vis_id',
                'vis_name',
                'vis_executor_adm_id',
                'vis_visvity_nature',
                'vis_start_time',
                'vis_end_time',
                'vis_days',
                'vis_cycle_number',
                'vis_content'
            )
            ->first();
        
        // 获取业务员名称
        $find_vis->adm_name = DB::table('admin')
            ->where('adm_id', $find_vis->vis_executor_adm_id)
            ->value('adm_name');
        
        $find_vis->vis_content = json_decode($find_vis->vis_content, true);

        // 获取拜访客户信息
        $find_vicl = DB::table('visit_clients as vicl')
            ->leftjoin('channel_unit as chun', 'chun.chun_id', '=', 'vicl.vicl_chun_id')
            ->where('vicl_vis_id', $request['vis_id'])
            ->select('vicl_id', 'vicl_chun_id', 'chun_unit_name', 'vicl_plan_quantity')
            ->get();
        $data['visit'] = $find_vis;
        $data['visit_clients'] = $find_vicl;
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }

    // 拜访记录
    public function visitRecord(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyVisitListsController;
        $error_message = $verify_data->deleteValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $search_data = $request->all();
        if (empty($search_data['vis_cycle_number'])) {
            $find_vis_data = DB::table('visit')
                ->where('vis_id', $request['vis_id'])
                ->select('vis_visvity_nature', 'vis_cycle_number')
                ->first();
            $search_data['vis_cycle_number'] = $find_vis_data->vis_cycle_number;
        }

        // 获取拜访记录
        $list_data = DB::table('visit_record as vire')
            ->leftjoin('channel_unit as chun', 'chun.chun_id', '=', 'vire.vire_chun_id')
            ->where('vire_vis_id', $request['vis_id'])
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['chun_unit_name'])) {
                    $query->where('chun_unit_name', 'like', '%'.$search_data['chun_unit_name'].'%');
                }
            })//名称
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['vis_cycle_number'])) {
                    $query->where('vire_cycle_number', $search_data['vis_cycle_number']);
                }
            })//周期序号
            ->select('vire_id', 'vire_chun_id', 'chun_unit_name', 'vire_executor_adm_id', 'vire_quantity', 'vire_start_time', 'vire_clock_time', 'vire_end_time', 'vire_state', 'vire_content')
            ->orderBy('vire_id', 'desc')
            ->paginate($this->show_count);
        
        $data = $list_data->items();
        if ($data) {
            // 获取创建人id
            $executor_adm_id = array_column($data, 'vire_executor_adm_id');//获取业务员id
            // 查询账号信息
            $find_admin = DB::table('admin')
                ->whereIn('adm_id', $executor_adm_id)
                ->select('adm_id', 'adm_name')
                ->get();
            $data_info['admin'] = $find_admin;
            // 拜访模板内容
            foreach ($data as $key => $value) {
                if ($value->vire_content) {
                    $value->vire_content = json_decode($value->vire_content, true);
                }
            }
            // 查询客户单位信息
            $find_vici = DB::table('visit_clients as vicl')
                ->leftjoin('channel_unit as chun', 'chun.chun_id', '=', 'vicl.vicl_chun_id')
                ->where('vicl_vis_id', $request['vis_id'])
                ->select('vicl_id', 'vicl_chun_id', 'chun_unit_name', 'vicl_plan_quantity', 'vicl_actual_quantity')
                ->get();
            $data_info['visit_clients'] = $find_vici;
        }

        $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'] = $data;                //返回数据

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info, 'list_button'=>$list_button]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    // 行驶路线
    public function runningRoute(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyVisitListsController;
        $error_message = $verify_data->runningRouteValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前业务员的公司id
        $adm_cid = DB::table('admin')
            ->where('adm_id', $request['vire_executor_adm_id'])
            ->value('adm_cid');
        
        // 获取当前年月
        $now_time = substr(date('Ym'), -4);

        // 获取表名
        $table_name = DB::table('table_link_visit')
            ->where('talv_codeid', '5000'.$adm_cid)
            ->where('talv_yemo', $now_time)
            ->value('talv_table_name');
        
        // 获取业务员出发和抵达的经纬度
        $location = DB::table($table_name.'_location_visit')
            ->where('lovi_adm_id', $request['vire_executor_adm_id'])
            ->where('lovi_vire_id', $request['vire_id'])
            ->orderBy('lovi_id', 'desc')
            ->select('lovi_id', 'lovi_longitude', 'lovi_latitude')
            ->paginate(300);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$location->items()]);
    }
}
