<?php

namespace App\Http\Controllers\Api\RegionManage;

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

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

    // 业务划区列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPrecinctsController;
        $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('precincts')
            ->where('prec_cid',$user_info->adm_cid)
            ->where('prec_superior_shop_id',$shop_id)
            ->where(function($query) use($search_data) {
                if (!empty($search_data['prec_name'])) {
                    $query->where('prec_name', 'like','%'.$search_data['prec_name'].'%');
                }
            }) //业务划区名称
            ->where(function($query) use($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_time']) && !empty($search_data['end_time'])){
                    $query->whereBetween('prec_create_time',[$search_data['start_time'],$search_data['end_time'].' 23:59:59']);
                }else{
                    // 如果选择开始时间
                    if (!empty($search_data['start_time'])){
                        $query->where('prec_create_time','>=',$search_data['start_time']);
                    }else{
                        // 如果选择结束时间
                        if (!empty($search_data['end_time'])) {
                            $query->where('prec_create_time','<=',$search_data['end_time'].' 23:59:59');
                        }
                    }
                }
            }) //创建时间
            ->select('prec_id','prec_region','prec_province','prec_city','prec_county','prec_name','prec_state','prec_adm_id','prec_create_time')
            ->orderBy('prec_id', 'desc')
            ->paginate($this->show_count);
        $list_items = $list_data->items();
        $person = [];
        if(!empty($list_items)){
            $adm_id = [];
            foreach ($list_items as $key => $value) {
                $adm_id[] = $value->prec_adm_id;
            }
            $person = DB::table('admin')
                ->whereIn('adm_id',$adm_id)
                ->get(['adm_id','adm_name']);
        } 
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;        //一页显示多少个
        $data_info['data'] = $list_items;                        //返回数据
        $data_info['person'] = $person;                        //操作人数据
        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        return response()->json(['code'=> 200,'msg'=>'success','data'=>$data_info, 'list_button'=>$list_button]);
    }

    //添加
    public function add(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPrecinctsController;
        $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;

        $prec_id = DB::table('precincts')
            ->where('prec_cid',$user_info->adm_cid)
            ->where('prec_superior_shop_id',$shop_id)
            ->where('prec_name',$request['prec_name'])
            ->value('prec_id');
        if (!empty($prec_id)) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'此名称已存在']);
        }
        $data['prec_region'] = $request['prec_region'];
        $data['prec_province'] = $request['prec_province'];
        $data['prec_city'] = $request['prec_city'];
        $data['prec_county'] = $request['prec_county'];
        $data['prec_name'] = $request['prec_name'];
        $data['prec_cid'] = $user_info->adm_cid;
        $data['prec_shop_id'] = $user_info->adm_shop_id;
        $data['prec_adm_id'] = $user_info->adm_id;
        $data['prec_superior_shop_id'] = $shop_id;

        $prec_res = DB::table('precincts')->insert($data);
        if ($prec_res) {
            Common::addLog($user_info, getRealIp($request), '业务划区', '添加', $request['prec_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 VerifyPrecinctsController;
        $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']);

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        $prec_id = DB::table('precincts')
            ->where('prec_cid',$user_info->adm_cid)
            ->where('prec_superior_shop_id',$shop_id)
            ->where('prec_name',$request['prec_name'])
            ->value('prec_id');
        if (!empty($prec_id)) {
            if($prec_id != $request['prec_id']){
                return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'此名称已存在']);
            }
        }
        $data['prec_region'] = $request['prec_region'];
        $data['prec_province'] = $request['prec_province'];
        $data['prec_city'] = $request['prec_city'];
        $data['prec_county'] = $request['prec_county'];
        $data['prec_name'] = $request['prec_name'];
        $data['prec_adm_id'] = $user_info->adm_id;
        $data['prec_update_time'] = date('Y-m-d H:i:s');

        $prec_res = DB::table('precincts')
            ->where('prec_id',$request['prec_id'])
            ->update($data);
        if ($prec_res) {
            Common::addLog($user_info, getRealIp($request), '业务划区', '编辑', $request['prec_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 VerifyPrecinctsController;
        $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']);

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

        foreach ($request['prec_id'] as $key => $value) {
            if(!is_int((int)$value)){
                return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误']);
            }
        }
        $prec_data = DB::table('precincts')
            ->whereIn('prec_id',$request['prec_id'])
            ->get(['prec_name']);
        $prec_name_str = '';
        foreach ($prec_data as $key => $value) {
            $prec_name_str .= $value->prec_name.',';
        }

        $data['prec_state'] = 1;
        $data['prec_update_time'] = date('Y-m-d H:i:s');

        $prec_res = DB::table('precincts')
            ->whereIn('prec_id',$request['prec_id'])
            ->update($data);
        if ($prec_res) {
            Common::addLog($user_info, getRealIp($request), '业务划区', '启用', trim($prec_name_str,',').' 提交成功');
            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 VerifyPrecinctsController;
        $error_message = $verify_data->stopValidator($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;
        foreach ($request['prec_id'] as $key => $value) {
            if(!is_int((int)$value)){
                return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误']);
            }
        }
        $prec_data = DB::table('precincts')
            ->whereIn('prec_id',$request['prec_id'])
            ->get(['prec_name']);
        $prec_name_str = '';
        foreach ($prec_data as $key => $value) {
            $prec_name_str .= $value->prec_name.',';
        }

        $data['prec_state'] = 2;
        $data['prec_update_time'] = date('Y-m-d H:i:s');

        $prec_res = DB::table('precincts')
            ->whereIn('prec_id',$request['prec_id'])
            ->update($data);
        if ($prec_res) {
            Common::addLog($user_info, getRealIp($request), '业务划区', '停用', trim($prec_name_str,',').' 提交成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'停用区域成功']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'停用区域失败']);
        }
    }
}
