<?php
namespace app\models\system;
use crmeb\basic\BaseModel;
use crmeb\services\UtilService;
use crmeb\traits\ModelTrait;

class Card extends BaseModel
{
    use ModelTrait;
    public function  getCreateTimeAttr($name)
    {
        return date("Y-m-d H:i:s",$name);
    }

    /**
     * 生成卡券
     * @param $data
     * @return Card|bool|\think\Model
     */
    public static function do_create($data)
    {
        if(!isset($data['title']) || $data['title'] == '') return self::setErrorInfo('批次名称不能为空!', true);
        if(!isset($data['totle_num']) || $data['totle_num'] == 0) return self::setErrorInfo('批次数量不能为0!', true);
        $data['create_time'] = time();
        $rs  = self::create($data);
        $maxid = CardInfo::whereDay('create_time')->where('type',$data['type'])->order('id desc')->value('card_number');
        $left = sprintf("%s%s",date("ymd"),str_pad($data['type'],2,'0',STR_PAD_LEFT));
        if($maxid) {
            $maxid = bcadd(substr($maxid, strlen($left) - 1), 1);
        }
        else
        {
            $maxid = 1;
        }
        $data1['card_id'] = $rs['id'];
        $data1['type'] = $rs['type'];
        $all = [];
        for ($i=0;$i<$data['totle_num'];$i++)
        {
            $data1['card_number'] = $left.str_pad($maxid,7,'0',STR_PAD_LEFT);
            $data1['card_password'] = UtilService::random_code_type(8);
            $data1['create_time'] = time();
            $data1['amount'] = $data['amount'];
            $all[] = $data1;
            $maxid++;
        }
        CardInfo::limit(1000)->insertAll($all);
        return $rs;
    }

    /**
     * 获取列表
     * @param $where
     * @return array
     */
    public static function lst($where)
    {
        $model = new self;
        if(isset($where['amount']) && $where['amount']>0)
        {
            $model = $model->where('amount','=',$where['amount']);
        }
        if(isset($where['type']) && $where['type']>-1)
        {
            $model = $model->where('type','=',$where['type']);
        }
        if(isset($where['status']) && $where[
            'status']>-1)
        {
            $model = $model->where('status','=',$where['status']);
        }
        if (isset($where['data']) && $where['data'] != '') {
            list($startTime, $endTime) = explode(' - ', $where['data']);
            $model = $model->where('create_time', '>', strtotime($startTime));
            $model = $model->where('create_time', '<', strtotime($endTime) + 24 * 3600);
        }
        if(isset($where['key']) && $where['key']!='')
        {
            $model = $model->whereLike('title','%'.$where['key'].'%');
        }
        $model = $model->order("id desc");
        $count = $model->value('count(id)')?:0;
        $data = $model->page($where['page'],$where['limit'])->select()->toarray();
        return compact('count','data');
    }
}