<?php

/**
 * 用户账户服务
 *
 * @author lixiaolin
 * @Date: 2021/8/31
 * @Time: 下午9:56
 * @Email: lixiaolin@bluearp.com
 * @version 1.0
 * @copyright BlueCity
 */

namespace App\Services;

use App\Inc\CacheInc;
use App\Inc\CommonInc;
use App\Models\MemberVehicles;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use App\Models\MemberAccount;
use Illuminate\Support\Facades\DB;

class AccountService extends Service
{
    public static $instance;
    public $modelMain = null;

    public function __construct()
    {
        $this->modelMain = new MemberAccount();
    }

    /**
     * @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 search($param, $columns = array('*'), $page = 1, $pageSize = 20)
    {
        $shopID = LoginUserService::getUserShopID();
        $where = [];
        $where[] = ['mem_shop_id', '=', $shopID];

        if (!empty($param['phone'])) {
            $where[] = ['mem_phone', '=', $param['phone']];
        }
        if (!empty($param['keywords'])) {
            $where[] = ['mem_name', 'like',  '%'.$param['keywords'].'%'];
        }
        if (!empty($param['car_num'])) {
            $where[] = ['mem_car_num', '=', $param['car_num']];
        }
        if (!empty($param['car_series'])) {
            $where[] = ['mem_car_series', '=', $param['car_series']];
        }
        if (!empty($param['max'])) {
            $where[] = ['mem_balance', '=<', $param['max']];
        }
        if (!empty($param['min'])) {
            $where[] = ['mem_balance', '>=', $param['min']];
        }
        if (!empty($param['create_date'])) {
            $where[] = ['mem_create_time', '>', $param['create_date']];
            $where[] = ['mem_create_time', '<', $param['create_date'] + 1];
        }

        $count = $this->modelMain
            ->where($where)
            ->count();
        $totalPage = ceil($count / $pageSize);
        if ($pageSize > 0) {
            $offset = ($page - 1) * $pageSize;

            $list = $this->modelMain
                ->where($where)
                ->select($columns)
                ->orderBy('mem_id', 'ASC')
                ->offset($offset)
                ->limit($pageSize)
                ->get();
        } else {
            $list = $this->modelMain
                ->where($where)
                ->select($columns)
                ->orderBy('mem_id', 'ASC')
                ->get();
        }
        $result = [];
        $result['page'] = ['totalPage' => $totalPage, 'count' => $count, 'page' => $page, 'page_size' => $pageSize];
        $result['list'] = $list;

        return $result;
    }

    public function create(array $request)
    {
        $mem_add_data['mem_cid'] = $request['adm_cid'];
        $mem_add_data['mem_shop_id'] = $request['shop_id'];
        $mem_add_data['mem_superior_shop_id'] = $request['superior_shop_id'];
        $mem_add_data['mem_name'] = $request['mem_name'];
        $mem_add_data['mem_sex'] = $request['mem_sex'];
        $mem_add_data['mem_phone'] = $request['mem_phone'];
        $mem_add_data['mem_birthday'] = $request['mem_birthday'] ? $request['mem_birthday'] : '';
        $mem_add_data['mem_car_num'] = str_replace(' ', '', $request['mem_car_num']);
        $mem_add_data['mem_car_series'] = $request['mem_car_series'] ? $request['mem_car_series'] : '';
        $mem_add_data['mem_car_model'] = $request['mem_car_model'] ? $request['mem_car_model'] : '';
        $mem_add_data['mem_province'] = $request['mem_province'];
        $mem_add_data['mem_city'] = $request['mem_city'];
        $mem_add_data['mem_county'] = $request['mem_county'];
        $mem_add_data['mem_address'] = $request['mem_address'];
        $mem_add_data['mem_bership'] = $request['mem_bership'];
//        $mem_id =  DB::table('member')->insertGetId($mem_add_data);
//
//        return $mem_id;
        $entity = parent::create($mem_add_data);
        if ($entity) {
            return $entity;
//            return $entity->mem_id;
        }

        return false;
    }

    public function update(array $request, int $ID, $attribute = 'mem_id')
    {
        $mem_edit_data = [];
        $mem_edit_data['mem_name'] = $request['mem_name'];
        $mem_edit_data['mem_sex'] = $request['mem_sex'];
        $mem_edit_data['mem_phone'] = $request['mem_phone'];
        $mem_edit_data['mem_birthday'] = $request['mem_birthday'] ? $request['mem_birthday'] : '';
        $mem_edit_data['mem_province'] = $request['mem_province'];
        $mem_edit_data['mem_city'] = $request['mem_city'];
        $mem_edit_data['mem_county'] = $request['mem_county'];
        $mem_edit_data['mem_address'] = $request['mem_address'];
        $mem_edit_data['mem_bership'] = $request['mem_bership'];
        $mem_edit_data['mem_update_time'] = date('Y-m-d H:i:s');

        $entity = parent::update($mem_edit_data, $ID, $attribute);
        if ($entity) {
            return $entity;
        }

        return false;
    }

    public static function lockAccount($memberID) {
        $accountLockKey = 'account_lock_'. $memberID;
        $lockExist = Cache::has($accountLockKey);
        if ($lockExist) {
            return false;
        }
        $result = Cache::add($accountLockKey, 1, CacheInc::LOCK_TIME);

        return $result;
    }

    public static function unlockAccount($memberID) {
        $accountLockKey = 'account_lock_'. $memberID;
        $lockExist = Cache::has($accountLockKey);
        if ($lockExist) {
            return false;
        }
        return Cache::forget($accountLockKey);
    }

    public static function changeBalance($account, $changeValue, $changeType) {
        $loginUser = LoginUserService::getUser();
        $preBalance = $afterBalance = $account['balance'];
        $memberID = $account['mem_id'];

        if ($changeType == CommonInc::ACCOUNT_LOG_TYPE_RECHARGE) {
            $logType = CommonInc::ACCOUNT_BALANCE_ADD;
            $afterBalance = $preBalance + $changeType;
        } elseif ($changeType == CommonInc::ACCOUNT_LOG_TYPE_ORDER) {
            $logType = CommonInc::ACCOUNT_BALANCE_REDUCE;
            $afterBalance = $preBalance - $changeType;
        }
        $data['balance'] = $afterBalance;

        $res = MemberAccount::where('mem_id', $memberID)->update($data);
        if ($res) {
            $log = [];
            $log['member_id']        = $data['member_id'];
            $log['log_type']         = $logType;
            $log['change_value']     = $changeValue;
            $log['change_type']      = $changeType;
            $log['superior_shop_id'] = $loginUser['superior_shop_id'];
            $log['com_id']           = $loginUser['com_id'];
            $log['shop_id']          = $loginUser['shop_id'];
            $log['create_uid']       = $loginUser['adm_id'];
            $log['pre_value']        = $preBalance;
            $log['after_value']      = $afterBalance;
            $logRes = (new AccountLogService())->create($log);
            if ($logRes) return true;
        }

        return false;
    }

    /**
     * 设置开关
     * @param int $id       内容ID
     * @param int $enable   开关值
     * @param int $shopID   门店编号
     *
     * @return mixed
     */
    public function setEnable(int $id, $enable = 1, $shopID = 0) {
        if ($shopID == 0) {
            $shopID = LoginUserService::getUserShopID();
        }
        return $this->modelMain
            ->where('mem_id', $id)
            ->where('mem_shop_id', $shopID)
            ->update(['enabled' => $enable]);
    }

