package com.fs.qw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.ad.apis.YouKuApiUtils;
import com.fs.ad.domain.AdAccount;
import com.fs.ad.mapper.AdAccountMapper;
import com.fs.ad.yk.vo.DataBackVo;
import com.fs.baidu.api.ConvertData;
import com.fs.baidu.domain.BdAccount;
import com.fs.baidu.mapper.BdAccountMapper;
import com.fs.baidu.param.ConversionType;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.PubFun;
import com.fs.common.utils.StringUtils;
import com.fs.course.domain.FsCourseWatchLog;
import com.fs.course.service.IFsCourseWatchLogService;
import com.fs.qw.domain.QwExternalContact;
import com.fs.qw.domain.QwWorkLink;
import com.fs.qw.domain.QwWorkUser;
import com.fs.qw.mapper.QwWorkUserMapper;
import com.fs.qw.result.QwExternalContactVo;
import com.fs.qw.service.IQwExternalContactService;
import com.fs.qw.service.IQwWorkLinkService;
import com.fs.qw.service.IQwWorkUserService;
import com.fs.qwApi.domain.QwExternalContactAllListResult;
import com.fs.qwApi.domain.QwLinkCustomerResult;
import com.fs.qwApi.param.QwExternalListParam;
import com.fs.qwApi.param.QwLinkCustomerParam;
import com.fs.qwApi.service.QwApiService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 企微获客添加的用户Service业务层处理
 *
 * @author fs
 * @date 2025-01-10
 */
@Service
@AllArgsConstructor
public class QwWorkUserServiceImpl extends ServiceImpl<QwWorkUserMapper, QwWorkUser> implements IQwWorkUserService {
    private final QwWorkUserMapper qwWorkUserMapper;
    private final IQwExternalContactService qwExternalContactService;
    private final IQwWorkLinkService qwWorkLinkService;
    private final QwApiService qwApiService;
    private final IFsCourseWatchLogService fsCourseWatchLogService;
    private final AdAccountMapper adAccountMapper;
    private final BdAccountMapper bdAccountMapper;

    /**
     * 查询企微获客添加的用户
     *
     * @param id 企微获客添加的用户主键
     * @return 企微获客添加的用户
     */
    @Override
    public QwWorkUser selectQwWorkUserById(Long id)
    {
        return qwWorkUserMapper.selectQwWorkUserById(id);
    }

    /**
     * 查询企微获客添加的用户列表
     *
     * @param qwWorkUser 企微获客添加的用户
     * @return 企微获客添加的用户
     */
    @Override
    public List<QwWorkUser> selectQwWorkUserList(QwWorkUser qwWorkUser)
    {
        return qwWorkUserMapper.selectQwWorkUserList(qwWorkUser);
    }

    /**
     * 新增企微获客添加的用户
     *
     * @param qwWorkUser 企微获客添加的用户
     * @return 结果
     */
    @Override
    public int insertQwWorkUser(QwWorkUser qwWorkUser)
    {
        qwWorkUser.setCreateTime(DateUtils.getNowDate());
        return qwWorkUserMapper.insertQwWorkUser(qwWorkUser);
    }

    /**
     * 修改企微获客添加的用户
     *
     * @param qwWorkUser 企微获客添加的用户
     * @return 结果
     */
    @Override
    public int updateQwWorkUser(QwWorkUser qwWorkUser)
    {
        qwWorkUser.setUpdateTime(DateUtils.getNowDate());
        return qwWorkUserMapper.updateQwWorkUser(qwWorkUser);
    }

    /**
     * 批量删除企微获客添加的用户
     *
     * @param ids 需要删除的企微获客添加的用户主键
     * @return 结果
     */
    @Override
    public int deleteQwWorkUserByIds(Long[] ids)
    {
        return qwWorkUserMapper.deleteQwWorkUserByIds(ids);
    }

    /**
     * 删除企微获客添加的用户信息
     *
     * @param id 企微获客添加的用户主键
     * @return 结果
     */
    @Override
    public int deleteQwWorkUserById(Long id)
    {
        return qwWorkUserMapper.deleteQwWorkUserById(id);
    }

    @Override
    public void syncUsers() {
        List<QwWorkLink> list = qwWorkLinkService.list();
        list.forEach(this::saveCustomer);
    }

