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

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\AccountControl\VerifyNoteMessageController;

// 财务系统 -- 短信日志列表
class NoteMessageController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyNoteMessageController;
        $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']);

        $search_data = $request->all();
        $list_data = DB::table('send_message')
            ->where('seme_cid', $user_info->adm_cid)
            ->where('seme_shop_id', $user_info->adm_shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['seme_name'])) {
                    $query->where('seme_name', 'like', '%'.$search_data['seme_name'].'%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['seme_phone'])) {
                    $query->where('seme_phone', 'like', '%'.$search_data['seme_phone'].'%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['seme_state'])) {
                    $query->where('seme_state', $search_data['seme_state']);
                }
            })
            ->where(function ($query) use ($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                    $query->whereBetween('seme_create_time', [$search_data['create_time_start'], $search_data['create_time_end'].' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['create_time_start'])) {
                        $query->where('seme_create_time', '>=', $search_data['create_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['create_time_end'])) {
                            $query->where('seme_create_time', '<=', $search_data['create_time_end'].' 23:59:59');
                        }
                    }
                }
            }) //创建时间
            ->select('seme_id', 'seme_name', 'seme_phone', 'seme_content', 'seme_row', 'seme_state', 'seme_create_time')
            ->orderBy('seme_id', 'desc')
            ->paginate($this->show_count);

        $list_items = $list_data->items();

        $count_row = DB::table('send_message')
            ->where('seme_cid', $user_info->adm_cid)
            ->where('seme_shop_id', $user_info->adm_shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['seme_name'])) {
                    $query->where('seme_name', 'like', '%'.$search_data['seme_name'].'%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['seme_phone'])) {
                    $query->where('seme_phone', 'like', '%'.$search_data['seme_phone'].'%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['seme_state'])) {
                    $query->where('seme_state', $search_data['seme_state']);
                }
            })
            ->where(function ($query) use ($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                    $query->whereBetween('seme_create_time', [$search_data['create_time_start'], $search_data['create_time_end'].' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['create_time_start'])) {
                        $query->where('seme_create_time', '>=', $search_data['create_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['create_time_end'])) {
                            $query->where('seme_create_time', '<=', $search_data['create_time_end'].' 23:59:59');
                        }
                    }
                }
            }) //创建时间
            ->where('seme_state', 1)
            ->select(DB::raw('sum(seme_row) as seme_row'))
            ->first();

        $shin_residue_num = DB::table('shop_info')
            ->where('shin_shop_id',$user_info->adm_shop_id)
            ->value('shin_residue_num');
        $shin_residue_num = $shin_residue_num ?: 0;

        $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['seme_row'] = $count_row->seme_row;           //总条数
        $data_info['shin_residue_num'] = $shin_residue_num;      //剩余总条数
        // 获取当前列表下的按钮
        $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 listTemplate(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_data = DB::table('send_template')
            ->where('sete_cid', $user_info->adm_cid)
            ->where('sete_superior_shop_id', $shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['sete_name'])) {
                    $query->where('sete_name', 'like', '%'.$search_data['sete_name'].'%');
                }
            })
            ->select('sete_id', 'sete_name', 'sete_content', 'sete_sign', 'sete_number')
            ->orderBy('sete_id', 'desc')
            ->get();

        if ($list_data) {
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$list_data]);
        } else {
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
    }

    // 添加模板
    public function addTemplate(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyNoteMessageController;
        $error_message = $verify_data->addTemplateValidator($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;

        $sete_id = DB::table('send_template')
            ->where('sete_name', $request['sete_name'])
            ->value('sete_id');
        if (!empty($sete_id)) {
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'模板名称已存在']);
        }

        $sete['sete_cid'] = $user_info->adm_cid;
        $sete['sete_shop_id'] = $user_info->adm_shop_id;
        $sete['sete_superior_shop_id'] = $shop_id;
        $sete['sete_name'] = $request['sete_name'];//模板名称
        $sete['sete_sign'] = $request['sete_sign'];//模板签名
        $sete['sete_content'] = $request['sete_content'];//模板内容
        $sete['sete_number'] = $request['sete_number'];//模板所占用的短信数量
        $res = DB::table('send_template')->insert($sete);

        if ($res) {
            Common::addLog($user_info, getRealIp($request), '短信列表', '模板设置', '添加短信模板:'.$sete['sete_name']);
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'添加成功']);
        } else {
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'编辑失败']);
        }
    }

    // 编辑模板
    public function editTemplate(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyNoteMessageController;
        $error_message = $verify_data->editTemplateValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

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

        $sete_id = DB::table('send_template')
            ->where('sete_id', '!=', $request['sete_id'])
            ->where('sete_name', $request['sete_name'])
            ->value('sete_id');
        if (!empty($sete_id)) {
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'模板名称已存在']);
        }

        $sete['sete_name'] = $request['sete_name'];//模板名称
        $sete['sete_sign'] = $request['sete_sign'];//模板签名
        $sete['sete_content'] = $request['sete_content'];//模板内容
        $sete['sete_number'] = $request['sete_number'];//模板所占用的短信数量
        $sete['sete_update_time'] = date('Y-m-d H:i:s');//模板所占用的短信数量
        $res = DB::table('send_template')
            ->where('sete_id', $request['sete_id'])
            ->update($sete);

        if ($res) {
            Common::addLog($user_info, getRealIp($request), '短信列表', '模板设置', '编辑短信模板:'.$sete['sete_name']);
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'编辑成功']);
        } else {
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'编辑失败']);
        }
    }

    // 短信模块
    public function listModule(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_data = DB::table('send_module')
            ->leftjoin('send_template as st', 'st.sete_id', '=', 'mode_sete_id')
            ->where('mode_cid', $user_info->adm_cid)
            ->where('mode_superior_shop_id', $shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mode_name'])) {
                    $query->where('mode_name', 'like', '%'.$search_data['mode_name'].'%');
                }
            })
            ->select('mode_id', 'mode_name', 'mode_state', 'sete_name')
            ->orderBy('mode_id', 'desc')
            ->get();

        if ($list_data) {
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$list_data]);
        } else {
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
    }

    // 绑定
    public function binding(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyNoteMessageController;
        $error_message = $verify_data->bindingValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $res = DB::table('send_module')
            ->where('mode_id', $request['mode_id'])
            ->update(['mode_sete_id'=>$request['sete_id'],'mode_update_time'=>date('Y-m-d H:i:s')]);
        if ($res) {
            $mode_name = DB::table('send_module')
                ->where('mode_id', $request['mode_id'])
                ->value('mode_name');

            $sete_name = DB::table('send_template')
                ->where('sete_id', $request['sete_id'])
                ->value('sete_name');
            Common::addLog($user_info, getRealIp($request), '短信列表', '模板设置', '模块:'.$mode_name.' 绑定了短信模板:'.$sete_name);
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'绑定成功']);
        } else {
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'绑定失败']);
        }
    }

    // 模块停用
    public function stopModule(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyNoteMessageController;
        $error_message = $verify_data->stopModuleValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $mode_name = DB::table('send_module')
            ->where('mode_id', $request['mode_id'])
            ->value('mode_name');

        $res = DB::table('send_module')
            ->where('mode_id', $request['mode_id'])
            ->update(['mode_state'=>2,'mode_update_time'=>date('Y-m-d H:i:s')]);
        if ($res) {
            Common::addLog($user_info, getRealIp($request), '短信列表', '模块设置', '模块:'.$mode_name.'停用');
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'停用成功']);
        } else {
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'停用失败']);
        }
    }

    // 模块启用
    public function startModule(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyNoteMessageController;
        $error_message = $verify_data->startModuleValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        
        $mode_name = DB::table('send_module')
            ->where('mode_id', $request['mode_id'])
            ->value('mode_name');

        $res = DB::table('send_module')
            ->where('mode_id', $request['mode_id'])
            ->update(['mode_state'=>1,'mode_update_time'=>date('Y-m-d H:i:s')]);
        if ($res) {
            Common::addLog($user_info, getRealIp($request), '短信列表', '模块设置', '模块:'.$mode_name.'启用');
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'启用成功']);
        } else {
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'启用失败']);
        }
    }

    // 删除模板
    public function deleteTemplate(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyNoteMessageController;
        $error_message = $verify_data->deleteTemplateValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

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

        // 判断模块是否引用
        $mode_id = DB::table('send_module')
            ->where('mode_sete_id', $request['sete_id'])
            ->value('mode_id');
        if ($mode_id) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前模板已被绑定，无法删除']);
        }

        $sete_name = DB::table('send_template')
            ->where('sete_id', $request['sete_id'])
            ->value('sete_name');

        $res = DB::table('send_template')
            ->where('sete_id', $request['sete_id'])
            ->delete();
        if ($res) {
            Common::addLog($user_info, getRealIp($request), '短信列表', '删除', '模块：'.$sete_name.'删除成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'删除成功']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'删除失败']);
        }
    }

    //支付记录
    public function listPay(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_data = DB::table('send_pay_record as spr')
            ->leftjoin('admin as a','a.adm_id','=','spr.sepr_adm_id')
            ->where('sepr_cid', $user_info->adm_cid)
            ->where('sepr_superior_shop_id', $shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['sete_name'])) {
                    $query->where('sete_name', 'like', '%'.$search_data['sete_name'].'%');
                }
            })
            ->select('adm_name', 'sepr_send_number', 'sepr_money', 'sepr_num', 'sepr_create_time','sepr_state')
            ->orderBy('sepr_id', 'desc')
            ->get();

        if ($list_data) {
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$list_data]);
        } else {
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
    }
}
