package com.ruoyi.web.controller.mall;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.mall.domain.MemberAddress;
import com.ruoyi.mall.mapper.MemberAddressMapper;
import com.ruoyi.mall.service.MemberAddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户地址 前端控制器
 * </p>
 *
 * @author xn
 * @since 2022-09-29
 */
@Api(tags = "用户地址", description = "提供用户地址相关的API")
@RestController
@RequestMapping("/api/address")
public class MemberAddressController {

    @Resource
    private MemberAddressMapper mapper;
    @Resource
    private MemberAddressService service;

    @ApiOperation("全国省市区list")
    @GetMapping("/addressList")
    public  RestResponse getAddressList(){
        return new RestResponse().setSuccess(true).setData(service.getAddressList());
    }
    @ApiOperation("新增收货地址")
    @PostMapping("/add")
    public RestResponse add(@RequestBody MemberAddress address){
        Long userId= SecurityUtils.getAppLoginUser().getAppUser().getId();
        address.setUserId(userId);
        if (address.getIsDefault()){
            changeDefault(userId);
        }
        mapper.insert(address);
        return new RestResponse().setSuccess(true).setMessage("成功");
    }

    @ApiOperation("收货地址列表")
    @PostMapping("/list")
    public RestResponse list(){
        Long userId= SecurityUtils.getAppLoginUser().getAppUser().getId();
        List<String> columns=new ArrayList<>();
        columns.add("add_time");
        columns.add("is_default");
        List<MemberAddress> list=mapper.selectList(new QueryWrapper<MemberAddress>()
                .eq("user_id",userId)
                .orderByDesc(columns));
        return new RestResponse().setSuccess(true).setMessage("成功").setData(list);
    }

    @ApiOperation("修改收货地址")
    @PostMapping("/edit")
    public RestResponse edit(@RequestBody MemberAddress address){
        Long userId= SecurityUtils.getAppLoginUser().getAppUser().getId();
        if (address.getIsDefault()){
            changeDefault(userId);
        }
        mapper.updateById(address);
        return new RestResponse().setSuccess(true).setMessage("成功");
    }

    @ApiOperation("删除收货地址")
    @PostMapping("/del")
    public RestResponse del(@RequestBody MemberAddress address){
        mapper.deleteById(address.getId());
        return new RestResponse().setSuccess(true).setMessage("成功");
    }

    public void changeDefault(Long userId){
        service.update(new UpdateWrapper<MemberAddress>().set("is_default",false).eq("user_id",userId));
    }



}

