package com.fs.company.controller.qw;

import java.util.Collections;
import java.util.List;

import com.fs.common.exception.CustomException;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.framework.security.LoginUser;
import com.fs.framework.service.TokenService;
import com.fs.his.dto.SendResultDetailDTO;
import com.fs.qw.bo.SendMsgLogBo;
import com.fs.qw.domain.QwCompany;
import com.fs.qw.domain.QwUser;
import com.fs.qw.service.IQwCompanyService;
import com.fs.qw.service.IQwUserService;
import com.fs.qw.vo.AcquisitionAssistantDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.page.TableDataInfo;
import com.fs.qw.domain.QwAcquisitionAssistant;
import com.fs.qw.service.IQwAcquisitionAssistantService;

/**
 * 企微-获客链接管理Controller
 *
 * @author fs
 * @date 2026-03-16
 */
@Slf4j
@RestController
@RequestMapping("/qw/acquisitionAssistant")
public class QwAcquisitionAssistantController extends BaseController {
    @Autowired
    private IQwAcquisitionAssistantService qwAcquisitionAssistantService;

    @Autowired
    private IQwCompanyService qwCompanyService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IQwUserService qwUserService;

    /**
     * 查询企微-获客链接管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(QwAcquisitionAssistant qwAcquisitionAssistant) {
        startPage();
        List<QwAcquisitionAssistant> list = qwAcquisitionAssistantService.selectQwAcquisitionAssistantList(qwAcquisitionAssistant);
        return getDataTable(list);
    }

    /**
     * 发送获客链接短信
     */
    @GetMapping("/sendAcquisitionMessage/{id}/{phone}")
    public AjaxResult sendAcquisitionMessage(@PathVariable Long id,@PathVariable String phone) {
        try {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            if (loginUser==null||loginUser.getCompany()==null){
                throw new CustomException("请登录");
            }
            SendMsgLogBo sendMsgLogBo=new SendMsgLogBo();
            sendMsgLogBo.setCompanyId(loginUser.getCompany().getCompanyId());
            sendMsgLogBo.setCompanyUserId(loginUser.getCompany().getUserId());
            validatePhone(phone);
            SendResultDetailDTO sendResultDetailDTO = qwAcquisitionAssistantService.sendMessageAcquisition(phone, id,sendMsgLogBo);
            if (sendResultDetailDTO.isSuccess()){
                return AjaxResult.success("发送成功");
            }else {
                return AjaxResult.error(sendResultDetailDTO.getFailReason());
            }
        } catch (Exception e) {
            log.error("发送失败：" + e.getMessage());
            return AjaxResult.error("网络异常，请稍后再试");
        }
    }
    /**
     * 根据linkId直接获取详情
     *
     * @param linkId 企微链接ID
     */
    @GetMapping("/getDetailByLinkId/{linkId}")
    public AjaxResult getDetailByLinkId(@PathVariable String linkId) {
        try {
            // 调用获取详情服务
            AcquisitionAssistantDetailVO detailVo = qwAcquisitionAssistantService.getDetailWithQw(linkId);
            return AjaxResult.success("获取成功", detailVo);
        } catch (CustomException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("系统异常：" + e.getMessage());
        }
    }

