package com.gxwebsoft.cms.controller;

import com.gxwebsoft.cms.entity.CmsContactLead;
import com.gxwebsoft.cms.param.CmsContactLeadParam;
import com.gxwebsoft.cms.service.CmsContactLeadService;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 联系表单/销售线索控制器
 *
 * @author 科技小王子
 * @since 2026-03-30
 */
@Slf4j
@Validated
@Tag(name = "联系表单/销售线索管理")
@RestController
@RequestMapping("/api/cms/cms-contact-lead")
public class CmsContactLeadController extends BaseController {

    @Resource
    private CmsContactLeadService cmsContactLeadService;

    // -------------------------
    //  公开接口（无需登录）
    // -------------------------

    /**
     * 提交联系表单（官网 /contact 页调用，不需要登录）
     */
    @Operation(summary = "提交联系表单")
    @PostMapping("/submit")
    public ApiResult<?> submit(@RequestBody @Valid CmsContactLead lead, HttpServletRequest request) {
        // 获取客户端真实IP
        String ip = getClientIp(request);
        if (cmsContactLeadService.submit(lead, ip)) {
            return success("提交成功，我们将尽快与您联系！");
        }
        return fail("提交失败，请稍后重试");
    }

    // -------------------------
    //  后台管理接口（需要权限）
    // -------------------------

    @Operation(summary = "分页查询线索列表")
    @PreAuthorize("hasAuthority('cms:contactLead:list')")
    @GetMapping("/page")
    public ApiResult<PageResult<CmsContactLead>> page(CmsContactLeadParam param) {
        return success(cmsContactLeadService.pageRel(param));
    }

    @Operation(summary = "查询全部线索")
    @PreAuthorize("hasAuthority('cms:contactLead:list')")
    @GetMapping()
    public ApiResult<List<CmsContactLead>> list(CmsContactLeadParam param) {
        return success(cmsContactLeadService.listRel(param));
    }

    @Operation(summary = "根据ID查询线索")
    @PreAuthorize("hasAuthority('cms:contactLead:list')")
    @GetMapping("/{id}")
    public ApiResult<CmsContactLead> get(@PathVariable("id") Integer id) {
        return success(cmsContactLeadService.getById(id));
    }

    @Operation(summary = "更新跟进状态/备注")
    @PreAuthorize("hasAuthority('cms:contactLead:update')")
    @PutMapping()
    public ApiResult<?> update(@RequestBody CmsContactLead lead) {
        if (cmsContactLeadService.updateById(lead)) {
            return success("更新成功");
        }
        return fail("更新失败");
    }

    @Operation(summary = "删除线索")
    @PreAuthorize("hasAuthority('cms:contactLead:remove')")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (cmsContactLeadService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @Operation(summary = "批量修改")
    @PreAuthorize("hasAuthority('cms:contactLead:update')")
    @PutMapping("/batch")
    public ApiResult<?> updateBatch(@RequestBody BatchParam<CmsContactLead> batchParam) {
        if (batchParam.update(cmsContactLeadService, "lead_id")) {
            return success("批量修改成功");
        }
        return fail("批量修改失败");
    }

    @Operation(summary = "批量删除")
    @PreAuthorize("hasAuthority('cms:contactLead:remove')")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (cmsContactLeadService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    // -------------------------
    //  工具方法
    // -------------------------

    /**
     * 获取客户端真实IP（兼容反向代理）
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // X-Forwarded-For 多个IP取第一个
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }
}
