<?php

namespace App\Http\Controllers\Api\ChannelManage;

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

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

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyChannelTypeController;
        $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('channel_type')
                        ->where('chty_cid', $user_info->adm_cid)
                        ->where('chty_superior_shop_id', $shop_id)
                        ->where('chty_delete', 1)
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['chty_name'])) {
                                $query->where('chty_name', 'like', '%' . $search_data['chty_name'].'%' );
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['chty_state'])) {
                                $query->where('chty_state', $search_data['chty_state']);
                            }
                        })
                        ->select('chty_id', 'chty_name', 'chty_channel_number', 'chty_state', 'chty_system_type')
                        ->orderBy('chty_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 VerifyChannelTypeController;
        $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;

        // 1. 判断单位类型是否存在
        $find_sepr = DB::table('channel_type')
            ->where('chty_delete', 1)
            ->where('chty_cid', $user_info->adm_cid)
            ->where('chty_superior_shop_id', $shop_id)
            ->where('chty_name', $request['chty_name'])
            ->first(['chty_id']);
        if ($find_sepr) {
            return response()->json(["code"=>500,'msg'=>'error','data'=>'单位类型已存在']);
        }

        // 2 新增一个单位类型
        $chty_add_data = [
            'chty_cid'=>$user_info->adm_cid,
            'chty_shop_id'=>$user_info->adm_shop_id,
            'chty_superior_shop_id'=>$shop_id,
            'chty_name'=>$request['chty_name'],
            'chty_state'=>$request['chty_state'],
        ];

        // 新增单位类型
        $chty_res =  DB::table('channel_type')->insert($chty_add_data);

        if ($chty_res) {
            Common::addLog($user_info, getRealIp($request), '单位类型','新增','新增单位类型：'.$request['chty_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 VerifyChannelTypeController;
        $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;

        // 1. 判断单位类型是否存在
        $find_sepr = DB::table('channel_type')
                ->where('chty_id', '<>', $request['chty_id'])
                ->where('chty_delete', 1)
                ->where('chty_cid', $user_info->adm_cid)
                ->where('chty_superior_shop_id', $shop_id)
                ->where('chty_name', $request['chty_name'])
                ->first(['chty_id']);
        if ($find_sepr) {
            return response()->json(["code"=>500,'msg'=>'error','data'=>'单位类型已存在']);
        }

        // 2 编辑单位类型
        $chty_edit_data = [
            'chty_cid'=>$user_info->adm_cid,
            'chty_shop_id'=>$user_info->adm_shop_id,
            'chty_superior_shop_id'=>$shop_id,
            'chty_name'=>$request['chty_name'],
            'chty_update_time'=>date('Y-m-d H:i:s'),
            'chty_state'=>$request['chty_state'],
        ];

        // 编辑单位类型
        $chty_res =  DB::table('channel_type')
                    ->where('chty_id', $request['chty_id'])
                    ->update($chty_edit_data);

        if ($chty_res) {
            Common::addLog($user_info, getRealIp($request), '单位类型','编辑','编辑单位类型：'.$request['chty_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 VerifyChannelTypeController;
        $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_chty = DB::table('channel_type')
                ->whereIn('chty_id',$request['chty_id'])
                ->get(['chty_name']);
        foreach ($find_chty as $key => $value) {
            $chty_name[] = $value->chty_name;
        }

        // 启用
        $update_data['chty_state'] = 1;//状态1启用2停用
        $update_data['chty_update_time'] = date('Y-m-d H:i:s');
        $chty_res = DB::table('channel_type')
                    ->whereIn('chty_id', $request['chty_id'])
                    ->update($update_data);

        if($chty_res) {
            Common::addLog($user_info, getRealIp($request), '单位类型','启用','单位类型：（'.implode(',', $chty_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 VerifyChannelTypeController;
        $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_chty = DB::table('channel_type')
                ->whereIn('chty_id',$request['chty_id'])
                ->get(['chty_name']);
        foreach ($find_chty as $key => $value) {
            $chty_name[] = $value->chty_name;
        }

        // 启用
        $update_data['chty_state'] = 2;//状态1启用2停用
        $update_data['chty_update_time'] = date('Y-m-d H:i:s');
        $chty_res = DB::table('channel_type')
                    ->whereIn('chty_id', $request['chty_id'])
                    ->update($update_data);

        if($chty_res) {
            Common::addLog($user_info, getRealIp($request), '单位类型','停用','单位类型：（'.implode(',', $chty_name).'）停用成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'停用成功']);
        }else{
            return response()->json(["code"=>500,'msg'=>'error','data'=>'停用失败']);
        }
    }

    // 删除
    public function delete(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyChannelTypeController;
        $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_chty = DB::table('channel_type')
                   ->whereIn('chty_id',$request['chty_id'])
                   ->get(['chty_name']);
        foreach ($find_chty as $key => $value) {
            $chty_name[] = $value->chty_name;
        }

        // 删除
        $update_data['chty_delete'] = 2;//是否删除：1正常2已删除
        $update_data['chty_update_time'] = date('Y-m-d H:i:s');
        $chty_res = DB::table('channel_type')
                    ->whereIn('chty_id', $request['chty_id'])
                    ->update($update_data);

        if($chty_res) {
            Common::addLog($user_info, getRealIp($request), '单位类型','删除','单位类型：（'.implode(',', $chty_name).'）删除成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'删除成功']);
        }else{
            return response()->json(["code"=>500,'msg'=>'error','data'=>'删除失败']);
        }
    }

    // 搜索客户类型
    public function searchChannelType(Request $request)
    {
        // 获取当前操作账号信息
        $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 = DB::table('channel_type')
                ->where('chty_cid',$user_info->adm_cid)
                ->where('chty_superior_shop_id',$shop_id)
                ->where('chty_state', 1)
                ->where('chty_delete', 1)
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['search_data'])) {
                        $query->where('chty_name', 'like', '%'.$search_data['search_data'].'%' );
                    }
                })
                ->get(['chty_id','chty_name']);
        return response()->json(["code"=>200,'msg'=>'success','data'=>$list]);
    }
}
