package com.gxwebsoft.cms.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.cms.entity.CmsContactLead;
import com.gxwebsoft.cms.mapper.CmsContactLeadMapper;
import com.gxwebsoft.cms.param.CmsContactLeadParam;
import com.gxwebsoft.cms.service.CmsContactLeadService;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 联系表单/销售线索Service实现
 *
 * @author 科技小王子
 * @since 2026-03-30
 */
@Slf4j
@Service
public class CmsContactLeadServiceImpl extends ServiceImpl<CmsContactLeadMapper, CmsContactLead>
        implements CmsContactLeadService {

    /** 企业微信群机器人 Webhook，留空则不发送 */
    @Value("${notify.wecom-webhook:}")
    private String wecomWebhook;

    /** 飞书群机器人 Webhook，留空则不发送 */
    @Value("${notify.feishu-webhook:}")
    private String feishuWebhook;

    // --------------------------------------------------------
    // 分页 / 列表
    // --------------------------------------------------------

    @Override
    public PageResult<CmsContactLead> pageRel(CmsContactLeadParam param) {
        PageParam<CmsContactLead, CmsContactLeadParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        List<CmsContactLead> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<CmsContactLead> listRel(CmsContactLeadParam param) {
        return baseMapper.selectListRel(param);
    }

    // --------------------------------------------------------
    // 公开提交接口
    // --------------------------------------------------------

    @Override
    public boolean submit(CmsContactLead lead, String ip) {
        // 补充默认值
        if (StrUtil.isBlank(lead.getSource())) {
            lead.setSource("web");
        }
        lead.setIp(ip);
        lead.setStatus(0); // 默认待跟进

        // 清洗手机号：去除空格、横线、括号等分隔符，仅保留 + 和数字
        // 防止 "Data too long for column 'phone'" 异常
        lead.setPhone(sanitizePhone(lead.getPhone()));

        boolean result = save(lead);
        if (result) {
            log.info("[联系表单] 新线索提交成功，name={}, phone={}", lead.getName(), lead.getPhone());
            // 异步推送通知，不阻塞接口响应
            sendNotifyAsync(lead);
        }
        return result;
    }

    /**
     * 清洗手机号：去除空格、横线、括号等分隔符，仅保留 + 和数字
     * 例如："+86 (138) 1234-5678" -> "+8613812345678"
     */
    private String sanitizePhone(String phone) {
        if (StrUtil.isBlank(phone)) {
            return phone;
        }
        return phone.replaceAll("[^+0-9]", "");
    }

    // --------------------------------------------------------
    // 异步通知（企业微信 + 飞书）
    // --------------------------------------------------------

    @Async
    public void sendNotifyAsync(CmsContactLead lead) {
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("MM-dd HH:mm"));
        String deliveryLabel = deliveryLabel(lead.getDelivery());

        if (StrUtil.isNotBlank(wecomWebhook)) {
            try {
                sendWecom(lead, deliveryLabel, now);
            } catch (Exception e) {
                log.warn("[联系表单] 企业微信通知发送失败: {}", e.getMessage());
            }
        }

        if (StrUtil.isNotBlank(feishuWebhook)) {
            try {
                sendFeishu(lead, deliveryLabel, now);
            } catch (Exception e) {
                log.warn("[联系表单] 飞书通知发送失败: {}", e.getMessage());
            }
        }
    }

    /**
     * 企业微信群机器人 - markdown 消息
     * 文档：https://developer.work.weixin.qq.com/document/path/91770
     */
    private void sendWecom(CmsContactLead lead, String deliveryLabel, String now) {
        String content = String.format(
                "## 📋 新销售线索（%s）\n" +
                "> **姓名：** %s\n" +
                "> **手机：** <font color=\"warning\">%s</font>\n" +
                "> **公司：** %s\n" +
                "> **交付：** %s\n" +
                "> **需求：** %s\n" +
                "> **来源：** %s",
                now,
                nullSafe(lead.getName()),
                nullSafe(lead.getPhone()),
                nullSafe(lead.getCompany()),
                deliveryLabel,
                truncate(lead.getNeed(), 100),
                nullSafe(lead.getSource())
        );

        Map<String, Object> textMap = new HashMap<>();
        textMap.put("content", content);

        Map<String, Object> payload = new HashMap<>();
        payload.put("msgtype", "markdown");
        payload.put("markdown", textMap);

        String body = JSON.toJSONString(payload);
        String resp = HttpUtil.post(wecomWebhook, body);
        log.info("[联系表单] 企业微信通知结果: {}", resp);
    }

    /**
     * 飞书群机器人 - 富文本（post）消息
     * 文档：https://open.feishu.cn/document/client-docs/bot-v3/add-custom-bot
     */
    private void sendFeishu(CmsContactLead lead, String deliveryLabel, String now) {
        // 标题行
        String title = "📋 新销售线索（" + now + "）";

        // 正文每行：[{"tag":"text","text":"xxx"}]
        List<List<Map<String, String>>> content = List.of(
                line("姓　名：" + nullSafe(lead.getName())),
                line("手　机：" + nullSafe(lead.getPhone())),
                line("公　司：" + nullSafe(lead.getCompany())),
                line("交　付：" + deliveryLabel),
                line("需　求：" + truncate(lead.getNeed(), 100)),
                line("来　源：" + nullSafe(lead.getSource()))
        );

        Map<String, Object> zhCn = new HashMap<>();
        zhCn.put("title", title);
        zhCn.put("content", content);

        Map<String, Object> postContent = new HashMap<>();
        postContent.put("zh_cn", zhCn);

        Map<String, Object> post = new HashMap<>();
        post.put("content", postContent);

        Map<String, Object> payload = new HashMap<>();
        payload.put("msg_type", "post");
        payload.put("content", post);

        String body = JSON.toJSONString(payload);
        String resp = HttpUtil.post(feishuWebhook, body);
        log.info("[联系表单] 飞书通知结果: {}", resp);
    }

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

    private String deliveryLabel(String delivery) {
        if (delivery == null) return "未选择";
        return switch (delivery) {
            case "saas" -> "SaaS（云端）";
            case "private" -> "私有化部署";
            case "hybrid" -> "混合部署";
            default -> delivery;
        };
    }

    private String nullSafe(String s) {
        return StrUtil.isBlank(s) ? "—" : s;
    }

    private String truncate(String s, int max) {
        if (StrUtil.isBlank(s)) return "—";
        return s.length() > max ? s.substring(0, max) + "…" : s;
    }

    /** 飞书 post 消息单行 */
    private List<Map<String, String>> line(String text) {
        Map<String, String> node = new HashMap<>();
        node.put("tag", "text");
        node.put("text", text);
        return List.of(node);
    }
}
