<?php

namespace App\Services\Finance;

use Illuminate\Database\Eloquent\Model;
use App\Models\Finance\WashRecharge;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Models\Common;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Validators\Finance\WashRechargeValidator;
use BlueCity\Core\Inc\ErrorInc;

// 充值管理
class WashRechargeService extends Service
{
    public static $instance;
    public $modelMain = null;
    public $mainValidator = null;

    public function __construct()
    {
        $this->modelMain = new WashRecharge();
        $this->mainValidator = new WashRechargeValidator();
    }

    /**
     * @return mixed
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }

    /**
     * 根据条件搜索数据内容
     *会员单位
     * @param array $param 条件
     * @param array $columns 内容
     * @param int $page 页码
     * @param int $pageSize 页容量
     * @return mixed
     */
    public function index($user_info, $search_data, $show_count = 10)
    {
        $list_data = DB::table('wash_recharge as wr')
            ->where('rech_shop_id', $user_info->adm_shop_id)
            ->where('rech_type', $search_data['rech_type']) //1会员2客户单位
            ->where('rech_delete', 2) //销户状态1销户2未销户
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['rech_client_name'])) {
                    $query->where('rech_client_name', 'like', '%' . $search_data['rech_client_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['rech_phone'])) {
                    $query->where('rech_phone', 'like', '%' . $search_data['rech_phone'] . '%');
                }
            }) //车牌号
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['rech_car_num'])) {
                    $query->where('rech_car_num', 'like', '%' . $search_data['rech_car_num'] . '%');
                }
            }) //客户电话
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['rech_car_vin'])) {
                    $query->where('rech_car_vin', 'like', '%' . $search_data['rech_car_vin'] . '%');
                }
            }) //车架号
            ->where(function ($query) use ($search_data) { //创建时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                    $query->whereBetween('rech_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('rech_create_time', '>=', $search_data['create_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['create_time_end'])) {
                            $query->where('rech_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) { //金额区间
                // 选择最大最小值
                if (!empty($search_data['money_min']) && !empty($search_data['money_max'])) {
                    $query->whereBetween('rech_balance', [$search_data['money_min'] * 100, $search_data['money_max'] * 100]);
                } else {
                    // 如果选择最小值
                    if (!empty($search_data['money_min'])) {
                        $query->where('rech_balance', '>=', $search_data['money_min'] * 100);
                    } else {
                        // 如果选择最大值
                        if (!empty($search_data['money_max'])) {
                            $query->where('rech_balance', '<=', $search_data['money_max'] * 100);
                        }
                    }
                }
            })
            ->select('rech_phone', 'rech_car_num', 'rech_car_vin', 'rech_create_time', 'rech_total_money', 'rech_balance', 'rech_state', 'rech_id', 'rech_client_name', 'rech_create_adm_id', 'rech_delete')
            ->orderBy('rech_id', 'desc')
            ->paginate($show_count);
        $list_items = $list_data->items();
        if ($list_items) {
            $adm_id = array_unique(array_column($list_items, 'rech_create_adm_id'));
            $find_admin = DB::table('admin')
                ->whereIn('adm_id', $adm_id)
                ->pluck('adm_name', 'adm_id')
                ->toArray();
            foreach ($list_items as $key => $value) {
                // 创建人信息
                if ($value->rech_create_adm_id) {
                    $list_items[$key]->adm_name = isset($find_admin[$value->rech_create_adm_id]) ? $find_admin[$value->rech_create_adm_id] : '';
                } else {
                    $list_items[$key]->adm_name = '';
                }
            }
        }
        $data['current_page'] = $list_data->currentPage();  //当前页面页码
        $data['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data['total'] = $list_data->total();               //总数据个数
        $data['current_number'] = $show_count;        //一页显示多少个
        $data['data'] = $list_items;                        //返回数据
        return $data;
    }

    /**
     * 检查是不是存在客户
     * @param $type 类型：1会员2客户单位
     * @param int $id 
     * @return mixed
     */
    public static function Exists($user_info, $type, $id = 0)
    {
        return WashRecharge::where('rech_shop_id', $user_info->adm_shop_id)
            ->where('rech_cid', $user_info->adm_cid)
            ->where('rech_client_id', $id)
            ->where('rech_type', $type)
            ->exists();
    }

    // 新增
    public static function add($user_info, $request)
    {
        $data['rech_cid'] = $user_info->adm_cid;
        $data['rech_superior_shop_id'] = $user_info->adm_shop_id;
        $data['rech_shop_id'] = $user_info->adm_shop_id;
        $data['rech_client_id'] = $request['rech_client_id']; //客户ID/客户单位id
        $data['rech_client_name'] = $request['rech_client_name']; //客户名称/客户单位名称
        $data['rech_type'] = $request['rech_type']; //1会员2客户单位
        $data['rech_phone'] = $request['rech_phone'] ?: ''; //客户电话
        $data['rech_car_num'] = $request['rech_car_num'] ?: ''; //车牌号
        $data['rech_car_vin'] = $request['rech_car_vin'] ?: ''; //车架号
        $data['rech_total_money'] = $request['rech_money'] * 100; //充值总金额
        $data['rech_balance'] = $request['rech_money'] * 100; //余额(单位分)
        $data['rech_time_start'] = $request['rech_time_start']; //有效期开始
        $data['rech_time_end'] = $request['rech_time_end']; //有效期结束
        $data['rech_create_adm_id'] = $user_info->adm_id; //创建人
        $data['rech_create_time'] = date('Y-m-d H:i:s');
        $data['rech_update_time'] = date('Y-m-d H:i:s');
        $rech_id = WashRecharge::insertGetId($data);
        $rein_data['rein_rech_id'] = $rech_id;
        $rein_data['rein_shop_id'] = $user_info->adm_shop_id;
        $rein_data['rein_money'] = $request['rech_money'] * 100;
        $rein_data['rein_content'] = '充值';
        $rein_data['rein_name'] = $request['rech_client_name'] ?: ''; //姓名
        $rein_data['rein_phone'] = $request['rech_phone'] ?: ''; //电话
        $rein_data['rein_car_num'] = $request['rech_car_num'] ?: ''; //车牌号
        $rein_data['rein_car_vin'] = $request['rech_car_vin'] ?: ''; //车架号
        $rein_data['rein_create_adm_id'] = $user_info->adm_id; //创建人
        $rein_data['rein_create_time'] = date('Y-m-d H:i:s');
        $rein_res = DB::table('wash_recharge_info')->insert($rein_data);
        if ($rech_id && $rein_res) {
            return true;
        } else {
            return false;
        }
    }

    // 修改
    public static function edit($user_info, $request)
    {
        $data['rech_cid'] = $user_info->adm_cid;
        $data['rech_superior_shop_id'] = $user_info->adm_shop_id;
        $data['rech_shop_id'] = $user_info->adm_shop_id;
        $data['rech_client_id'] = $request['rech_client_id']; //客户ID/客户单位id
        $data['rech_client_name'] = $request['rech_client_name']; //客户名称/客户单位名称
        $data['rech_type'] = $request['rech_type']; //1会员2客户单位
        $data['rech_phone'] = $request['rech_phone'] ?: ''; //客户电话
        $data['rech_car_num'] = $request['rech_car_num'] ?: ''; //车牌号
        $data['rech_car_vin'] = $request['rech_car_vin'] ?: ''; //车架号
        // $data['rech_balance'] = $request['rech_money']*100;//余额(单位分)
        $data['rech_time_start'] = $request['rech_time_start']; //有效期开始
        $data['rech_time_end'] = $request['rech_time_end']; //有效期结束
        $data['rech_create_adm_id'] = $user_info->adm_id; //创建人
        $data['rech_update_time'] = date('Y-m-d H:i:s');
        $rech_res = WashRecharge::where('rech_id', $request['rech_id'])->update($data);
        if ($rech_res) {
            return true;
        } else {
            return false;
        }
    }

    // 更改启用状态
    public static function editState($ids, $state)
    {
        $data['rech_state'] = $state;
        $data['rech_update_time'] = date('Y-m-d H:i:s');
        return WashRecharge::where('rech_id', $ids)
            ->update($data);
    }

    // 更改销户状态
    public static function deleteState($data, $state)
    {
        $update_data['rech_delete'] = $state;
        $update_data['rech_remark'] = $data['rech_remark'];
        $update_data['rech_update_time'] = date('Y-m-d H:i:s');
        return WashRecharge::where('rech_id', $data['rech_id'])
            ->update($update_data);
    }

    // 会员客户充值详情
    public static function info($user_info, $request)
    {
        $info = DB::table('wash_recharge')
            ->where('rech_shop_id', $user_info->adm_shop_id)
            ->where('rech_type', $request['rech_type'])
            ->where('rech_id', $request['rech_id'])
            ->select('rech_id', 'rech_client_name', 'rech_phone', 'rech_car_num', 'rech_car_vin', 'rech_balance', 'rech_time_start', 'rech_time_end')
            ->first();
        $rech_info = DB::table('wash_recharge_info')
            ->where('rein_rech_id', $info->rech_id)
            ->select('rein_money', 'rein_content', 'rein_car_num', 'rein_car_vin', 'rein_name', 'rein_phone', 'rein_create_time')
            ->get()->toArray();
        if (empty($info)) {
            return ['code'=>ErrorInc::DATA_EMPTY, 'msg'=>'没查到充值记录', 'data'=>''];
        }

        $data['info'] = $info;
        $data['rech_info'] = $rech_info;
        return ['code'=>200, 'msg'=>'success', 'data'=>$data];
    }

    // 充值
    public static function recharge($user_info, $request)
    {
        $rein_data['rein_rech_id'] = $request['rech_id'];
        $rein_data['rein_shop_id'] = $user_info->adm_shop_id;
        $rein_data['rein_money'] = $request['rech_money'] * 100;
        $rein_data['rein_content'] = '充值';
        $rein_data['rein_name'] = $request['rech_client_name'] ?: ''; //姓名
        $rein_data['rein_phone'] = $request['rech_phone'] ?: ''; //电话
        $rein_data['rein_car_num'] = $request['rech_car_num'] ?: ''; //车牌号
        $rein_data['rein_car_vin'] = $request['rech_car_vin'] ?: ''; //车架号
        $rein_data['rein_create_adm_id'] = $user_info->adm_id; //创建人
        $rein_data['rein_create_time'] = date('Y-m-d H:i:s');
        $rein_res = DB::table('wash_recharge_info')->insert($rein_data);

        $find_data = DB::table('wash_recharge')
            ->where('rech_id', $request['rech_id'])
            ->select('rech_total_money', 'rech_balance')
            ->first();
        $update_data['rech_total_money'] = $find_data->rech_total_money + $request['rech_money'] * 100;
        $update_data['rech_balance'] = $find_data->rech_balance + $request['rech_money'] * 100;
        $update_data['rech_update_time'] = date('Y-m-d H:i:s');
        $rech_res = DB::table('wash_recharge')
            ->where('rech_id', $request['rech_id'])
            ->update($update_data);
        if ($rech_res && $rein_res) {
            return true;
        } else {
            return false;
        }
    }
}