    /**
     * 获取单行数据
     * @param int    $id       内容ID
     * @param mixed  $fields   字段
     * @param int    $shopID   门店编号
     *
     * @return mixed
     */
    public static function getFieldsById($id, $fields = '*', $shopID = 0){
        if ($shopID == 0) {
            $shopID = LoginUserService::getUserShopID();
        }
        return MemberAccount::where('mem_id', $id)
            ->where('mem_shop_id', $shopID)
            ->select($fields)
            ->first();
    }

    /**
     * 判断是否存在
     * @param array  $where    条件字段
     * @param int    $shopID   门店编号
     *
     * @return mixed
     */
    public static function getExists($where, $shopID = 0) {
        if ($shopID == 0) {
            $shopID = LoginUserService::getUserShopID();
        }
        return MemberAccount::where('mem_shop_id', $shopID)
            ->where($where)
            ->exist();
    }

    /**
     * 获取首条
     * @param array  $where    条件字段
     * @param int    $shopID   门店编号
     *
     * @return mixed
     */
    public static function getOne($where, $shopID = 0) {
        if ($shopID == 0) {
            $shopID = LoginUserService::getUserShopID();
        }
        return MemberAccount::where('mem_shop_id', $shopID)
            ->where($where)
            ->first();
    }

    /**
     * 获取确定行数据
     *
     * @param int $ID       获取ID值
     * @param int $shopID   门店ID
     *
     * @return mixed
     */
    public static function getByID(int $ID,  $shopID = 0) {
        if ($shopID == 0) {
            $shopID = LoginUserService::getUserShopID();
        }

        return MemberAccount::where('mem_id', $ID)
            ->where('mem_shop_id', $shopID)
            ->where('enabled', 1)
            ->first();
    }

    /**
     * 获取用户汽车
     *
     * @param int $memberID       获取用户ID值
     *
     * @return mixed
     */
    public static function getMemberVehicles($memberID) {
        return MemberVehicles::where('meca_mem_id', $memberID)
            ->get();
    }
}
