/*
 *      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.sing.user.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import org.springblade.core.launch.constant.AppConstant;
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.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.sing.user.entity.UserAddress;
import org.springblade.sing.user.vo.UserAddressVO;
import org.springblade.sing.user.wrapper.UserAddressWrapper;
import org.springblade.sing.user.service.IUserAddressService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户收获地址表 控制器
 *
 * @author BladeX
 * @since 2021-11-09
 */
@RestController
@AllArgsConstructor
@RequestMapping("sing_user/useraddress")
@Api(value = "用户收获地址表", tags = "用户收获地址表接口")
public class UserAddressController extends BladeController {

	private final IUserAddressService userAddressService;
	private final String MAP_URL = "https://apis.map.qq.com/ws/geocoder/v1/?location=";
	private final String MAP_KEY = "WAGBZ-EFIKU-2W2VF-4UX5F-ATB3F-HKBFU";

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入userAddress")
	public R<UserAddressVO> detail(UserAddress userAddress) {
		UserAddress detail = userAddressService.getOne(Condition.getQueryWrapper(userAddress));
		return R.data(UserAddressWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 用户收获地址表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入userAddress")
	public R<IPage<UserAddressVO>> list(UserAddress userAddress, Query query) {
		LambdaQueryWrapper<UserAddress> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(userAddress.getPhone() != null,UserAddress::getPhone,userAddress.getPhone());
		wrapper.eq(userAddress.getUserId() != null,UserAddress::getUserId,userAddress.getUserId());
		wrapper.like(userAddress.getAddress() != null,UserAddress::getAddress,userAddress.getAddress());
		wrapper.like(userAddress.getConsignee() != null,UserAddress::getConsignee,userAddress.getConsignee());
		wrapper.orderByDesc(UserAddress::getIsDefault);
		IPage<UserAddress> pages = userAddressService.page(Condition.getPage(query), wrapper);
		return R.data(UserAddressWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 用户收获地址表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入userAddress")
	public R<IPage<UserAddressVO>> page(UserAddressVO userAddress, Query query) {
		IPage<UserAddressVO> pages = userAddressService.selectUserAddressPage(Condition.getPage(query), userAddress);
		return R.data(pages);
	}

	/**
	 * 新增 用户收获地址表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入userAddress")
	public R save(@Valid @RequestBody UserAddress userAddress) {
		return R.status(userAddressService.save(userAddress));
	}

	/**
	 * 修改 用户收获地址表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入userAddress")
	public R update(@Valid @RequestBody UserAddress userAddress) {
		return R.status(userAddressService.updateById(userAddress));
	}

	/**
	 * 新增或修改 用户收获地址表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入userAddress")
	public R submit(@Valid @RequestBody UserAddress userAddress) {
		return R.status(userAddressService.saveOrUpdate(userAddress));
	}


	/**
	 * 删除 用户收获地址表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(userAddressService.deleteLogic(Func.toLongList(ids)));
	}

	@GetMapping("/getLocation")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "", notes = "传入rule")
	public R getLocationData(String latitude,String longitude) {
		String request_url = MAP_URL +latitude+","+longitude + "&key=" + MAP_KEY;
		String s = HttpUtil.get(request_url);
		JSONObject jsonObject = JSONUtil.parseObj(s);
		return R.data(jsonObject);
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submitAddress")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入userAddress")
	public R submitAddress(@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);
	}


}