    /**
     * 新增企微-获客链接管理
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody QwAcquisitionAssistant qwAcquisitionAssistant) {
        try {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            qwAcquisitionAssistant.setCreateBy(String.valueOf(loginUser.getUser().getUserId()));
            Long companyId = loginUser.getUser().getCompanyId();
            QwCompany qwCompany = getQwCompany(qwAcquisitionAssistant.getCorpId());
            QwAcquisitionAssistant result = qwAcquisitionAssistantService.createWithQw(qwCompany.getCorpId(), qwCompany.getOpenSecret(), qwAcquisitionAssistant,companyId);
            return AjaxResult.success("创建成功", result);
        } catch (CustomException e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取企微用户列表
     */
    @PostMapping("/qwUserList")
    public AjaxResult getQwUserList(@RequestBody QwUser qwUser) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        qwUser.setCompanyId(loginUser.getCompany().getCompanyId());
        List<QwUser> qwUserList = qwUserService.selectQwUserListByAcquisition(qwUser);
        if (qwUserList != null && !qwUserList.isEmpty()) {
            return AjaxResult.success("获取成功", qwUserList);
        } else {
            return AjaxResult.error("未找到用户");
        }
    }

    /**
     * 获取企微用户主体列表
     */
    @PostMapping("/qwUserCompanyList")
    public AjaxResult getQwUserCompanyList(@RequestBody QwCompany qwCompany) {
        qwCompany.setStatus(1L);//启用状态的主体
        List<QwCompany> qwCompanyList = qwCompanyService.selectQwCompanyList(qwCompany);
        if (qwCompanyList != null && !qwCompanyList.isEmpty()) {
            return AjaxResult.success("获取成功", qwCompanyList);
        } else {
            return AjaxResult.error("未找到主体");
        }
    }

    /**
     * 获取企微用户列表
     */
    @PostMapping("/getQwUserListByIds")
    public AjaxResult getQwUserListByIds(@RequestBody List<Long> qwUserTableIds) {
        if (qwUserTableIds == null || qwUserTableIds.isEmpty()) {
            return AjaxResult.success(Collections.emptyList());
        }
        // 限制最多500个，避免性能问题
        if (qwUserTableIds.size() > 500) {
            qwUserTableIds = qwUserTableIds.subList(0, 500);
        }
        List<QwUser> qwUserList = qwUserService.selectQwUserListByIds(qwUserTableIds);
        if (qwUserList != null && !qwUserList.isEmpty()) {
            return AjaxResult.success("获取成功", qwUserList);
        } else {
            return AjaxResult.error("未找到用户");
        }
    }

    /**
     * 修改企微-获客链接
     */
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody QwAcquisitionAssistant qwAcquisitionAssistant) {
        try {
            // 参数校验
            if (qwAcquisitionAssistant.getId() == null) {
                return AjaxResult.error("ID不能为空");
            }
            if (StringUtils.isEmpty(qwAcquisitionAssistant.getLinkId())) {
                return AjaxResult.error("链接ID不能为空");
            }

            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

            qwAcquisitionAssistant.setUpdateBy(String.valueOf(loginUser.getUser().getUserId()));
            QwCompany qwCompany = getQwCompany(qwAcquisitionAssistant.getCorpId());
            QwAcquisitionAssistant result = qwAcquisitionAssistantService.updateWithQw(
                    qwCompany.getCorpId(), qwCompany.getOpenSecret(), qwAcquisitionAssistant,loginUser.getUser().getCompanyId());

            return AjaxResult.success("修改成功", result);
        } catch (CustomException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("系统异常：" + e.getMessage());
        }
    }

    /**
     * 删除企微-获客链接
     *
     * @param id 本地记录ID
     */
    @GetMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable Long id) {
        try {
            // 先查询本地记录，获取linkId
            QwAcquisitionAssistant assistant = qwAcquisitionAssistantService.selectQwAcquisitionAssistantById(id);
            if (assistant == null) {
                return AjaxResult.error("获客链接不存在");
            }
            QwCompany qwCompany = getQwCompany(assistant.getCorpId());
            // 调用删除服务
            qwAcquisitionAssistantService.deleteWithQw(qwCompany.getCorpId(), qwCompany.getOpenSecret(), assistant);

            return AjaxResult.success("删除成功");
        } catch (CustomException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("系统异常：" + e.getMessage());
        }
    }

    private QwCompany getQwCompany(String corpId) {
        if (StringUtils.isBlank(corpId)) {
            log.error("获客链接管理参数异常:{}", corpId);
            throw new CustomException("未找到企业微信主体");
        }
        QwCompany qwCompany = qwCompanyService.selectQwCompanyByCorpId(corpId);
        if (qwCompany == null) {
            log.error("获客链接管理-企微主体获取异常:{}", corpId);
            throw new CustomException("未找到企业微信主体");
        }
        return qwCompany;
    }

    /**
     * 校验电话
     */
    private void validatePhone(String phone) {
        if (StringUtils.isEmpty(phone)) {
            throw new CustomException("发送短信的电话号码不能为空", 400);
        }

        // 支持手机号或固话
        if (!phone.matches("^1[3-9]\\d{9}$") && !phone.matches("^\\d{3,4}-?\\d{7,8}$")) {
            throw new CustomException("电话号码格式不正确，请输入正确的手机号或固定电话", 400);
        }
    }
}
