package com.gxwebsoft.house.controller;

import cn.hutool.core.util.StrUtil;
import com.gxwebsoft.common.core.annotation.OperationLog;
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 com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.house.entity.HouseMessage;
import com.gxwebsoft.house.entity.HouseAiChatRequest;
import com.gxwebsoft.house.entity.HouseAiLeadRequest;
import com.gxwebsoft.house.ai.HouseAiAgentService;
import com.gxwebsoft.house.param.HouseMessageParam;
import com.gxwebsoft.house.service.HouseMessageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.regex.Pattern;

/**
 * AI找房留言控制器
 */
@Tag(name = "AI找房留言管理")
@RestController
@RequestMapping("/api/house/house-message")
public class HouseMessageController extends BaseController {

    private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");
    private static final Pattern WECHAT_PATTERN = Pattern.compile("^[a-zA-Z][-_a-zA-Z0-9]{5,19}$");

    @Resource
    private HouseMessageService houseMessageService;
    @Resource
    private HouseAiAgentService houseAiAgentService;

    @Operation(summary = "分页查询AI找房留言")
    @GetMapping("/page")
    public ApiResult<PageResult<HouseMessage>> page(HouseMessageParam param) {
        return success(houseMessageService.pageRel(param));
    }

    @Operation(summary = "查询全部AI找房留言")
    @GetMapping()
    public ApiResult<List<HouseMessage>> list(HouseMessageParam param) {
        return success(houseMessageService.listRel(param));
    }

    @Operation(summary = "根据id查询AI找房留言")
    @GetMapping("/{id}")
    public ApiResult<HouseMessage> get(@PathVariable("id") Integer id) {
        return success(houseMessageService.getByIdRel(id));
    }

    @OperationLog
    @Operation(summary = "添加AI找房留言")
    @PostMapping()
    public ApiResult<?> save(@RequestBody HouseMessage houseMessage) {
        String error = validateMessage(houseMessage);
        if (error != null) {
            return fail(error);
        }
        User loginUser = getLoginUser();
        if (loginUser != null) {
            houseMessage.setUserId(loginUser.getUserId());
        }
        houseMessage.setRealName(houseMessage.getRealName().trim());
        houseMessage.setPhone(StrUtil.trimToNull(houseMessage.getPhone()));
        houseMessage.setWechat(StrUtil.trimToNull(houseMessage.getWechat()));
        houseMessage.setSource(StrUtil.blankToDefault(houseMessage.getSource(), "ai_house"));
        if (houseMessage.getStatus() == null) {
            houseMessage.setStatus(0);
        }
        if (houseMessageService.save(houseMessage)) {
            return success("提交成功");
        }
        return fail("提交失败");
    }

    @OperationLog
    @Operation(summary = "提交AI找房咨询线索")
    @PostMapping("/ai-agent")
    public ApiResult<?> saveAiAgentLead(@RequestBody HouseAiLeadRequest request) {
        User loginUser = getLoginUser();
        if (loginUser == null) {
            return fail("请先登录后再提交咨询线索");
        }
        if (loginUser.getTenantId() == null) {
            return fail("当前登录账号缺少租户信息，暂无法提交咨询线索");
        }
        HouseMessage houseMessage = new HouseMessage();
        houseMessage.setRealName(request.getRealName());
        houseMessage.setPhone(request.getPhone());
        houseMessage.setWechat(request.getWechat());
        String error = validateMessage(houseMessage);
        if (error != null) {
            return fail(error);
        }
        HouseAiChatRequest chatRequest = new HouseAiChatRequest();
        chatRequest.setConversationId(request.getConversationId());
        chatRequest.setUserId(loginUser.getUserId());
        chatRequest.setTenantId(loginUser.getTenantId());
        houseMessage.setUserId(loginUser.getUserId());
        houseMessage.setTenantId(loginUser.getTenantId());
        houseMessage.setRealName(houseMessage.getRealName().trim());
        houseMessage.setPhone(StrUtil.trimToNull(houseMessage.getPhone()));
        houseMessage.setWechat(StrUtil.trimToNull(houseMessage.getWechat()));
        houseMessage.setSource("ai_house");
        houseMessage.setComments(houseAiAgentService.buildLeadSummary(chatRequest));
        houseMessage.setStatus(0);
        if (houseMessageService.save(houseMessage)) {
            return success("提交成功");
        }
        return fail("提交失败");
    }

    @OperationLog
    @Operation(summary = "修改AI找房留言")
    @PutMapping()
    public ApiResult<?> update(@RequestBody HouseMessage houseMessage) {
        String error = validateMessage(houseMessage);
        if (error != null) {
            return fail(error);
        }
        houseMessage.setRealName(houseMessage.getRealName().trim());
        houseMessage.setPhone(StrUtil.trimToNull(houseMessage.getPhone()));
        houseMessage.setWechat(StrUtil.trimToNull(houseMessage.getWechat()));
        if (houseMessageService.updateById(houseMessage)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @OperationLog
    @Operation(summary = "删除AI找房留言")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (houseMessageService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @OperationLog
    @Operation(summary = "批量修改AI找房留言")
    @PutMapping("/batch")
    public ApiResult<?> updateBatch(@RequestBody BatchParam<HouseMessage> batchParam) {
        if (batchParam.update(houseMessageService, "message_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @OperationLog
    @Operation(summary = "批量删除AI找房留言")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (houseMessageService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    private String validateMessage(HouseMessage houseMessage) {
        if (houseMessage == null || StrUtil.isBlank(houseMessage.getRealName())) {
            return "请输入姓名";
        }
        if (houseMessage.getRealName().trim().length() > 30) {
            return "姓名不能超过30个字符";
        }
        boolean hasPhone = StrUtil.isNotBlank(houseMessage.getPhone());
        boolean hasWechat = StrUtil.isNotBlank(houseMessage.getWechat());
        if (!hasPhone && !hasWechat) {
            return "手机号和微信号请至少填写一项";
        }
        if (hasPhone && !PHONE_PATTERN.matcher(houseMessage.getPhone().trim()).matches()) {
            return "手机号格式不正确";
        }
        if (hasWechat && !WECHAT_PATTERN.matcher(houseMessage.getWechat().trim()).matches()) {
            return "微信号格式不正确";
        }
        return null;
    }
}
