package com.cyksj.web.controller.user;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.model.entity.Address;
import com.cyksj.service.user.AddressService;
import com.cyksj.service.user.UserBindRelationService;
import com.cyksj.web.util.StpUserUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author chan
 * @date 2022/10/13 3:07 PM
 */
@RestController
@RequestMapping("/applets/address")
@RequiredArgsConstructor
public class AddressController {

    private final AddressService addressService;

    private final UserBindRelationService userBindRelationService;

    @GetMapping("/get")
    public Result<List<Address>> get(){
        long userId = StpUserUtil.getLoginIdAsLong();
        List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
        List<Address> addressList = addressService.list(Wrappers.lambdaQuery(Address.class).in(Address::getUserId, userIdList));
        return GatewayResponse.SUCCESS.newBuilder().toResult(addressList);
    }

    @Transactional(rollbackFor = Throwable.class)
    @PostMapping("/post")
    public Result<Address> save(@RequestBody Address address){
        long userId = StpUserUtil.getLoginIdAsLong();
        List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
        int count = addressService.count(Wrappers.lambdaQuery(Address.class).in(Address::getUserId, userIdList));
        if (count >= 20) {
            throw new BusinessRuntimeException("收货地址最多可添加20条, 请清理后再添加.");
        }
        if (count == 0) {
            // 当前新增的地址是唯一一个地址时 无论用户是否设为默认地址 都设为默认地址
            address.setIsDefault(true);
        }

        if(address.getIsDefault() != null && address.getIsDefault() ){
            addressService.update(Wrappers.lambdaUpdate(Address.class).in(Address::getUserId,userIdList).set(Address::getIsDefault,false));
        }
        address.setUserId(userId);
        addressService.save(address);
        return GatewayResponse.SUCCESS.newBuilder().toResult(address);
    }

    @Transactional(rollbackFor = Throwable.class)
    @PutMapping("/update")
    public Result<Address> update(@RequestBody Address address){

        long userId = StpUserUtil.getLoginIdAsLong();
        List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
        if(address.getIsDefault() != null && address.getIsDefault() ){
            addressService.update(Wrappers.lambdaUpdate(Address.class).in(Address::getUserId,userIdList).set(Address::getIsDefault,false));
        }

        addressService.updateById(address);
        return GatewayResponse.SUCCESS.newBuilder().toResult(address);
    }

    @DeleteMapping("/delete/{id}")
    public Result<String> delete(@PathVariable Long id){
        long userId = StpUserUtil.getLoginIdAsLong();
        List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
        Address one = addressService.getOne(Wrappers.lambdaQuery(Address.class)
                .eq(Address::getId, id)
                .in(Address::getUserId, userIdList));
        if (one != null) {
            addressService.removeById(id);
        }
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }


}
