/**
 * BladeX Commercial License Agreement
 * Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
 * <p>
 * Use of this software is governed by the Commercial License Agreement
 * obtained after purchasing a license from BladeX.
 * <p>
 * 1. This software is for development use only under a valid license
 * from BladeX.
 * <p>
 * 2. Redistribution of this software's source code to any third party
 * without a commercial license is strictly prohibited.
 * <p>
 * 3. Licensees may copyright their own code but cannot use segments
 * from this software for such purposes. Copyright of this software
 * remains with BladeX.
 * <p>
 * Using this software signifies agreement to this License, and the software
 * must not be used for illegal purposes.
 * <p>
 * Author: Chill Zhuang (bladejava@qq.com)
 */
package org.springblade.transport.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.annotation.PreAuth;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.transport.excel.CommonAddressExcel;
import org.springblade.transport.pojo.entity.CommonAddress;
import org.springblade.transport.pojo.vo.CommonAddressRemoveResultVO;
import org.springblade.transport.pojo.vo.CommonAddressVO;
import org.springblade.transport.service.ICommonAddressService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

/**
 * 常用地址 控制器
 *
 * @author Chill
 */
@RestController
@AllArgsConstructor
@PreAuth(menu = "common_address")
@RequestMapping("/common-address")
@Tag(name = "常用地址", description = "常用地址")
public class CommonAddressController extends BladeController {

	private static final int DEFAULT_CURRENT = 1;
	private static final int DEFAULT_SIZE = 10;
	private static final int MAX_SIZE = 100;
	private static final String NORMAL_SITE_CODE = "/";

	private final ICommonAddressService commonAddressService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description = "传入id")
	public R<CommonAddressVO> detail(@Parameter(description = "主键", required = true) @RequestParam Long id) {
		return R.data(commonAddressService.detail(id));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@Operation(summary = "分页", description = "传入commonAddress")
	public R<IPage<CommonAddressVO>> list(CommonAddressVO commonAddress, Query query) {
		IPage<CommonAddressVO> pages = commonAddressService.selectCommonAddressPage(Condition.getPage(normalizeQuery(query)), commonAddress);
		return R.data(pages);
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 3)
	@Operation(summary = "新增或修改", description = "传入commonAddress")
	public R submit(@RequestBody CommonAddress commonAddress) {
		return R.status(commonAddressService.submit(commonAddress));
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 4)
	@Operation(summary = "逻辑删除", description = "传入ids")
	public R<CommonAddressRemoveResultVO> remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
		return R.data(commonAddressService.removeAddress(ids));
	}

	/**
	 * 来源地址选项
	 */
	@GetMapping("/source-options")
	@ApiOperationSupport(order = 5)
	@Operation(summary = "来源地址选项", description = "传入addressType和keyword")
	public R<List<CommonAddressVO>> sourceOptions(@RequestParam String addressType,
												  @RequestParam(required = false) String keyword) {
		return R.data(commonAddressService.sourceOptions(addressType, keyword));
	}

	/**
	 * 导出常用地址
	 */
	@GetMapping("/export-common-address")
	@ApiOperationSupport(order = 6)
	@Operation(summary = "导出常用地址")
	public void exportCommonAddress(CommonAddressVO commonAddress,
									@RequestParam(required = false) String ids,
									HttpServletResponse response) {
		List<CommonAddressExcel> list = commonAddressService.exportCommonAddress(buildExportQuery(commonAddress, ids));
		ExcelUtil.export(response, "常用地址" + DateUtil.time(), "常用地址", list, CommonAddressExcel.class);
	}

	private Query normalizeQuery(Query query) {
		if (query == null) {
			query = new Query();
		}
		if (query.getCurrent() == null || query.getCurrent() < DEFAULT_CURRENT) {
			query.setCurrent(DEFAULT_CURRENT);
		}
		if (query.getSize() == null || query.getSize() <= 0) {
			query.setSize(DEFAULT_SIZE);
		}
		if (query.getSize() > MAX_SIZE) {
			query.setSize(MAX_SIZE);
		}
		return query;
	}

	private LambdaQueryWrapper<CommonAddress> buildExportQuery(CommonAddressVO commonAddress, String ids) {
		LambdaQueryWrapper<CommonAddress> queryWrapper = Wrappers.<CommonAddress>lambdaQuery()
			.eq(CommonAddress::getIsDeleted, 0)
			.orderByDesc(CommonAddress::getUpdateTime)
			.orderByDesc(CommonAddress::getCreateTime);
		if (Func.isNotEmpty(ids)) {
			queryWrapper.in(CommonAddress::getId, Func.toLongList(ids));
		}
		if (Objects.equals(commonAddress.getAllDept(), 1)) {
			if (!AuthUtil.isAdministrator()) {
				throw new ServiceException("无权导出全部组织常用地址");
			}
		} else {
			queryWrapper.eq(CommonAddress::getDeptId, currentDeptId());
		}
		if (Objects.equals(commonAddress.getAllDept(), 1) && Func.isNotEmpty(commonAddress.getDeptId())) {
			queryWrapper.eq(CommonAddress::getDeptId, commonAddress.getDeptId());
		}
		if (Func.isNotEmpty(commonAddress.getAddressName())) {
			queryWrapper.like(CommonAddress::getAddressName, commonAddress.getAddressName().trim());
		}
		if (Func.isNotEmpty(commonAddress.getAddressType())) {
			queryWrapper.eq(CommonAddress::getAddressType, commonAddress.getAddressType().trim());
		}
		if (Func.isNotEmpty(commonAddress.getDetailAddress())) {
			queryWrapper.like(CommonAddress::getDetailAddress, commonAddress.getDetailAddress().trim());
		}
		if (Func.isNotEmpty(commonAddress.getRegionName())) {
			queryWrapper.like(CommonAddress::getRegionName, commonAddress.getRegionName().trim());
		}
		if (Func.isNotEmpty(commonAddress.getSiteCode()) && !NORMAL_SITE_CODE.equals(commonAddress.getSiteCode().trim())) {
			queryWrapper.eq(CommonAddress::getSiteCode, commonAddress.getSiteCode().trim());
		}
		if (Func.isNotEmpty(commonAddress.getContactName())) {
			queryWrapper.like(CommonAddress::getContactName, commonAddress.getContactName().trim());
		}
		if (Func.isNotEmpty(commonAddress.getContactPhone())) {
			queryWrapper.like(CommonAddress::getContactPhone, commonAddress.getContactPhone().trim());
		}
		return queryWrapper;
	}

	private Long currentDeptId() {
		Long deptId = Func.firstLong(AuthUtil.getDeptId());
		if (Func.isEmpty(deptId) || deptId <= 0) {
			throw new ServiceException("当前用户所属组织为空，无法导出常用地址");
		}
		return deptId;
	}

}
