<?php
/**
 * @package merchant
 *
 * @author xaboy
 * @day 2020-05-07
 *
 * 
 */

namespace app\common\dao\user;


use app\common\dao\BaseDao;
use app\common\enum\CommonEnum;
use app\common\model\user\UserAddress as model;
use app\entity\CommonEntity;
use app\entity\data\user\UserAddressEntity;

class UserAddressDao extends BaseDao
{


    /**
     * @return string
     * @author Qinii
     */
    protected function getModel(): string
    {
        return model::class;
    }


    public function userFieldExists($field, $value,$uid): bool
    {
        return (($this->getModel()::getDB())->where('uid',$uid)->where($field,$value)->count()) > 0;
    }

    public function changeDefault(int $uid)
    {
        return ($this->getModel()::getDB())->where('uid',$uid)->update(['is_default' => 0]);
    }

    public function getAll(int $uid)
    {
        return (($this->getModel()::getDB())->where('uid',$uid));
    }

    /**
     * 根据 地址ID 获取地址实体
     * @param int $addressId
     * @return CommonEntity
     */
    public function getAddressEntityByAddressId(int $addressId): CommonEntity
    {
        $addressData = [];
        try {
            /** @var model $model */
            $model = $this->getModel();
            $addressDataRes = $model::getDB()
                ->where('address_id', '=', $addressId)
                ->where('is_del', '=', CommonEnum::IS_DEL['No']['code'])
                ->find();
            if (!empty($addressDataRes)) {
                $addressData = $addressDataRes->toArray();
            }
        } catch (\Exception $e) {

        }
        return UserAddressEntity::newInstance($addressData);
    }
}
