/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.gateway.client_gateway.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.ldt.user.entity.UserAddress;
import org.springblade.ldt.user.service.IUserAddressService;
import org.springblade.ldt.user.vo.UserAddressVO;
import org.springblade.ldt.user.wrapper.UserAddressWrapper;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 *  控制器
 *
 * @author BladeX
 * @since 2021-09-20
 */
@RestController
@AllArgsConstructor
@RequestMapping("client/useraddress")
@Api(value = "", tags = "接口")
public class ClientUserAddressController extends BladeController {

	private final IUserAddressService userAddressService;


	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入userAddress")
	public R<IPage<UserAddressVO>> list(UserAddress userAddress, Query query) {
		IPage<UserAddress> pages = userAddressService.page(Condition.getPage(query), Condition.getQueryWrapper(userAddress).lambda().orderByDesc(UserAddress::getIsDefault));
		return R.data(UserAddressWrapper.build().pageVO(pages));
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入userAddress")
	public R submit(@Valid @RequestBody UserAddress userAddress) {
		Assert.notNull(userAddress.getUserId(), "用户id不能为空");
		List<UserAddress> addressList = userAddressService.list(Condition.getQueryWrapper(new UserAddress()).lambda()
			.eq(UserAddress::getUserId, userAddress.getUserId()));

		if (Objects.isNull(userAddress.getId())) {
			return  R.status(this.saveAddress(userAddress, addressList));
		}
		return R.status(this.updateAddress(userAddress,addressList));
	}

	/**
	 * 修改地址
	 * @param userAddress
	 * @param addressList
	 * @return
	 */
	private boolean updateAddress(UserAddress userAddress, List<UserAddress> addressList) {
		if (!userAddress.getIsDefault()) {
			return userAddressService.updateById(userAddress);
		}
		//修改成默认地址
		List<UserAddress> defaultAddresses = addressList.stream().filter(item -> item.getIsDefault() && !item.getId().equals(userAddress.getId())).collect(Collectors.toList());
		if (CollUtil.isEmpty(defaultAddresses)) {
			return userAddressService.updateById(userAddress);
		}
		defaultAddresses.forEach(item -> item.setIsDefault(false));
		userAddressService.updateBatchById(defaultAddresses);
		return userAddressService.updateById(userAddress);
	}

	/**
	 * 新增地址
	 * @param userAddress
	 * @param addressList
	 * @return
	 */
	private boolean saveAddress(UserAddress userAddress,List<UserAddress> addressList) {
		//如果数据库中没有该用户的地址，将该新增的地址置为默认
		if (CollUtil.isEmpty(addressList)) {
			userAddress.setIsDefault(true);
			return userAddressService.save(userAddress);
		}
		//如果数据库中有用户的地址，且不是设置默认地址
		if (!userAddress.getIsDefault()) {
			return userAddressService.save(userAddress);
		}
		//设置默认地址,将旧的默认地址置为不默认
		List<UserAddress> defaultAddresses = addressList.stream().filter(UserAddress::getIsDefault).collect(Collectors.toList());
		if (CollUtil.isEmpty(defaultAddresses)) {
			return userAddressService.save(userAddress);
		}
		defaultAddresses.forEach(item -> item.setIsDefault(false));
		userAddressService.updateBatchById(defaultAddresses);
		return  userAddressService.save(userAddress);
	}
}
