<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */


namespace app\api\logic;


use app\common\enum\YesNoEnum;
use app\common\logic\BaseLogic;
use app\common\model\Region;
use app\common\model\UserAddress;


/**
 * 用户地址逻辑
 * Class UserAddressLogic
 * @package app\api\logic
 */
class UserAddressLogic extends BaseLogic
{

    /**
     * @notes 列表
     * @param $userId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getLists($userId)
    {
        return UserAddress::where(['user_id' => $userId])->select()->toArray();
    }



    /**
     * @notes 详情
     * @param $addressId
     * @param $userId
     * @return array
     */
    public static function getDetail($addressId, $userId)
    {
        return UserAddress::getAddressById($userId, $addressId)->toArray();
    }


    /**
     * @notes 获取默认地址
     * @param $userId
     * @return array
     */
    public static function getDefault($userId)
    {
        return UserAddress::getDefaultAddress($userId)->toArray();
    }


    /**
     * @notes 设置默认地址
     * @param $params
     * @param $userId
     */
    public static function setDefault($params, $userId)
    {
        UserAddress::where(['user_id' => $userId])->update(['is_default' => YesNoEnum::NO]);
        UserAddress::where(['id' => $params['id'], 'user_id' => $userId])->update(['is_default' => YesNoEnum::YES]);
    }

    /**
     * @notes 添加地址
     * @param $params
     * @param $userId
     */
    public static function addAddress($params, $userId)
    {
        if ($params['is_default'] == YesNoEnum::YES) {
            UserAddress::where(['user_id' => $userId])->update(['is_default' => YesNoEnum::NO]);
        } else {
            $isFirst = UserAddress::where(['user_id' => $userId])->findOrEmpty();
            if ($isFirst->isEmpty()) {
                $params['is_default'] = YesNoEnum::YES;
            }
        }

        UserAddress::create([
            'user_id'       => $userId,
            'contact'       => $params['contact'],
            'mobile'        => $params['mobile'],
            'province_id'   => $params['province_id'],
            'city_id'       => $params['city_id'],
            'district_id'   => $params['district_id'],
            'address'       => $params['address'],
            'is_default'    => $params['is_default'] ?? YesNoEnum::NO,
            'create_time'   => time()
        ]);
    }


    /**
     * @notes 编辑地址
     * @param $params
     */
    public static function editAddress($params)
    {
        if ($params['is_default'] == YesNoEnum::YES) {
            UserAddress::where(['user_id' => $params['user_id']])->update(['is_default' => YesNoEnum::NO]);
        }

        UserAddress::update([
            'contact'       => $params['contact'],
            'mobile'        => $params['mobile'],
            'province_id'   => $params['province_id'],
            'city_id'       => $params['city_id'],
            'district_id'   => $params['district_id'],
            'address'       => $params['address'],
            'is_default'    => $params['is_default'],
        ], ['id' => $params['id'], 'user_id' => $params['user_id']]);
    }


    /**
     * @notes  删除
     * @param $params
     */
    public static function del($params)
    {
        UserAddress::destroy(['user_id' => $params['user_id'], 'id' => $params['id']]);
    }

    /**
     * @notes 将省市区名称转为id
     * @param $params
     * @return string[]
     */
    public static function handleRegion($params)
    {
        $province = self::handleRegionField($params['province'], 1);
        $city = self::handleRegionField($params['city'], 2,$province);
        $district = self::handleRegionField($params['district'], 3,$city);
        $result = [
            'province' => $province,
            'city' => $city,
            'district' => $district,
        ];
        return $result;
    }

    /**
     * @notes 根据地址名称获取id
     * @param $field
     * @param $level
     * @return mixed|string
     */
    public static function handleRegionField($field, $level,$partnerId = 100000)
    {
        $region = Region::where([
            ['level', '=', $level],
            ['name', 'like', '%' . $field . '%'],
            ['parent_id', '=', $partnerId]
        ])->findOrEmpty();

        if($region->isEmpty()) {
            return '';
        }
        return $region->id;
    }

    /**
     * @notes 获取地区
     * @param int $pid
     * @return Region[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author lgp
     * @date 2022/11/8 6:42 下午
     */
    public static function getRegion($pid = 0){
        $where = [];
        if(0 === $pid){
            $where[] = ['level','=',1];
        }else{
            $where[] = ['parner_id','=',$pid];
        }
        $regionLists = Region::where($where)->field('id,name')->select();
        return $regionLists;
    }
}
