<?php

namespace app\models\system;

use app\models\user\User;
use crmeb\basic\BaseModel;
use crmeb\traits\ModelTrait;

class SystemStoreMember extends BaseModel
{
    use ModelTrait;

    /**
     * 获取门店会员卡
     * @param int $reg_store_id
     * @return string
     */
    private static function getnextcardno($reg_store_id = 1)
    {
        $max = self::where('reg_store_id', $reg_store_id)->value('max(card_no)');
        $id = bcadd(substr($max, 4), 1);
        return str_pad($reg_store_id, "4", "0", STR_PAD_LEFT) . str_pad($id, 8, "0", STR_PAD_LEFT);
    }

    /**
     * 设置会员卡
     * @param $uid
     * @param int $reg_store_id
     * @return SystemStoreMember|\think\Model
     */
    public static function setstorecardno($uid, $reg_store_id = 1)
    {
        $card_no = self::getnextcardno($reg_store_id);
        $stock_rights = 1;
        User::where('uid', $uid)->update(['reg_store_id' => $reg_store_id]);
        return self::create(compact('uid', 'reg_store_id', 'card_no', 'stock_rights'));
    }

    /**
     * 获取用户会员卡
     * @param $uid
     * @return mixed
     */
    public static function getcardno($uid)
    {
        return self::where('uid', $uid)->value('card_no');
    }

    /**
     * 增加消费
     * @param $uid
     * @param $total_price
     */
    public static function add_consume($uid, $total_price)
    {
        $info = self::where('uid', $uid)->find();

        if (date("Y", time()) != $info['year']) {
            $consume_rights = bcsub(floor(bcdiv(bcadd($total_price, 0, 2), 1000, 2)), $info['use_consume_rights']);
            $data['year'] = date("Y");
            $data['consume_year'] = $total_price;
            return self::where('uid', $uid)->inc('consume_sum', $total_price)->inc('consume_rights', $consume_rights)->update($data);

        } else {
            $consume_rights = bcsub(floor(bcdiv(bcadd($total_price, $info['consume_sum'], 2), 1000, 2)), bcadd($info['use_consume_rights'], $info['consume_rights']));
            return self::where('uid', $uid)->inc('consume_sum', $total_price)->inc('consume_year', $total_price)->inc('consume_rights', $consume_rights)->update();
        }
    }

    public static function lst($where)
    {
        $model = new self;
        $model = $model->alias("a")->join("user b", "a.uid=b.uid", "left");
        if ($where['store_id'] > 0) $model = $model->where('a.reg_store_id', $where['store_id']);
        if ($where['key']) $model = $model->wherelike('b.phone|a.card_no', "%" . $where['key'] . "%");
        $model = $model->field('a.*,b.nickname,b.phone,b.avatar,b.now_money,b.consumer,b.integral');
        $count = $model->count();
        $data = $model->page($where['page'], $where['limit'])->order("a.uid desc")->select()->toarray();
        return compact('count', 'data');
    }
}