<?php

namespace App\Http\Controllers\Api\ProductManage;

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

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

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderLabelController;
        $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('order_label')
                        ->where('orla_cid', $user_info->adm_cid)
                        ->where('orla_superior_shop_id', $shop_id)
                        ->where('orla_delete', 1)
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['orla_name'])) {
                                $query->where('orla_name', 'like', '%'.$search_data['orla_name'].'%' );
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['orla_state'])) {
                                $query->where('orla_state', $search_data['orla_state']);
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['orla_ord_service_type'])) {
                                $query->where('orla_ord_service_type', $search_data['orla_ord_service_type']);
                            }
                        })
                        ->select('orla_id', 'orla_name', 'orla_ord_service_type',  'orla_recycle_state',  'orla_remarks', 'orla_state')
                        ->orderBy('orla_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 VerifyOrderLabelController;
        $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('order_label')
                        ->where('orla_delete', 1)
                        ->where('orla_cid', $user_info->adm_cid)
                        ->where('orla_superior_shop_id', $shop_id)
                        ->where('orla_name', $request['orla_name'])
                        ->select('orla_id')
                        ->first();
        if ($find_sepr) {
            return response()->json(["code"=>500,'msg'=>'error','data'=>'订单标签已存在']);
        }

        // 2 新增一个订单标签数据
        $orla_add_data = [
            'orla_cid'=>$user_info->adm_cid,
            'orla_shop_id'=>$user_info->adm_shop_id,
            'orla_superior_shop_id'=>$shop_id,
            'orla_name'=>$request['orla_name'],
            'orla_ord_service_type'=>$request['orla_ord_service_type'],
            'orla_recycle_state'=>$request['orla_recycle_state'],
            'orla_remarks'=>$request['orla_remarks'] ? $request['orla_remarks'] : '',
        ];

        // 新增订单标签
        $orla_res =  DB::table('order_label')->insert($orla_add_data);

        if ($orla_res) {
            Common::addLog($user_info, getRealIp($request), '订单标签','新增','新增订单标签：'.$request['orla_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 VerifyOrderLabelController;
        $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('order_label')
                        ->where('orla_id', '<>', $request['orla_id'])
                        ->where('orla_delete', 1)
                        ->where('orla_cid', $user_info->adm_cid)
                        ->where('orla_superior_shop_id', $shop_id)
                        ->where('orla_name', $request['orla_name'])
                        ->select('orla_id')
                        ->first();
        if ($find_sepr) {
            return response()->json(["code"=>500,'msg'=>'error','data'=>'订单标签已存在']);
        }


        // 2 编辑订单标签数据
        $orla_edit_data = [
            'orla_cid'=>$user_info->adm_cid,
            'orla_shop_id'=>$user_info->adm_shop_id,
            'orla_superior_shop_id'=>$shop_id,
            'orla_name'=>$request['orla_name'],
            'orla_ord_service_type'=>$request['orla_ord_service_type'],
            'orla_recycle_state'=>$request['orla_recycle_state'],
            'orla_remarks'=>$request['orla_remarks'] ? $request['orla_remarks'] : '',
            'orla_update_time'=>date('Y-m-d H:i:s'),
        ];

        DB::beginTransaction();
        // 编辑订单标签
        $orla_res =  DB::table('order_label')
                    ->where('orla_id', $request['orla_id'])
                    ->update($orla_edit_data);

        if ($orla_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '订单标签','编辑','编辑订单标签：'.$request['orla_name'].'成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'编辑订单标签：成功']);
        }else{
            DB::rollBack();
            return response()->json(["code"=>500,'msg'=>'error','data'=>'编辑订单标签：失败']);
        }
    }

    // 启用
    public function start(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderLabelController;
        $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_bra = DB::table('order_label')
                    ->whereIn('orla_id',$request['orla_id'])
                    ->select('orla_name')
                    ->get();
        foreach ($find_bra as $key => $value) {
            $orla_name[] = $value->orla_name;
        }

        // 启用
        $update_data['orla_state'] = 1;//状态1启用2停用
        $update_data['orla_update_time'] = date('Y-m-d H:i:s');
        $orla_res = DB::table('order_label')
                    ->whereIn('orla_id', $request['orla_id'])
                    ->update($update_data);

        if($orla_res) {
            Common::addLog($user_info, getRealIp($request), '订单标签','启用','订单标签：（'.implode(',', $orla_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 VerifyOrderLabelController;
        $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_bra = DB::table('order_label')
                    ->whereIn('orla_id',$request['orla_id'])
                    ->select('orla_name')
                    ->get();
        foreach ($find_bra as $key => $value) {
            $orla_name[] = $value->orla_name;
        }

        // 启用
        $update_data['orla_state'] = 2;//状态1启用2停用
        $update_data['orla_update_time'] = date('Y-m-d H:i:s');
        $orla_res = DB::table('order_label')
                    ->whereIn('orla_id', $request['orla_id'])
                    ->update($update_data);

        if($orla_res) {
            Common::addLog($user_info, getRealIp($request), '订单标签','停用','订单标签：（'.implode(',', $orla_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 VerifyOrderLabelController;
        $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_bra = DB::table('order_label')
                    ->whereIn('orla_id',$request['orla_id'])
                    ->select('orla_name')
                    ->get();
        foreach ($find_bra as $key => $value) {
            $orla_name[] = $value->orla_name;
        }

        // 删除
        $update_data['orla_delete'] = 2;//是否删除：1正常2已删除
        $update_data['orla_update_time'] = date('Y-m-d H:i:s');
        $orla_res = DB::table('order_label')
                    ->whereIn('orla_id', $request['orla_id'])
                    ->update($update_data);

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

    //获取订单标签数据
    public function getOrderLabel(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $search_data = $request->all();

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

        $brand_info  =  DB::table('order_label')
                        ->where('orla_cid',$user_info->adm_cid)
                        ->where('orla_superior_shop_id',$shop_id)
                        ->where('orla_state', 1)
                        ->where('orla_delete', 1)
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['orla_name'])) {
                                $query->where('orla_name', 'like', '%'.$search_data['orla_name'].'%' );
                            }
                        })
                        ->get(['orla_id','orla_name']);
        return response()->json(['code'=> 200,'msg'=>'success','data_info'=>$brand_info]);
    }
}
