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

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\SystemsManage\VerifyVirtualStoresController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Crypt;
use App\Http\Models\Api\Common;
use App\Http\Controllers\Api\YongYou\YongYouController;

// 虚拟加盟店
class VirtualStoresController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyVirtualStoresController;
        $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']);
        if ($user_info->shop_superior_id == 0) {
            $shop_id = $user_info->adm_shop_id;
        } else {
            $shop_id = $user_info->shop_superior_id;
        }

        $search_data = $request->all();
        $list_data = DB::table('virtual_shop as vs')
            ->leftjoin('channel_unit as a', 'a.chun_id', '=', 'vs.vish_chun_id')
            ->where('vish_cid', $user_info->adm_cid)
            ->where('vish_superior_shop_id', $shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['vish_store_name'])) {
                    $query->where('vish_store_name', 'like', '%' . $search_data['vish_store_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['vish_name'])) {
                    $query->where('adm_name', 'like', '%' . $search_data['vish_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['vish_phone'])) {
                    $query->where('vish_phone', 'like', '%' . $search_data['vish_phone'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['address'])) {
                    $query->where('vish_address', 'like', '%' . $search_data['address'] . '%');
                }
            })
            ->orwhere(function ($query) use ($search_data) {
                if (!empty($search_data['address'])) {
                    $query->where('vish_province', 'like', '%' . $search_data['address'] . '%');
                }
            })
            ->orwhere(function ($query) use ($search_data) {
                if (!empty($search_data['address'])) {
                    $query->where('vish_city', 'like', '%' . $search_data['address'] . '%');
                }
            })
            ->orwhere(function ($query) use ($search_data) {
                if (!empty($search_data['address'])) {
                    $query->where('vish_county', 'like', '%' . $search_data['address'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['vish_state'])) {
                    $query->where('vish_state', $search_data['vish_state']);
                }
            })
            ->select('vish_id', 'vish_store_name', 'chun_name as vish_name', 'chun_phone as vish_phone', 'vish_province', 'vish_city', 'vish_county', 'vish_address', 'vish_state', 'vish_create_time')
            ->orderBy('vish_id', 'desc')
            ->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 (!empty($data_info['data'])) {
            foreach ($data_info['data'] as $key => $value) {
                $data_info['data'][$key]->account_count = DB::table('virtual_adm')
                    ->where('viad_vish_id', $value->vish_id)
                    ->count();
            }
        }

        // 获取当前列表下的按钮
        $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 VerifyVirtualStoresController;
        $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']);

        DB::beginTransaction();
        $vish['vish_cid'] = $user_info->adm_cid;
        $vish['vish_superior_shop_id'] = $user_info->adm_shop_id;

        $vish['vish_name'] = $request['vish_name'];
        $vish['vish_phone'] = $request['vish_phone'];
        // 客户单位表
        $chun_data = DB::table('channel_unit')
            ->where('chun_id', $request['chun_id'])
            ->first(['chun_province', 'chun_city', 'chun_county', 'chun_address', 'chun_unit_name']);
        $vish['vish_store_name'] = $chun_data->chun_unit_name;
        $vish['vish_province'] = $chun_data->chun_province;
        $vish['vish_city'] = $chun_data->chun_city;
        $vish['vish_county'] = $chun_data->chun_county;
        $vish['vish_address'] = $chun_data->chun_address;
        $vish['vish_chun_id'] = $request['chun_id'];

        // 判断加盟店名称是否存在
        $store_name = DB::table('virtual_shop')
            ->where('vish_cid', $user_info->adm_cid)
            ->where('vish_store_name', $chun_data->chun_unit_name)
            ->value('vish_store_name');
        if ($store_name) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'虚拟加盟店名称已存在']);
        }

        $chun_res = DB::table('channel_unit')
            ->where('chun_id', $request['chun_id'])
            ->update(['chun_type' => 2, 'chun_update_time' => date('Y-m-d H:i:s')]);

        // 新增虚拟加盟店
        $vish_id =  DB::table('virtual_shop')->insertGetId($vish);

        // $adm_id = $this->detectionAdm($user_info, $request['vish_phone'], $request['vish_name'], $request['adm_password'], $vish_id);

        // 3.4 将新增的账号id更新到门店表的 shop_adm_id 字段
        // $shop_save_res = DB::table('virtual_shop')
        //     ->where('vish_id', $vish_id)
        //     ->update(['vish_adm_id' => $adm_id,'vish_update_time'=>date('Y-m-d H:i:s')]);
        if ($vish_id && $chun_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '虚拟加盟店', '新增', '新增虚拟加盟店：' . $request['shop_store_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 VerifyVirtualStoresController;
        $error_message = $verify_data->editValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

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

        // 3 编辑虚拟加盟店信息
        DB::beginTransaction();

        $adm_id = $this->detectionAdm($user_info, $request['vish_phone'], $request['vish_name'], $request['adm_password'], $request['vish_id']);

        // 判断手机号是否存在
        $store_name = DB::table('virtual_shop')
            ->where('vish_id', $request['vish_id'])
            ->select('vish_store_name', 'vish_adm_id', 'vish_chun_id')
            ->first();
        // 判断加盟店名称是否存在
        $store_res = DB::table('virtual_shop')
            ->where('vish_cid', $user_info->adm_cid)
            ->where('vish_id', '<>', $request['vish_id'])
            ->where('vish_store_name', $store_name->vish_store_name)
            ->select('vish_store_name', 'vish_adm_id')
            ->first();
        if ($store_res) {
            return response()->json(["code"=>500, 'msg'=>'error', 'data'=>'客户单位名称重复']);
        }

        // 客户单位表
        $chun_data = DB::table('channel_unit')
            ->where('chun_id', $store_name->vish_chun_id)
            ->first(['chun_province', 'chun_city', 'chun_county', 'chun_address', 'chun_unit_name']);

        $shop_save_data['vish_store_name'] = $chun_data->chun_unit_name;
        $shop_save_data['vish_province'] = $chun_data->chun_province;
        $shop_save_data['vish_city'] = $chun_data->chun_city;
        $shop_save_data['vish_county'] = $chun_data->chun_county;
        $shop_save_data['vish_address'] = $chun_data->chun_address;
        $shop_save_data['vish_name'] = $request['vish_name'];
        $shop_save_data['vish_phone'] = $request['vish_phone'];
        $shop_save_data['vish_adm_id'] = $adm_id;
        $shop_save_data['vish_update_time'] = date('Y-m-d H:i:s');

        $shop_save_res = DB::table('virtual_shop')
            ->where('vish_id', $request['vish_id'])
            ->update($shop_save_data);

        if ($shop_save_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '加盟店', '编辑', '编辑加盟店：' . $request['vish_store_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 VerifyVirtualStoresController;
        $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_shop = DB::table('virtual_shop')
            ->whereIn('vish_id', $request['vish_id'])
            ->select('vish_store_name')
            ->get();
        foreach ($find_shop as $key => $value) {
            $shop_store_name[] = $value->vish_store_name;
        }

        // 启用
        $update_data['vish_state'] = 1; //状态1启用2停用
        $update_data['vish_update_time'] = date('Y-m-d H:i:s');
        $shop_res = DB::table('virtual_shop')->whereIn('vish_id', $request['vish_id'])->update($update_data);

        if ($shop_res) {
            Common::addLog($user_info, getRealIp($request), '虚拟加盟店', '启用', '启用虚拟加盟店：（' . implode(',', $shop_store_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 VerifyVirtualStoresController;
        $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_shop = DB::table('virtual_shop')
            ->whereIn('vish_id', $request['vish_id'])
            ->select('vish_store_name')
            ->get();
        foreach ($find_shop as $key => $value) {
            $shop_store_name[] = $value->vish_store_name;
        }

        // 停用
        $update_data['vish_state'] = 2; //状态1启用2停用
        $update_data['vish_update_time'] = date('Y-m-d H:i:s');
        $shop_res = DB::table('virtual_shop')->whereIn('vish_id', $request['vish_id'])->update($update_data);

        if ($shop_res) {
            Common::addLog($user_info, getRealIp($request), '虚拟加盟店', '停用', '停用虚拟加盟店：（' . implode(',', $shop_store_name) . '）停用成功');
            return response()->json(["code"=>200, 'msg'=>'success', 'data'=>'停用成功']);
        } else {
            return response()->json(["code"=>500, 'msg'=>'error', 'data'=>'停用失败']);
        }
    }

    // 账号列表
    public function accountList(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $search_data = $request->all();
        $list_data = DB::table('virtual_adm as va')
            ->leftjoin('admin as a', 'a.adm_id', '=', 'va.viad_adm_id')
            ->leftjoin('virtual_shop as vs', 'vs.vish_id', '=', 'va.viad_vish_id')
            ->where('vish_superior_shop_id', $user_info->adm_shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['adm_name'])) {
                    $query->where('adm_name', 'like', '%' . $search_data['adm_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['vish_store_name'])) {
                    $query->where('vish_store_name', 'like', '%' . $search_data['vish_store_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['viad_state'])) {
                    $query->where('viad_state', $search_data['viad_state']);
                }
            })
            ->where('adm_shop_id', $user_info->adm_shop_id)
            ->select('adm_phone', 'adm_name', 'viad_state', 'vish_store_name', 'viad_create_time', 'viad_id')
            ->orderBy('viad_id', 'desc')
            ->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();                //返回数据

        // 获取当前列表下的按钮
        $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'=>'暂无数据', 'list_button'=>$list_button]);
        }
    }

    // 检索技师
    public function searchingAccount(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyVirtualStoresController;
        $error_message = $verify_data->searchingAccountValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $data = DB::table('admin')
            ->where('adm_phone', $request['phone'])
            ->first(['adm_phone', 'adm_name']);
        if (empty($data)) {
            $data = (object)[];
        }
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }

    // 添加技师
    public function addAccount(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyVirtualStoresController;
        $error_message = $verify_data->addAccountValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

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

        $detection_res = $this->detectionAdm($user_info, $request['adm_phone'], $request['adm_name'], $request['adm_password'], $request['vish_id']);
        if ($detection_res['code'] != 500) {
            if (config('apisystem.SYNC_STATE')) {
                // 与速电系统同步技师数据
                $system_shop = DB::table('shop_correlation')
                    ->where('shco_shop_id', $user_info->adm_shop_id)
                    ->first(['shco_system_shop_id', 'shco_state']);
                if (isset($system_shop->shco_state) && $system_shop->shco_state == 2) {
                    $param['id'] = $detection_res; //技师id
                    $param['name'] = $request['adm_name']; //技师姓名
                    $param['phone'] = $request['adm_phone']; //技师手机号
                    $param['store_id'] = $system_shop->shco_system_shop_id; //第三方系统的门店id
                    $param['time'] = date('Y-m-d H:i:s');
                    $param['type'] = 1;
                    $param['token'] = config('apisystem.sd_token');
                    $url = config('apisystem.sd_server_name') . '/index.php/sync_install_persion';
                    $doPost_res = Common::doPost($param, $url);
                    $doPost_res = json_decode($doPost_res);
                    if ($doPost_res->code != 200) {
                        DB::rollBack();
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'失败']);
                    }
                }
            }
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '虚拟加盟店', '添加技师', '技师（' . $request['adm_name'] . ':' . $request['adm_phone'] . '）添加成功');
            return response()->json(["code"=>200, 'msg'=>'success', 'data'=>'添加成功']);
        } else {
            DB::rollBack();
            return response()->json($detection_res);
        }
    }

    // 启用技师
    public function startAccount(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 查询加盟店信息
        $list_data = DB::table('virtual_adm as va')
            ->leftjoin('admin as a', 'a.adm_id', '=', 'va.viad_adm_id')
            ->leftjoin('admin_shop_role as asr', 'asr.adm_id', '=', 'a.adm_id')
            ->whereIn('viad_id', $request['viad_id'])
            ->where('asr.shop_id', $user_info->adm_shop_id)
            ->select('adm_name')
            ->orderBy('viad_id', 'desc')
            ->get();
        foreach ($list_data as $key => $value) {
            $name[] = $value->adm_name;
        }

        // 启用
        $update_data['viad_state'] = 1; //状态1启用2停用
        $update_data['viad_update_time'] = date('Y-m-d H:i:s');
        $shop_res = DB::table('virtual_adm')
            ->whereIn('viad_id', $request['viad_id'])
            ->update($update_data);

        if ($shop_res) {
            Common::addLog($user_info, getRealIp($request), '虚拟加盟店->技师列表', '启用', '启用技师：（' . implode(',', $name) . '）启用成功');
            return response()->json(["code"=>200, 'msg'=>'success', 'data'=>'启用成功']);
        } else {
            return response()->json(["code"=>500, 'msg'=>'error', 'data'=>'启用失败']);
        }
    }

    // 停用技师
    public function stopAccount(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 查询加盟店信息
        $list_data = DB::table('virtual_adm as va')
            ->leftjoin('admin as a', 'a.adm_id', '=', 'va.viad_adm_id')
            ->leftjoin('admin_shop_role as asr', 'asr.adm_id', '=', 'a.adm_id')
            ->whereIn('viad_id', $request['viad_id'])
            ->where('asr.shop_id', $user_info->adm_shop_id)
            ->select('adm_name')
            ->orderBy('viad_id', 'desc')
            ->get();
        foreach ($list_data as $key => $value) {
            $name[] = $value->adm_name;
        }

        // 停用
        $update_data['viad_state'] = 2; //状态1启用2停用
        $update_data['viad_update_time'] = date('Y-m-d H:i:s');
        $shop_res = DB::table('virtual_adm')
            ->whereIn('viad_id', $request['viad_id'])
            ->update($update_data);

        if ($shop_res) {
            Common::addLog($user_info, getRealIp($request), '虚拟加盟店->技师列表', '停用', '停用技师：（' . implode(',', $name) . '）停用成功');
            return response()->json(["code"=>200, 'msg'=>'success', 'data'=>'停用成功']);
        } else {
            return response()->json(["code"=>500, 'msg'=>'error', 'data'=>'停用失败']);
        }
    }

    // 查看技师
    public function lookAccount(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 查询加盟店信息
        $list_data = DB::table('virtual_adm as va')
            ->leftjoin('admin as a', 'a.adm_id', '=', 'va.viad_adm_id')
            ->leftjoin('admin_shop_role as asr', 'asr.adm_id', '=', 'a.adm_id')
            ->where('viad_vish_id', $request['vish_id'])
            ->where('asr.shop_id', $user_info->adm_shop_id)
            ->select('adm_name', 'adm_phone')
            ->orderBy('viad_id', 'desc')
            ->get();
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_data]);
    }

    // 检测账号表是否存在
    public function detectionAdm(
        $user_info,
        $adm_phone,
        $adm_name,
        $adm_password,
        $vish_id
    ) {
        $adm = DB::table('admin')
            ->leftJoin('admin_shop_role as asr', 'asr.adm_id', '=', 'admin.adm_id')
            ->where('asr.shop_id', $user_info->adm_shop_id)
            ->where('admin.adm_phone', $adm_phone)
            ->first(['admin.adm_id', 'admin.adm_type']);
        $account = 'os' . time();
        if (empty($adm)) {
            $adm_id = DB::table('admin')
                ->where('adm_phone', $adm_phone)
                ->value('adm_id');
            if(empty($adm_id)) {
                $adm_password = md5($adm_password . 'faster123456');
                $admin_add_data = [
                    'adm_cid' => $user_info->adm_cid,
                    'adm_superior_shop_id' => $user_info->adm_shop_id,
                    'adm_shop_id' => $user_info->adm_shop_id,
                    'adm_leave' => 3,
                    'adm_phone' => $adm_phone,
                    'adm_account' => $account,
                    'adm_password' => $adm_password,
                    'adm_name' => $adm_name,
                    'adm_creator_id' => $user_info->adm_id,
                    'adm_type' => 2
                ];
                // 新增账号
                $adm_id =  DB::table('admin')->insertGetId($admin_add_data);
            }

            //新增账号门店权限关系表
            $insertAdminShopRoleData = [
                'adm_id' => $adm_id,
                'shop_cid' => $user_info->adm_cid,
                'superior_shop_id' => $user_info->adm_shop_id,
                'shop_id' => $user_info->adm_shop_id,
                'adm_shop_leave' => 3,
                'phone' => $adm_phone,
                'create_time' => date("Y-m-d H:i:s", time()),
                'update_time' => date("Y-m-d H:i:s", time()),
            ];
            $admin_shop_role_id =  DB::table('admin_shop_role')->insertGetId($insertAdminShopRoleData);

            // 3.4 将新增的账号id更新到门店表的 shop_adm_id 字段
            $save_res = DB::table('virtual_shop')
                ->where('vish_id', $vish_id)
                ->update(['vish_adm_id' => $adm_id, 'vish_update_time' => date('Y-m-d H:i:s')]);
        } else {
            if (!empty($adm_password)) {
                $data['adm_password'] = md5($adm_password . 'faster123456');
            }
            $data['adm_update_time'] = date('Y-m-d H:i:s');
            $data['adm_name'] = $adm_name;
            $data['adm_phone'] = $adm_phone;
            if ($adm->adm_type == 1) {
                $data['adm_type'] = 3;
            }
            $save_res = DB::table('admin')
                ->where('adm_id', $adm->adm_id)
                ->update($data);
            $adm_id = $adm->adm_id;
        }
        // 虚拟加盟店关联表
        $viad_id = DB::table('virtual_adm')
            ->where('viad_adm_id', $adm_id)
            ->where('viad_vish_id', $vish_id)
            ->value('viad_id');
        if (empty($viad_id)) {
            $viad['viad_vish_id'] = $vish_id;
            $viad['viad_adm_id'] = $adm_id;
            $viad['viad_create_time'] = date('Y-m-d H:i:s');

            $viad_res = DB::table('virtual_adm')->insert($viad);
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'当前门店已存在该技师！'];
            $viad_res = true;
        }
        if (empty($save_res) || empty($viad_res) || empty($admin_shop_role_id)) {
            return false;
        }
        return $adm_id;
    }
}
