<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016～2022 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------


namespace app\wap\model\user;


use basic\ModelBasic;
use traits\ModelTrait;

/**收货地址表
 * Class UserAddress
 * @package app\wap\model\user
 */
class UserAddress extends ModelBasic
{
    use ModelTrait;

    protected $insert = ['add_time'];

    protected function setAddTimeAttr()
    {
        return time();
    }

    public static function setDefaultAddress($id, $uid)
    {
        self::beginTrans();
        $res1 = self::where('uid', $uid)->update(['is_default' => 0]);
        $res2 = self::where('id', $id)->where('uid', $uid)->update(['is_default' => 1]);
        $res = $res1 !== false && $res2 !== false;
        self::checkTrans($res);
        return $res;
    }

    public static function userValidAddressWhere($model = null, $prefix = '')
    {
        if ($prefix) $prefix .= '.';
        $model = self::getSelfModel($model);
        return $model->where("{$prefix}is_del", 0);
    }

    public static function getUserValidAddressList($uid, $field = '*')
    {
        return self::userValidAddressWhere()->where('uid', $uid)->order('add_time DESC')->field($field)->select()->toArray() ?: [];
    }

    public static function getUserDefaultAddress($uid, $field = '*')
    {
        return self::userValidAddressWhere()->where('uid', $uid)->where('is_default', 1)->field($field)->find();
    }
}
