<?php

namespace app\admin\model\system;

use crmeb\traits\ModelTrait;
use crmeb\basic\BaseModel;

/**
 * 用户消费新增金额明细 model
 * Class User
 * @package app\admin\model\user
 */
class StoreBill extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'store_bill';

    use ModelTrait;


    //修改积分减少积分记录
    public static function expend($title, $store_id, $type, $number, $link_id = 0, $balance = 0, $mark = '')
    {
        $pm = 0;
        $id = self::getkeytoid('bill_id');
        $add_time = date("Y-m-d H:i:s");
        return self::create(compact('title', 'store_id', 'link_id', 'type', 'number', 'balance', 'mark', 'pm', 'add_time', 'id'));
    }

    //修改积分增加积分记录
    public static function income($title, $store_id, $type, $number, $link_id = 0, $balance = 0, $mark = '')
    {
        $pm = 1;
        $id = self::getkeytoid('bill_id');
        $add_time = date("Y-m-d H:i:s");
        return self::create(compact('title', 'store_id', 'link_id', 'type', 'number', 'balance', 'mark', 'pm', 'add_time', 'id'));
    }

    public static function getBillList($where)
    {
        $whereModel = self::setWhereList($where);
        $count = $whereModel->count();
        $data = ($data = $whereModel->page((int)$where['page'], (int)$where['limit'])->select()) && count($data) ? $data->toArray() : [];
        return compact('data', 'count');
    }

    public static function setWhereList($where)
    {
        $time['data'] = '';
        if ($where['start_time'] != '' && $where['end_time'] != '') {
            $time['data'] = $where['start_time'] . ' - ' . $where['end_time'];
        }
        $model = self::getModelTime($time, self::alias('A')
            ->join('system_store B', 'B.id=A.store_id')
            ->order('A.add_time desc,A.id desc'), 'A.add_time');
        if (trim($where['type']) != '') {
            $model = $model->where('A.type', $where['type']);
        }
        if ($where['nickname'] != '') {
            $model = $model->where('B.name|B.id', 'like', "%$where[nickname]%");
        }

        if (isset($where['store_id']) && $where['store_id'] != '') {
            $model = $model->where('A.store_id', $where['store_id']);
        }
        return $model->field(['A.*', 'A.add_time', 'B.id', 'B.name']);
    }

    /**
     * 用户获得总佣金
     * @return float
     */
    public static function getBrokerageCount()
    {
        return self::where('pm', 1)->where('type', 'product_sale')->sum('number');
    }

}