<?php
namespace App\Http\Controllers\DatasBase;
use App\Http\Controllers\BaseController;
use App\Services\BmmcService;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Http\Request;
use App\Models\Admin;
use Excel;
use \Exception;
use DB;
class RegionController extends BaseController
{
	//---------------地域管理

    /**
     * @name  地域管理 >> 列表页
     * @param reg_name 地域名称
     * @param level 地域级别
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/8/31
     */
	public function index(Request $request){
        $level = (int)$request->input('level',1);
        //页码数据
        $page_size = (int)$request->input('page_size',10);
        $page = (int)$request->input('page',1);
        if($page<1){
            $page = 1;
        }
        $offset = ($request->input('page',1)-1)*$page_size;
        $Db = Db::table('region');
        if($request->filled('level') && $level>0){
        	$Db = $Db->where('reg_level',$level);
        }
        if($request->filled('reg_name')){
        	$Db = $Db->where('reg_name','like','%'.$request->input('reg_name').'%');
        }
       	$count = $Db->count();
       	$list = $Db->offset($offset)->limit($page_size)->orderBy('reg_id','asc')->get();
        $data = [];
        $data['page'] = ['page'=>$page,'page_size'=>$page_size,'count'=>$count,'allPage' => ceil($count/$page_size)];
        $all_button = BmmcService::whereButton($request->input('token'),$request->input('Pri_id'));
        $export = BmmcService::getTopButton('addRegion','',$all_button);
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮
       	if(!$list->isEmpty()){
       		$temp = $list->toArray();
       		unset($list);
       		$list = $temp;
       		foreach ($list as $key => $val) {
                $buttonData = [];
                $buttonData[] = 'editRegion';
                $button = BmmcService::getListButton($buttonData,$all_button);
                $list[$key]['button_one'] = $button['button_one']??[];
                $list[$key]['button_two'] = $button['button_two']??[];
                $list[$key]['button_three'] = $button['button_three']??[];

       			switch ($val['reg_level']) {
       				case 1:
       					$list[$key]['reg_level'] = '省级';
       					break;
       				case 2:
       					$list[$key]['reg_level'] = '市级';
       					break;
       				case 3:
       					$list[$key]['reg_level'] = '县级';
       					break;
       				case 4:
       					$list[$key]['reg_level'] = '乡镇级';
       					break;
       			}
       		}
            $data['list'] = $list;
       		return $this->success('获取成功',$data);exit;
       	}
       	$data['list'] = [];
       	return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$data);exit;
	}

    /**
     * @name  添加
     * @param type       1:获取省份列表; 2:获取城市数据;3:获取乡镇数据;4:执行添加
     * @param number     省份编号(type=2,type=3)
     * @param level      2:省级;3:市级;4:乡镇级
     * @param sheng_num  省级编号
     * @param shi_num    市级编号
     * @param xian_num   乡镇编号
     * @param add_name   地址名称
     * @param add_num    地址编号
     * @param reg_alias  地域别名
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/9/1
     */
    public function addRegion(Request $request){
        $type = (int)$request->input('type',1);
        //获取省份数据
        if($type==1){
            $data = Db::table('region')->where('reg_level',1)->select('reg_id','reg_name','reg_num')->get();
            return $this->success('获取成功',$data);exit;
        }elseif($type==2){
            //获取城市数据
            $data = Db::table('region')->where('reg_level',2)->where('reg_blnum',$request->input('number'))->select('reg_id','reg_name','reg_num')->get();
            return $this->success('获取成功',$data);exit;
        }elseif($type==3){
            //获取乡镇数据
            $data = Db::table('region')->where('reg_level',3)->where('reg_blnum',$request->input('number'))->select('reg_id','reg_name','reg_num')->get();
            return $this->success('获取成功',$data);exit;
        }else{
            if($request->filled('level') && $request->filled('sheng_num') && $request->filled('add_name') && $request->filled('add_num')){

            }else{
                return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
            }
            //执行添加
            $add_level = (int)$request->input('level',1);
            switch ($add_level)
            {
                case 2:
                    $level = "市级";
                    $poss['reg_level'] = 2;
                    $poss['reg_num'] = $request->input('add_num');
                    $poss['reg_blnum'] = $request->input('sheng_num');
                    break;
                case 3:
                    $level = "区县";
                    $poss['reg_level'] = 3;
                    $poss['reg_num'] = $request->input('add_num');
                    $poss['reg_blnum'] = $request->input('shi_num');
                    break;
                case 4:
                    $level = "乡镇/街道";
                    $poss['reg_level'] = 4;
                    $poss['reg_num'] = $request->input('add_num');
                    $poss['reg_blnum'] = $request->input('xian_num');
                    break;
            }
            $poss['reg_name'] = $request->input('add_name');
            $poss['reg_alias'] = $request->input('reg_alias');
            $res = Db::table('region')->insertGetId($poss);
            if($res){
                if($poss['reg_level']==3){
                    $shi = Db::table("region")->where("reg_num",$request->input('shi_num'))->select("reg_blnum","reg_name",'reg_id')->first();
                    $sheng = Db::table("region")->where("reg_num",$request->input('sheng_num'))->select("reg_blnum","reg_name",'reg_id')->first();

                    $disareanew_data = [];
                    $disareanew_data['are_sheng'] = $sheng['reg_name'];
                    $disareanew_data['are_shi'] = $shi['reg_name'];
                    $disareanew_data['are_xian'] = $poss['reg_name'];

                    $disareanew_data['are_shid'] = $sheng['reg_id'];
                    $disareanew_data['are_sid'] = $shi['reg_id'];
                    $disareanew_data['are_xid'] = $res;
                    $disareanew_data['creact_time'] = date("Y-m-d H:i:s");
                    $disareanew_data['creact_id'] = $request->get('session_token')['id'];
                    $disareanew_data['company_id'] = $request->get('session_token')['company_id'];
                    Db::table('disareanew')->insert($disareanew_data);
                }
                $this->insertingLog("添加，",'',"级别：".$level.";名称：".$poss['reg_name'].";上级编号：".$poss['reg_blnum'].";地域编号：".$poss['reg_num'],"地域管理",$request->ip(),$request->get('session_token')['admin_acc']);

                return $this->success('操作成功');exit;
            } else {
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
            }

        }
    }

    /**
     * @name  编辑
     * @param reg_id     数据id
     * @paran reg_alias  地域别名
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/8/31
     */
	public function editRegion(Request $request){
		$id = (int)$request->input('reg_id',0);
		if($request->filled('reg_id') && $id != 0 && $request->filled('reg_alias')){
			$reg_alias = $request->input('reg_alias');
			$old_alias = Db::table('region')->where('reg_id',$id)->select('reg_alias','reg_id')->first();
			if(!$old_alias){
                return $this->error('请求错误,未找到该地域数据', ErrorInc::MYSQL_FAILED,$id);exit;
			}
			$res = Db::table('region')->where('reg_id',$id)->update(['reg_alias'=>$reg_alias]);
			if($res){
				$this->insertingLog("编辑，",'',$old_alias['reg_alias']."->".$reg_alias,"地域管理",$request->ip(),$request->get('session_token')['admin_acc']);//日志
                return $this->success('操作成功');exit;
            } else {
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
			}
		}else{
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
		}
	}



}
