<?php

namespace App\Http\Controllers\Api\SystemsManage;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\SystemsManage\VerifyStoreListController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Crypt;
use App\Http\Models\Api\Common;
use App\Services\Shop\ShopService;

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

	// 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStoreListController;
        $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('shop')
                        ->where('shop_cid',$user_info->adm_cid)
                        ->where('shop_superior_id',$shop_id)
                        ->where('shop_type','!=',3)
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['shop_store_name'])) {
                                $query->where('shop_store_name', 'like', $search_data['shop_store_name'].'%' );
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['shop_name'])) {
                                $query->where('shop_name', 'like', '%'.$search_data['shop_name'].'%' );
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['shop_phone'])) {
                                $query->where('shop_phone', 'like', '%'.$search_data['shop_phone'].'%' );
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['shop_address'])) {
                                $query->where('shop_address', 'like', $search_data['shop_address'].'%' );
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['shop_state'])) {
                                $query->where('shop_state', $search_data['shop_state']);
                            }
                        })
                        ->select('shop_id', 'shop_store_name', 'shop_name', 'shop_phone', 'shop_province','shop_superior_id',
                        'shop_city', 'shop_county', 'shop_address', 'shop_state', 'shop_staff_number', 'shop_type')
                        ->orderBy('shop_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'=>'暂无数据']);
        }
    }

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

        // 1. 判断门店名称是否存在
        $store_name = DB::table('shop')
				        ->where('shop_cid',$user_info->adm_cid)
				        ->where('shop_store_name',$request['shop_store_name'])
				        ->first();
        if ($store_name) {
            return response()->json(["code"=>500,'msg'=>'error','data'=>'门店名称已存在']);
        }

        // 2. 判断手机号是否存在
        $adm_phone = DB::table('admin_shop_role')
				        ->where('phone',$request['shop_phone'])
				        ->where('shop_id',$user_info->adm_shop_id)
				        ->first();
		if (!empty($adm_phone)) {
            return response()->json(["code"=>500,'msg'=>'error','data'=>'当前门店手机号已存在']);
        }else{
            res = DB::table('admin_shop_role')
                ->where('phone',$request['shop_phone'])
                ->where('adm_shop_leave',1)
                ->first();
            if(!empty($res)) {
                return response()->json(["code"=>500,'msg'=>'error','data'=>'当前手机号已是店长']);
            }
        }

        // 3. 新增门店
        DB::beginTransaction();
        // 3.1 门店表新增一个门店数据
       	$shop_add_data = [
            'shop_cid'=>$user_info->adm_cid,
            'shop_superior_id'=>$user_info->adm_shop_id,
            'shop_store_name'=>$request['shop_store_name'],
            'shop_name'=>$request['shop_name'],
            'shop_phone'=>$request['shop_phone'],
            'shop_adm_id'=>0,
            'shop_province'=>$request['shop_province'],
            'shop_city'=>$request['shop_city'],
            'shop_county'=>$request['shop_county'],
            'shop_address'=>$request['shop_address'],
        ];
        // 新增门店
        $shop_id =  DB::table('shop')->insertGetId($shop_add_data);
        ShopService::addFestival($shop_id);

        // 3.2 新增一个角色数据，店长的角色，店长角色的权限应该是固定的，新增店长账号需要有对应的角色
        $role_add_data = [
            'rol_cid'=>$user_info->adm_cid,
            'rol_shop_id'=>$shop_id,
            'rol_type'=>1,
            'rol_name'=>'总管理',
            'rol_privilege'=>config('apisystem.direct_sale_store'),
            'rol_creator_id'=>$user_info->adm_id
        ];
        // 新增角色
        $role_id =  DB::table('role')->insertGetId($role_add_data);

        // 3.3 账号表新增一个账号数据，账号类型为店长
        $adm_id = DB::table('admin')
            ->where('adm_phone', $request['shop_phone'])
            ->value('adm_id');
        if(empty($adm_id)) {
            $admin_add_data = [
                'adm_cid'=>$user_info->adm_cid,
                'adm_shop_id'=>$shop_id,
                'adm_leave'=>1,
                'adm_phone'=>$request['shop_phone'],
                'adm_account'=>$request['adm_account'],
                'adm_password'=>md5($request['adm_password'].'faster123456'),
                'adm_name'=>$request['shop_name'],
                'adm_role'=>$role_id,
                'adm_creator_id'=>$user_info->adm_id,
            ];
            // 新增账号
            $adm_id =  DB::table('admin')->insertGetId($admin_add_data);
        }
        //新增账号门店权限关系表
        $insertAdminShopRoleData = [
            'adm_id' => $adm_id,
            'shop_cid' => $user_info->adm_cid,
            'superior_shop_id' => $shop_id,
            'shop_id' => $shop_id,
            'role_id' => $role_id,
            'adm_shop_leave' => 1,
            'phone' => $request['shop_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 字段
        $shop_save_res = DB::table('shop')->where('shop_id', $shop_id)->update(['shop_adm_id' => $adm_id]);
        if ($shop_id && $role_id && $adm_id && $shop_save_res && $admin_shop_role_id) {
            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 VerifyStoreListController;
        $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']);

        // 1. 判断门店名称是否存在
        $store_name = DB::table('shop')
	        ->where('shop_cid',$user_info->adm_cid)
	        ->where('shop_id', '<>', $request['shop_id'])
	        ->where('shop_store_name', $request['shop_store_name'])
	        ->select('shop_store_name')
	        ->first();
        if ($store_name) {
            return response()->json(["code"=>500,'msg'=>'error','data'=>'门店名称已存在']);
        }

        // 2. 判断手机号是否存在
        $store_name = DB::table('shop')
	        ->where('shop_id', $request['shop_id'])
	        ->select('shop_store_name', 'shop_adm_id')
	        ->first();
        $adm_phone = DB::table('admin_shop_role')
	        ->where('phone', $request['shop_phone'])
	        ->where('shop_id', $store_name->shop_adm_id)
	        ->where('adm_id', '<>', $store_name->shop_adm_id)
	        ->select('adm_phone')
	        ->first();
		if ($adm_phone) {
            return response()->json(["code"=>500,'msg'=>'error','data'=>'手机号已存在']);
        }else{
            res = DB::table('admin_shop_role')
                ->where('phone',$request['shop_phone'])
                ->where('adm_shop_leave',1)
                ->first();
            if(!empty($res)) {
                return response()->json(["code"=>500,'msg'=>'error','data'=>'当前手机号已是店长']);
            }
        }

        // 3 编辑门店信息
        DB::beginTransaction();

        // 3.1 门店表更改数据
        $shop_save_data = [
            'shop_store_name'=>$request['shop_store_name'],
            'shop_name'=>$request['shop_name'],
            'shop_phone'=>$request['shop_phone'],
            'shop_province'=>$request['shop_province'],
            'shop_city'=>$request['shop_city'],
            'shop_county'=>$request['shop_county'],
            'shop_address'=>$request['shop_address'],
            'shop_update_time'=>date('Y-m-d H:i:s'),
        ];
        $shop_save_res = DB::table('shop')->where('shop_id', $request['shop_id'])->update($shop_save_data);

        // 3.2 账号表更改数据
        $admin_save_data = [
            'adm_phone'=>$request['shop_phone'],
            'adm_name'=>$request['shop_name'],
            'adm_creator_id'=>$user_info->adm_id,
            'adm_update_time'=>date('Y-m-d H:i:s'),
        ];
        if ($request['adm_password']) {
        	$admin_save_data['adm_password'] = md5($request['adm_password'].'faster123456');
        }
        $adm_save_res = DB::table('admin')->where('adm_id', $store_name->shop_adm_id)->update($admin_save_data);
        $adm_save_res1 = DB::table('admin_shop_role')->where('adm_id', $store_name->shop_adm_id)->where('shop_id', $request['shop_id'])->update(['phone' => $request['shop_phone']]);
        if ($shop_save_res && $adm_save_res && $adm_save_res1) {
            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 start(Request $request)
    {
    	// 验证数据
        $verify_data = new VerifyStoreListController;
        $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('shop')
			        ->whereIn('shop_id',$request['shop_id'])
			        ->select('shop_store_name')
			        ->get();
        foreach ($find_shop as $key => $value) {
            $shop_store_name[] = $value->shop_store_name;
        }

        // 营业
        $update_data['shop_state'] = 1;//状态1营业2停业
        $update_data['shop_update_time'] = date('Y-m-d H:i:s');
        $shop_res = DB::table('shop')->whereIn('shop_id',$request['shop_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 export(Request $request)
    {
    　　// 查询数据库数据
    　　$list = DB::table('goods')->select('goo_id', 'goo_name', 'goo_type')->get();
    　　$this->userListExport($list);
    }

    public function userListExport($list)
    {
        // 导出充值记录的头部信息
        $cell = ['商品id', '商品名称', '商品类型', ];
        
        $cellData = [];
        foreach ($list as &$value) {
    　　　　　　　// 填充数据
                $cellData[] = ([
                    $value->goo_id,
                    $value->goo_name,
                    $value->goo_type,
                ]);
        }
        $this->exportUser($cell, $cellData);
    }


    public function exportUser($cell, $data, $title = '客户列表')
    {
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $title . '.csv"');
        header('Cache-Control: max-age=0');

        set_time_limit(0);   // 设置脚本最大执行时间 为0
        ini_set('memory_limit', '1024M');    // 临时设置最大内存占用

        // 打开PHP文件句柄，php://output 表示直接输出到浏览器
        $fp = fopen('php://output', 'a');

        $column_name = [];
        // 将中文标题转换编码，否则乱码
        foreach ($cell as $i => $v) {
            $column_name[$i] = iconv('utf-8', 'GBK//IGNORE', $v);
        }

        // 将标题名称通过fputcsv写到文件句柄
        fputcsv($fp, $column_name);
        foreach ($data as $row) {
            foreach ($row as $key => $item) {
                $row[$key] = iconv('utf-8', 'GBK//IGNORE', $item);
            }
            fputcsv($fp, $row);
        }
        $res = ['file' => $title];
        return response()->json($res);
    }


    public function exportData($headRowArray, $dataArray, $exportfilename = '1111')
    {
        $header = array_values($headRowArray);
        header("Content-type:text/csv;charset=utf-8");
        header("Content-disposition:attachment;filename={$exportfilename}.csv");
        header('Cache-Control:must-revalIDate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        $fp = fopen('PHP://output', 'w');
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
        fputcsv($fp, $header);
        $total = count($dataArray);
        $limit = 5000 ;
        $page_num = ceil ( $total / $limit ) ;
        for ( $i = 0 ; $i <= $page_num ; $i ++ ) {
            $out_put_data = array_slice ( $dataArray , $limit * $i , $limit ) ;
            foreach ( $out_put_data as $daTarowArray ) {
                $data = array_map(function($item){return "\t".$item;},$data);
                fputcsv($fp, $data);
            }
            ob_flush () ;
            flush () ;
            sleep(1);
        }
        fclose($fp);
        exit;
    }

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

        $shop_id = $request['shop_id'];
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if ($user_info->shop_superior_id == 0) {
            // 总店id，判断要停业的数组中是否有总店id
            if (in_array($user_info->adm_shop_id, $shop_id)) {
                // 删除总店id
                $shop_key = array_search($user_info->adm_shop_id,$shop_id);
                unset($shop_id[$shop_key]);
            }
        }

        // 查询门店信息
        $find_shop = DB::table('shop')
			        ->whereIn('shop_id',$shop_id)
			        ->select('shop_store_name')
			        ->get();
        foreach ($find_shop as $key => $value) {
            $shop_store_name[] = $value->shop_store_name;
        }

        // 停业
        $update_data['shop_state'] = 2;//状态1营业2停业
        $update_data['shop_update_time'] = date('Y-m-d H:i:s');
        $shop_res = DB::table('shop')->whereIn('shop_id',$shop_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 searchPeople(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStoreListController;
        $error_message = $verify_data->searchPeopleValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $search_data = $request->all();
        $info = DB::table('admin as a')
                ->leftJoin('admin_shop_role as asr', 'asr.adm_id', '=', 'a.adm_id')
                ->leftJoin('role as r', 'a.adm_role', '=', 'r.rol_id')
                ->where('asr.shop_id', $search_data['shop_id'])
                ->where('asr.adm_shop_leave', '!=', 1)
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['adm_name'])) {
                        $query->where('a.adm_name', 'like', $search_data['adm_name'].'%' )
                              ->orwhere('a.adm_phone', 'like', $search_data['adm_name'].'%' );
                    }
                })
                ->get(['a.adm_id','a.adm_name','a.adm_phone','r.rol_name','a.adm_account']);

        return response()->json(['code'=> 200,'msg'=>'success','data'=>$info]);
    }

    // 人员分配--搜索门店
    public function searchShop(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $search_data = $request->all();

        $info = DB::table('shop')
                ->where('shop_cid', $user_info->adm_cid)
                ->where('shop_superior_id', $user_info->adm_shop_id)
                ->orWhere('shop_id', $user_info->adm_shop_id)
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['shop_store_name'])) {
                        $query->where('shop_store_name', 'like', $search_data['shop_store_name'].'%' );
                    }
                })
                ->get(['shop_id','shop_store_name']);

        return response()->json(['code'=> 200,'msg'=>'success','data'=>$info]);
    }

    // 人员分配--提交
    public function peopleSubmit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStoreListController;
        $error_message = $verify_data->peopleSubmitValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        if (!empty($request['left_adm_id'][0])) {
            $left_adm_id = $request['left_adm_id'];
            foreach ($left_adm_id as $key => $value) {
                if (!is_numeric($value)) {
                    return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'左侧参数类型错误']);
                }
            }
        }else{
            $left_adm_id = [];
        }

        if (!empty($request['right_adm_id'][0])) {
            $right_adm_id = $request['right_adm_id'];
            foreach ($right_adm_id as $key => $value) {
                if (!is_numeric($value)) {
                    return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'右侧参数类型错误']);
                }
            }
        }else{
            $right_adm_id = [];
        }

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

        // 1.获取左侧门店下原有的员工id
        $old_left_adm_id = DB::table('admin_shop_role')
                         ->where('shop_id',$request['left_shop_id'])
                         ->get(['adm_id'])->toArray();
        $old_left_adm_id = array_column($old_left_adm_id,'adm_id');
        // 2.获取右侧门店下原有的员工id
        $old_right_adm_id = DB::table('admin_shop_role')
                         ->where('shop_id',$request['right_shop_id'])
                         ->get(['adm_id'])->toArray();
        $old_right_adm_id = array_column($old_right_adm_id,'adm_id');

        // 得到左边最终的数组
        $left_is_more = array_diff($old_left_adm_id, $left_adm_id);
        $right_is_more = array_diff($left_is_more, $right_adm_id);
        $left_end = array_merge($right_is_more,$left_adm_id);

        // 得到右边最终的数组
        $right_is_more = array_diff($old_right_adm_id, $right_adm_id);
        $left_is_more = array_diff($right_is_more, $left_adm_id);
        $right_end = array_merge($left_is_more,$right_adm_id);

        
        DB::beginTransaction();
        // 修改左侧门店下的员工总数
        $left_shop_info = DB::table('shop')
                        ->where('shop_id',$request['left_shop_id'])
                        ->value('shop_staff_number');
        if(count($left_end) == $left_shop_info){
            $left_staff = true;
        }else{
            $left_staff = DB::table('shop')
                        ->where('shop_id',$request['left_shop_id'])
                        ->update(['shop_staff_number'=>count($left_end)]);
        }
        
        // 修改右侧该门店下的员工总数
        $right_shop_info = DB::table('shop')
                         ->where('shop_id',$request['right_shop_id'])
                         ->value('shop_staff_number');
        if(count($right_end) == $right_shop_info){
            $right_staff = true;
        }else{

            $right_staff = DB::table('shop')
                         ->where('shop_id',$request['right_shop_id'])
                         ->update(['shop_staff_number'=>count($right_end)]);
        }

        // 修改左侧员工的门店id
        $left_now_adm = DB::table('admin_shop_role')
                 ->where('shop_id',$request['left_shop_id'])
                 ->get(['adm_id'])->toArray();
        $left_now_adm=array_column($left_now_adm,'adm_id');
        if(array_diff($left_adm_id, $left_now_adm)){
            $left_shop_id = DB::table('admin_shop_role')
                      ->whereIn('adm_id',$left_adm_id)
                      ->update(['shop_id'=>$request['left_shop_id']]);
        }else{
            $left_shop_id = true;
        }
        // 修改右侧员工的门店id
        $right_now_adm = DB::table('admin_shop_role')
                 ->where('shop_id',$request['right_shop_id'])
                 ->get(['adm_id'])->toArray();
        $right_now_adm=array_column($right_now_adm,'adm_id');
        if(array_diff($right_adm_id, $right_now_adm)){
            $right_shop_id = DB::table('admin_shop_role')
                           ->whereIn('adm_id',$right_adm_id)
                           ->update(['shop_id'=>$request['right_shop_id']]);
        }else{
            $right_shop_id = true;
        }

        if($left_staff && $right_staff && $left_shop_id && $right_shop_id){
            DB::commit();
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'分配成功']);
        }else{
            DB::rollBack();
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'分配失败']);
        }
    }
}
