<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\api\service\ucenter;

use app\common\model\users\UsersAddress as UsersAddressModel;
use app\common\service\Users as UsersService;
use app\common\model\Region as RegionModel;

/**
 * @package app\api\service\ucenter
 * @class Address
 * @author xzncit 2024-03-03
 */
class Address {

    public static function getList(){
        return UsersAddressModel::where("user_id",UsersService::get("id",0))->select()->map(function ($res){
            $res["address"] = RegionModel::getArea([$res["province"],$res["city"],$res["area"]]," ") . $res["address"];
            return $res;
        });
    }

    /**
     * 详情
     * @param $id
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function detail($id){
        $row = UsersAddressModel::where(["user_id"=>UsersService::get("id",0),"id"=>$id])->find();
        if(empty($row)){
            return [];
        }

        $row["area_name"] = RegionModel::getArea([$row["province"],$row["city"],$row["area"]],",");
        return $row;
    }

    /**
     * 保存
     * @param $data
     */
    public static function save($data){
        $data["user_id"] = UsersService::get("id",0);
        if(isset($data["id"]) && $row = UsersAddressModel::where("id",$data["id"])->where("user_id",UsersService::get("id",0))->find()){
            UsersAddressModel::where("id",$data["id"])->where("user_id",UsersService::get("id",0))->save($data);
        }else{
            $data["create_time"] = time();
            $data["is_default"]  = UsersAddressModel::where("user_id",UsersService::get("id",0))->count() ? 0 : 1;
            UsersAddressModel::create($data);
        }
    }

    /**
     * 修改状态
     * @param array $params
     */
    public static function status($params=[]){
        $condition = [];
        $condition[] = ["user_id","=",UsersService::get("id",0)];
        UsersAddressModel::where($condition)->save([ "is_default"=>0 ]);
        $condition[] = ["id","=",$params["id"]??0];
        UsersAddressModel::where($condition)->save([ "is_default"=>1 ]);
    }

    /**
     * 删除
     * @param $id
     */
    public static function delete($id){
        UsersAddressModel::where("id",$id)->where("user_id",UsersService::get("id",0))->delete();
    }

}