package com.fs.company.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.common.annotation.DataScope;
import com.fs.common.exception.base.BaseException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.PubFun;
import com.fs.company.domain.CompanyUser;
import com.fs.company.domain.CompanyVoiceRoboticWx;
import com.fs.company.domain.CompanyWxClient;
import com.fs.company.mapper.CompanyVoiceRoboticWxMapper;
import com.fs.company.mapper.CompanyWxClientMapper;
import com.fs.company.service.ICompanyWxClientService;
import com.fs.company.vo.AddWxResultVo;
import com.fs.crm.domain.CrmCustomer;
import com.fs.crm.service.impl.CrmCustomerServiceImpl;
import com.fs.wxUser.domain.CompanyWxUser;
import com.fs.wxUser.mapper.CompanyWxUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 添加个微信账号Service业务层处理
 *
 * @author fs
 * @date 2024-12-09
 */
@Slf4j
@AllArgsConstructor
@Service
public class CompanyWxClientServiceImpl extends ServiceImpl<CompanyWxClientMapper, CompanyWxClient> implements ICompanyWxClientService {

    private final CrmCustomerServiceImpl crmCustomerService;
    private final CompanyWxDialogServiceImpl companyWxDialogService;
    private final CompanyWxUserMapper companyWxUserMapper;
    private final CompanyVoiceRoboticWxMapper companyVoiceRoboticWxMapper;


    /**
     * 查询添加个微信账号
     *
     * @param id 添加个微信账号ID
     * @return 添加个微信账号
     */
    @Override
    public CompanyWxClient selectCompanyWxClientById(Long id)
    {
        return baseMapper.selectCompanyWxClientById(id);
    }

    /**
     * 查询添加个微信账号列表
     *
     * @param companyWxClient 添加个微信账号
     * @return 添加个微信账号
     */
    @Override
    public List<CompanyWxClient> selectCompanyWxClientList(CompanyWxClient companyWxClient)
    {
        return baseMapper.selectCompanyWxClientList(companyWxClient);
    }

    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<CompanyWxClient> selectCompanyWxClientListCompany(CompanyWxClient companyWxClient)
    {
        return baseMapper.selectCompanyWxClientListCompany(companyWxClient);
    }

    /**
     * 新增添加个微信账号
     *
     * @param companyWxClient 添加个微信账号
     * @return 结果
     */
    @Override
    public int insertCompanyWxClient(CompanyWxClient companyWxClient)
    {
        companyWxClient.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insertCompanyWxClient(companyWxClient);
    }

    /**
     * 修改添加个微信账号
     *
     * @param companyWxClient 添加个微信账号
     * @return 结果
     */
    @Override
    public int updateCompanyWxClient(CompanyWxClient companyWxClient)
    {
        return baseMapper.updateCompanyWxClient(companyWxClient);
    }

    /**
     * 批量删除添加个微信账号
     *
     * @param ids 需要删除的添加个微信账号ID
     * @return 结果
     */
    @Override
    public int deleteCompanyWxClientByIds(Long[] ids)
    {
        return baseMapper.deleteCompanyWxClientByIds(ids);
    }

    /**
     * 删除添加个微信账号信息
     *
     * @param id 添加个微信账号ID
     * @return 结果
     */
    @Override
    public int deleteCompanyWxClientById(Long id)
    {
        return baseMapper.deleteCompanyWxClientById(id);
    }

    @Override
    public List<CompanyWxClient> toDayAddWxAccountList(Long companyId, Long accountId, Integer addType) {
        List<CompanyWxClient> list = baseMapper.toDayAddWxAccountList(companyId, accountId, addType);
        if(list.isEmpty()) return new ArrayList<>();
        List<CrmCustomer> crmCustomerList = new ArrayList<>(crmCustomerService.listByIds(PubFun.listToNewList(list, CompanyWxClient::getCustomerId)));
        Map<Long, CrmCustomer> customerMap = PubFun.listToMapByGroupObject(crmCustomerList, CrmCustomer::getCustomerId);
        list.forEach(e -> {
            CrmCustomer crmCustomer = customerMap.getOrDefault(e.getCustomerId(), new CrmCustomer());
            e.setTemplateDetails(setTemplate(e.getTemplateDetails(), crmCustomer));
            e.setRemark(crmCustomer.getCustomerName() + "-" + crmCustomer.getMobile());
            e.setMemo(crmCustomer.getCustomerName() + "-" + crmCustomer.getMobile());
        });
        return list;
    }

