<?php

namespace app\models\store;

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

class StoreRechargeCardBrokerage extends BaseModel
{
	/**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

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

    use ModelTrait;

    public static function merSet($mer_id, $alias = '')
    {
        return $mer_id ? self::where($alias ? $alias . '.mer_id' : 'mer_id', $mer_id) : new self;
    }

    protected function getAddTimeAttr($value)
    {
        if ($value) return date('Y-m-d H:i:s', $value);
        return '';
    }

    /**
     * 充值卡列表
     * @param $where
     * @return array
     */
    public static function systemPage($where)
    {
        $model = self::setWhere($where);
        $count = $model->count();
        $list = $model->page((int)$where['page'], (int)$where['limit'])
            ->select();
        return compact('count', 'list');
    }

    /**
     * 设置充值卡 where 条件
     * @param $where
     * @param null $model
     * @return mixed
     */
    public static function setWhere($where, $model = null)
    {
        $model = $model === null ? new self() : $model;
        $model = $model->where('mer_id', $where['mer_id']);
        return $model->order('id desc')->where('is_del', 0);
    }

    /**
     * 新增或编辑充值卡返现比例
     */
    public static function saveRechargeCardBrokerage($indata, $cid)
    {
        foreach($indata as $value){
            if(!$value){
                return $this->fail('请输入正确的返现比例');
            }
            if(!empty($value['id'])){
                $ids[] = $value['id'];
                self::edit($value, $value['id']);
            }else{
                $ids[] = self::insertGetId($value);
            }
        }
        $data[] = ['id', 'not in', $ids];
        $data[] = ['cid', '=', $cid];
        $overs = self::where($data)->select();
        foreach($overs as $over){
            self::destroy($over['id']);
        }
    }
}