    @Override
    public void uploadBd() {
        // 查询所有企微客户数据
        List<QwExternalContactVo> list = qwExternalContactService.selectAllQwJoinAdClickLog(0);
        // 需要提交的转换信息
        List<ConversionType> conversionList = new ArrayList<>();
        // 注册提交状态
        List<QwExternalContactVo> registerList = list.stream().filter(e -> e.getUploadRegisterStatus() == 0).collect(Collectors.toList());
        // 是否注册，如果已经注册并且没有提交，改状态生成提交数据
        registerList.stream().filter(e -> e.getFsUserId() != null).forEach(e -> {
           e.setUploadRegisterStatus(1);
            conversionList.add(ConversionType.builder().logidUrl(e.getUrl()).accountId(e.getAccountId()).newType(25).build());
        });
        // 是否看课完成
        List<QwExternalContactVo> finisList = list.stream().filter(e -> e.getUploadRegisterStatus() == 1 && e.getUploadFinishedStatus() == 0).collect(Collectors.toList());
        if(!finisList.isEmpty()){
            // 外部联系人ID
            List<Long> exIdList = PubFun.listToNewList(finisList, QwExternalContactVo::getId);
            // 根据外部联系人ID查找看课记录
            List<FsCourseWatchLog> watchLogList = fsCourseWatchLogService.list(new QueryWrapper<FsCourseWatchLog>().in("qw_external_contact_id", exIdList).eq("log_type", 2));
            if(!watchLogList.isEmpty()){
                // 根据外部联系人ID来分组看完多少节课
                Map<Long, Long> watchList = PubFun.listToMapByGroupCount(watchLogList, FsCourseWatchLog::getQwExternalContactId);
                // 如果看完过一次就判定完课改变提交状态，并且组装提交数据
                finisList.stream().filter(e -> watchList.containsKey(e.getId())).forEach(e -> {
                    e.setUploadFinishedStatus(1);
                    conversionList.add(ConversionType.builder().accountId(e.getAccountId()).logidUrl(e.getUrl()).newType(27).build());
                });
            }
        }
        List<AdAccount> accountList = adAccountMapper.selectBatchIds(PubFun.listToNewList(conversionList, ConversionType::getAccountId));
        PubFun.setListObject(accountList, bdAccountMapper, AdAccount::getLinkId, BdAccount::getId, AdAccount::setBdAccount);
        Map<Long, AdAccount> accountMap = PubFun.listToMapByGroupObject(accountList, AdAccount::getId);
        Map<Long, List<ConversionType>> map = PubFun.listToMapByGroupList(conversionList, ConversionType::getAccountId);
        map.entrySet().stream()
                .filter(e -> accountMap.containsKey(e.getKey()) && accountMap.get(e.getKey()) != null)
                .forEach(e -> ConvertData.sendConvertData(accountMap.get(e.getKey()).getBdAccount().getToken(), e.getValue()));
        // 修改提交状态
        List<QwExternalContact> collect = list.stream().map(e -> {
            QwExternalContact qwExternalContact = new QwExternalContact();
            qwExternalContact.setId(e.getId());
            qwExternalContact.setUploadRegisterStatus(e.getUploadRegisterStatus());
            qwExternalContact.setUploadFinishedStatus(e.getUploadFinishedStatus());
            return qwExternalContact;
        }).collect(Collectors.toList());
        if(!collect.isEmpty()){
            qwExternalContactService.updateBatchById(collect);
        }

    }

    @Override
    public void openidGetExId(String userId) {
        QwExternalListParam qwExternalListParam = new QwExternalListParam();
        qwExternalListParam.setUserid_list(Arrays.asList(userId));
        qwExternalListParam.setLimit(100);
        QwExternalContactAllListResult result = qwApiService.getAllExternalcontactList(qwExternalListParam, "ww51717e2b71d5e2d3");
        System.out.println(result);
    }

    @Override
    public void uploadYk() {
        // 查询所有企微客户数据
        List<QwExternalContactVo> list = qwExternalContactService.selectAllQwJoinAdClickLog(1);
        // 需要提交的转换信息
        List<DataBackVo> conversionList = new ArrayList<>();
        // 添加的微信列表
        List<QwExternalContactVo> addWxList = list.stream().filter(e -> e.getUploadAddWxStatus() == 0).collect(Collectors.toList());
        // 改变状态，并创建提交百度数据
        addWxList.forEach(e -> {
            e.setUploadAddWxStatus(1);
            conversionList.add(DataBackVo.builder().trackId(e.getVid()).creativeId(e.getAid()).build());
        });

        // 上传数据给百度
        YouKuApiUtils.sendYk(conversionList);
        if(!list.isEmpty()){
            // 修改提交状态
            qwExternalContactService.updateBatchById(list.stream().map(e -> {
                QwExternalContact qwExternalContact = new QwExternalContact();
                qwExternalContact.setId(e.getId());
                qwExternalContact.setUploadAddWxStatus(e.getUploadAddWxStatus());
                return qwExternalContact;
            }).collect(Collectors.toList()));
        }
    }

    // 同步添加用户信息
    public void saveCustomer(QwWorkLink qwWorkLink){
        List<QwLinkCustomerResult.Customer> list = getCustomer(qwWorkLink, null);
        if(list == null || list.isEmpty()) return;
        List<QwWorkUser> collect = list.stream().map(e -> {
            QwWorkUser user = new QwWorkUser();
            user.setLinkId(qwWorkLink.getId());
            user.setExternalUserid(e.getExternal_user_id());
            user.setUserid(e.getUser_id());
            user.setChatStatus(e.getChat_status());
            user.setState(e.getState());
            user.setCreateTime(new Date());
            return user;
        }).collect(Collectors.toList());
        collect.forEach(e -> {
            boolean update = update(e, new QueryWrapper<QwWorkUser>().eq("link_id", qwWorkLink.getId()).eq("external_userid", e.getExternalUserid()));
            if(!update){
                save(e);
            }
        });
    }
    // 获取链接下面的用户
    public List<QwLinkCustomerResult.Customer> getCustomer(QwWorkLink qwWorkLink, String cursor){
        QwLinkCustomerResult result = qwApiService.linkCustomer(QwLinkCustomerParam.builder().link_id(qwWorkLink.getLinkId()).limit(500).cursor(cursor).build(), qwWorkLink.getCorpId());
        List<QwLinkCustomerResult.Customer> customerList = result.getCustomer_list();
        if(StringUtils.isNotEmpty(result.getNext_cursor())){
            List<QwLinkCustomerResult.Customer> customer = getCustomer(qwWorkLink, result.getNext_cursor());
            if(customer != null && !customer.isEmpty()){
                customerList.addAll(customer);
            }
        }
        return customerList;
    }
}
