<?php
namespace App\Http\Controllers\Api\AfterSaleManage;

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

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

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyAfterLabelController;
        $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;
        $page_size = $request->input('show_count', 10);
        $search_data = $request->all();
        $list_data = DB::table('after_label as afla')
            ->leftJoin('after_label as aflb', 'afla.afla_parent_id', '=', 'aflb.afla_id')
            ->where('afla.afla_cid', $user_info->adm_cid)
            ->where('afla.afla_superior_shop_id', $shop_id)
            ->where('afla.afla_delete', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['afla_name'])) {
                    $query->where('afla.afla_name', 'like', '%' . $search_data['afla_name'].'%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['afla_state'])) {
                    $query->where('afla.afla_state', $search_data['afla_state']);
                }
            })
            ->select('afla.afla_id', 'afla.afla_name', 'afla.afla_state', 'afla.afla_parent_id', 'aflb.afla_name as afla_parent_name')
            ->orderBy('afla.afla_id', 'desc')
            ->paginate($page_size);
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $page_size;       //一页显示多少个
        $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 VerifyAfterLabelController;
        $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_afla_name = DB::table('after_label')
            ->where('afla_delete', 1)
            ->where('afla_cid', $user_info->adm_cid)
            ->where('afla_superior_shop_id', $shop_id)
            ->where('afla_name', $request['afla_name'])
            ->select('afla_id')
            ->first();
        if ($find_afla_name) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'售后标签名称已存在']);
        }

        $afla_data['afla_cid'] = $user_info->adm_cid;
        $afla_data['afla_superior_shop_id'] = $shop_id;
        $afla_data['afla_shop_id'] = $user_info->adm_shop_id;
        $afla_data['afla_name'] = $request['afla_name'];
        $afla_data['afla_parent_id'] = $request['afla_parent_id'];

        // 判断隶属上级
        if ($request['afla_parent_id']) {
            // 查找隶属品类是第几级
            $afla_rank = DB::table('after_label')
                ->where('afla_id', $request['afla_parent_id'])
                ->value('afla_rank');
            if ($afla_rank >= '3') {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'所属售后标签已超过三级']);
            }
            $afla_data['afla_rank'] = $afla_rank + 1;
        } else {
            $afla_data['afla_rank'] = 1;
        }

        // 新增售后标签
        $afla_res = DB::table('after_label')->insert($afla_data);

        if ($afla_res) {
            Common::addLog($user_info, getRealIp($request), '售后标签', '新增', '新增售后标签:'.$request['afla_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 VerifyAfterLabelController;
        $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;

        // 判断售后标签名称是否存在
        $find_afla_name = DB::table('after_label')
            ->where('afla_id', '<>', $request['afla_id'])
            ->where('afla_delete', 1)
            ->where('afla_cid', $user_info->adm_cid)
            ->where('afla_superior_shop_id', $shop_id)
            ->where('afla_name', $request['afla_name'])
            ->select('afla_id')
            ->first();
        if ($find_afla_name) {
            return response()->json(['code'=>500,'msg'=>'error','data'=>'标签已存在']);
        }

        $afla_data['afla_name'] = $request['afla_name'];
        $afla_data['afla_parent_id'] = $request['afla_parent_id'];
        $afla_data['afla_update_time'] = date('Y-m-d H:i:s');

        if ($request['cate_parent_id']) {
            // 查询隶属售后标签是第几级
            $afla_rank = DB::table('after_label')
                ->where('afla_id', $request['afla_parent_id'])
                ->value('afla_rank');
            if ($afla_rank >= '3') {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'所属售后标签已超过三级']);
            }
            $afla_data['afla_rank'] = $afla_rank + 1;
        } else {
            $afla_data['afla_rank'] = 1;
        }

        $afla_res =  DB::table('after_label')
            ->where('afla_id', $request['afla_id'])
            ->update($afla_data);

        if ($afla_res) {
            Common::addLog($user_info, getRealIp($request), '售后标签', '编辑', '编辑售后标签：'.$request['afla_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 VerifyAfterLabelController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 启用
        $update_data['afla_state'] = 1;//状态1启用2停用
        $update_data['afla_update_time'] = date('Y-m-d H:i:s');
        $afla_res = DB::table('after_label')
            ->whereIn('afla_id', $request['afla_id'])
            ->update($update_data);

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

            // 查询信息
            $find_afla_name = DB::table('after_label')
                ->whereIn('afla_id', $request['afla_id'])
                ->select('afla_name')
                ->get();
            foreach ($find_afla_name as $key => $value) {
                $afla_name[] = $value->afla_name;
            }
            Common::addLog($user_info, getRealIp($request), '售后标签', '启用', '售后标签：（'.implode(',', $afla_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 VerifyAfterLabelController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 停用
        $update_data['afla_state'] = 2;//状态1启用2停用
        $update_data['afla_update_time'] = date('Y-m-d H:i:s');
        $afla_res = DB::table('after_label')
            ->whereIn('afla_id', $request['afla_id'])
            ->update($update_data);

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

            // 查询信息
            $find_afla_name = DB::table('after_label')
                ->whereIn('afla_id', $request['afla_id'])
                ->select('afla_name')
                ->get();
            foreach ($find_afla_name as $key => $value) {
                $afla_name[] = $value->afla_name;
            }
            Common::addLog($user_info, getRealIp($request), '售后标签', '停用', '售后标签：（'.implode(',', $afla_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 VerifyAfterLabelController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 售后标签下有售后单的不得删除
        $order_after = DB::table('order_after')
            ->whereIn('oraf_orla_id', $request['afla_id'])
            ->where('oraf_delete', 1)
            ->first();
        if ($order_after) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'售后标签下有售后单不得删除']);
        }
        
        // 售后标签下有子标签不得删除
        $son_afla_id = DB::table('after_label')
            ->whereIn('afla_parent_id', $request['afla_id'])
            ->where('afla_delete', 1)
            ->first();
        if ($son_afla_id) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'售后标签下有子标签不得删除']);
        }

        // 删除
        $update_data['afla_delete'] = 2;//是否删除：1正常2已删除
        $update_data['afla_update_time'] = date('Y-m-d H:i:s');
        $cate_res = DB::table('after_label')
            ->whereIn('afla_id', $request['afla_id'])
            ->update($update_data);

        if ($cate_res) {
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            // 查询信息
            $find_afla_name = DB::table('after_label')
                ->whereIn('afla_id', $request['afla_id'])
                ->select('afla_name')
                ->get();
            foreach ($find_afla_name as $key => $value) {
                $afla_name[] = $value->afla_name;
            }
            Common::addLog($user_info, getRealIp($request), '售后标签', '删除', '售后标签：（'.implode(',', $afla_name).'）删除成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'删除成功']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'删除失败']);
        }
    }

    // 获取售后标签数据
    public function getAfterLabel(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;

        $list_data  =  DB::table('after_label')
            ->where('afla_cid', $user_info->adm_cid)
            ->where('afla_superior_shop_id', $shop_id)
            ->where('afla_state', 1)
            ->where('afla_delete', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('afla_name', 'like', '%'.$search_data['search_data'].'%');
                }
            })
            ->select('afla_id', 'afla_name')
            ->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();                //返回数据
        return response()->json(['code'=>200, 'msg'=>'success', 'data_info'=>$data_info]);
    }
}
