package com.fs.company.controller.newAdv;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fs.common.result.Result;
import com.fs.newAdv.domain.DomainUrl;
import com.fs.newAdv.service.IDomainService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 域名管理Controller
 *
 * @author zhangqin
 * @date 2025-11-06
 */
@Slf4j
@RestController
@RequestMapping("/adv/domains")
@Validated
public class DomainController {

    @Autowired
    private IDomainService domainService;

    /**
     * 分页查询域名列表
     *
     * @param name    域名名称（模糊查询）
     * @param domain  域名地址（模糊查询）
     * @param status  状态
     * @return 域名列表
     */
    @GetMapping("/page")
    public Result<IPage<DomainUrl>> page(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String domain,
            @RequestParam(required = false) Integer status) {
        Page<DomainUrl> pageParam = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<DomainUrl> queryWrapper = new LambdaQueryWrapper<>();

        if (StrUtil.isNotBlank(name)) {
            queryWrapper.like(DomainUrl::getName, name);
        }
        if (StrUtil.isNotBlank(domain)) {
            queryWrapper.like(DomainUrl::getDomain, domain);
        }
        if (status != null) {
            queryWrapper.eq(DomainUrl::getStatus, status);
        }

        queryWrapper.orderByDesc(DomainUrl::getCreateTime);

        IPage<DomainUrl> result = domainService.page(pageParam, queryWrapper);
        return Result.success(result);
    }


    /**
     * 根据ID查询域名详情
     *
     * @param id 域名ID
     * @return 域名详情
     */
    @GetMapping("/{id}")
    public Result<DomainUrl> getById(@PathVariable Long id) {
        log.info("查询域名详情 | id={}", id);

        DomainUrl domainUrl = domainService.getById(id);
        if (domainUrl == null) {
            return Result.error("域名不存在");
        }

        return Result.success(domainUrl);
    }

    /**
     * 新增域名
     *
     * @param request 域名信息
     * @return 操作结果
     */
    @PostMapping
    public Result<DomainUrl> create(@RequestBody @Validated DomainCreateRequest request) {
        log.info("新增域名 | name={}, domain={}", request.getName(), request.getDomain());

        // 检查域名是否已存在
        LambdaQueryWrapper<DomainUrl> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DomainUrl::getDomain, request.getDomain());
        long count = domainService.count(queryWrapper);
        if (count > 0) {
            return Result.error("域名已存在");
        }

        DomainUrl domainUrl = new DomainUrl();
        domainUrl.setName(request.getName());
        domainUrl.setDomain(request.getDomain());
        domainUrl.setStatus(request.getStatus() != null ? request.getStatus() : 1);
        domainUrl.setRemark(request.getRemark());

        boolean success = domainService.save(domainUrl);
        if (!success) {
            return Result.error("新增域名失败");
        }

        log.info("新增域名成功 | id={}", domainUrl.getId());
        return Result.success(domainUrl);
    }

    /**
     * 更新域名
     *
     * @param id      域名ID
     * @param request 域名信息
     * @return 操作结果
     */
    @PutMapping("/{id}")
    public Result<String> update(@PathVariable Long id,
                                  @RequestBody @Validated DomainUpdateRequest request) {
        log.info("更新域名 | id={}, name={}, domain={}", id, request.getName(), request.getDomain());

        DomainUrl domainUrl = domainService.getById(id);
        if (domainUrl == null) {
            return Result.error("域名不存在");
        }

        // 如果修改了域名地址，检查新域名是否已被其他记录使用
        if (StrUtil.isNotBlank(request.getDomain()) && !request.getDomain().equals(domainUrl.getDomain())) {
            LambdaQueryWrapper<DomainUrl> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DomainUrl::getDomain, request.getDomain())
                       .ne(DomainUrl::getId, id);
            long count = domainService.count(queryWrapper);
            if (count > 0) {
                return Result.error("域名已存在");
            }
        }

        domainUrl.setName(request.getName());
        domainUrl.setDomain(request.getDomain());
        domainUrl.setStatus(request.getStatus());
        domainUrl.setRemark(request.getRemark());

        boolean success = domainService.updateById(domainUrl);
        if (!success) {
            return Result.error("更新域名失败");
        }

        log.info("更新域名成功 | id={}", id);
        return Result.success("更新成功");
    }

    /**
     * 删除域名
     *
     * @param id 域名ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        log.info("删除域名 | id={}", id);

        DomainUrl domainUrl = domainService.getById(id);
        if (domainUrl == null) {
            return Result.error("域名不存在");
        }

        boolean success = domainService.removeById(id);
        if (!success) {
            return Result.error("删除域名失败");
        }

        log.info("删除域名成功 | id={}", id);
        return Result.success("删除成功");
    }

    /**
     * 批量删除域名
     *
     * @param ids 域名ID列表
     * @return 操作结果
     */
    @DeleteMapping("/batch")
    public Result<String> batchDelete(@RequestBody List<Long> ids) {
        log.info("批量删除域名 | ids={}", ids);

        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择要删除的域名");
        }

        boolean success = domainService.removeByIds(ids);
        if (!success) {
            return Result.error("批量删除域名失败");
        }

        log.info("批量删除域名成功 | count={}", ids.size());
        return Result.success("删除成功");
    }

    /**
     * 启用/禁用域名
     *
     * @param id     域名ID
     * @param status 状态（0禁用 1启用）
     * @return 操作结果
     */
    @PutMapping("/{id}/status")
    public Result<String> updateStatus(@PathVariable Long id, @RequestParam Integer status) {
        log.info("修改域名状态 | id={}, status={}", id, status);

        DomainUrl domainUrl = domainService.getById(id);
        if (domainUrl == null) {
            return Result.error("域名不存在");
        }

        domainUrl.setStatus(status);
        boolean success = domainService.updateById(domainUrl);
        if (!success) {
            return Result.error("修改状态失败");
        }

        log.info("修改域名状态成功 | id={}, status={}", id, status);
        return Result.success("修改成功");
    }

    /**
     * 域名创建请求DTO
     */
    @Data
    public static class DomainCreateRequest {
        @NotBlank(message = "域名名称不能为空")
        private String name;

        @NotBlank(message = "域名地址不能为空")
        private String domain;

        private Integer status;

        private String remark;
    }

    /**
     * 域名更新请求DTO
     */
    @Data
    public static class DomainUpdateRequest {
        @NotBlank(message = "域名名称不能为空")
        private String name;

        @NotBlank(message = "域名地址不能为空")
        private String domain;

        @NotNull(message = "状态不能为空")
        private Integer status;

        private String remark;
    }
}