    /**
     * 根据正则表达式提取字符串里面的变量  ${name} -> name
     * @param template 模板字符串
     * @return 字段集合
     */
    public static List<String> extractPlaceholders(String template) {
        List<String> placeholders = new ArrayList<>();
        // 正则表达式：匹配 ${} 中的内容
        String regex = "\\$\\{(.*?)\\}";
        // 创建 Pattern 和 Matcher
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(template);
        // 遍历匹配到的占位符
        while (matcher.find()) {
            // 提取占位符中的内容 (例如 name, age, occupation)
            placeholders.add(matcher.group(1));
        }
        return placeholders;
    }

    /**
     * 模板替换
     * @param template 模板
     * @param t        替换数据
     * @return 返回替换文本
     */
    public static <T> String setTemplate(String template, T t) {
        List<String> filedListStr = extractPlaceholders(template);
        List<Field> list = Arrays.asList(t.getClass().getDeclaredFields());
        Map<String, Optional<Object>> fieldValue = list.stream().peek(e -> e.setAccessible(true)).filter(e -> filedListStr.contains(e.getName())).collect(Collectors.toMap(Field::getName, e -> {
            try {
                Object o = e.get(t);
                if(o == null) return Optional.empty();
                return Optional.of(o);
            } catch (IllegalAccessException ex) {
                return Optional.empty();
            }
        }));
        Map<String, Object> param = fieldValue.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().orElse("")));
        Set<String> keySet = fieldValue.keySet();
        List<String> collect = filedListStr.stream().filter(key -> keySet.stream().noneMatch(f -> f.equals(key))).collect(Collectors.toList());
        collect.forEach(e-> param.put(e, ""));
        StrSubstitutor strSubstitutor = new StrSubstitutor(param);
        return strSubstitutor.replace(template);
    }
    @Override
    public void addWxResult(AddWxResultVo vo) {
        CompanyWxClient companyWxClient = baseMapper.selectById(vo.getId());
        if(companyWxClient == null) throw new BaseException("未找到数据");
        companyWxClient.setIsAdd(2);
        companyWxClient.setAddTime(LocalDateTime.now());
        companyWxClient.setUpdateTime(new Date());
        baseMapper.updateById(companyWxClient);
    }

    @Override
    public void addWxTrueResult(AddWxResultVo vo) {
        CompanyWxClient companyWxClient = baseMapper.selectById(vo.getId());
        companyWxClient.setIsAdd(1);
        companyWxClient.setAddTime(LocalDateTime.now());
        baseMapper.updateById(companyWxClient);
        log.info("回调数据：{}", companyWxClient);
        CompanyUser companyUser = baseMapper.selectCompanyByAccountId(companyWxClient.getRoboticWxId());
        CompanyWxUser companyWx = companyWxUserMapper.selectCompanyWxUserByWeixinId(vo.getWxNo());
        if(companyWx == null){
            companyWx = new CompanyWxUser();
            companyWx.setAccountId(vo.getAccountId());
            companyWx.setCompanyId(companyUser.getCompanyId());
            companyWx.setCompanyUserId(companyUser.getUserId());
            companyWx.setNickName(companyWxClient.getNickName() + "-" + companyWxClient.getPhone());
            companyWx.setWeixinId(companyWxClient.getWxNo());
            companyWx.setRemark(companyWxClient.getNickName() + "-" + companyWxClient.getPhone());
            companyWx.setStatus(1);
            companyWx.setCreateTime(new Date());
            companyWxUserMapper.insertCompanyWxUser(companyWx);
            CompanyVoiceRoboticWx wx = companyVoiceRoboticWxMapper.selectById(companyWxClient.getRoboticWxId());
            wx.setAddNum(wx.getAddNum() + 1);
            companyVoiceRoboticWxMapper.updateById(wx);
        }else{
            companyWx.setNickName(vo.getWxName());
            companyWxUserMapper.updateCompanyWxUser(companyWx);
        }
    }
}
