package com.cyksj.service.corp.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Jsons;
import com.cyksj.mapper.SysCorpFollowRelateMapper;
import com.cyksj.mapper.corp.CorpCustomerAcquisitionLinkMapper;
import com.cyksj.mapper.corp.CorpCustomerAcquisitionLinkPopularizeMapper;
import com.cyksj.model.entity.CorpCustomerAcquisitionLink;
import com.cyksj.model.entity.CorpCustomerAcquisitionLinkPopularize;
import com.cyksj.model.entity.SysCorpFollowRelate;
import com.cyksj.model.request.corp.link.Range;
import com.cyksj.model.request.corp.link.WxCpLinkAdd;
import com.cyksj.model.request.corp.link.WxCpLinkAddResp;
import com.cyksj.model.request.corp.link.WxCpLinkUpd;
import com.cyksj.service.corp.CorpCustomerAcquisitionLinkService;
import com.cyksj.service.corp.WxCorpOps;
import com.cyksj.service.sys.SysCorpServiceRelateService;
import com.cyksj.xxljob.XxlJobInfo;
import com.cyksj.xxljob.XxlJobUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author chan
 * @date 2023/11/10 10:08
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CorpCustomerAcquisitionLinkServiceImpl extends ServiceImpl<CorpCustomerAcquisitionLinkMapper, CorpCustomerAcquisitionLink> implements CorpCustomerAcquisitionLinkService {

    private final WxCorpOps corpOps;

    private final CorpCustomerAcquisitionLinkPopularizeMapper corpCustomerAcquisitionLinkPopularizeMapper;

    private final SysCorpServiceRelateService sysCorpServiceRelateService;

    private final SysCorpFollowRelateMapper sysCorpFollowRelateMapper;

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void add(CorpCustomerAcquisitionLink corpCustomerAcquisitionLink) throws Exception {
        WxCpLinkAdd wxCpLinkAdd = new WxCpLinkAdd();
        wxCpLinkAdd.setLinkName(corpCustomerAcquisitionLink.getLinkName());
        wxCpLinkAdd.setSkipVerify(corpCustomerAcquisitionLink.getSkipVerify());
        Range range = new Range();
        String userList = corpCustomerAcquisitionLink.getUserList();
        //值班客服
        List<String> followIds = sysCorpServiceRelateService.getFollowIdsByRelateIds(Jsons.parseList(userList, Integer.class));
        range.setUserList(followIds);
        wxCpLinkAdd.setRange(range);
        WxCpLinkAddResp wxCpLinkAddResp = corpOps.customerAcquisitionCreateLink(null, wxCpLinkAdd);
        corpCustomerAcquisitionLink.setUrl(wxCpLinkAddResp.getLink().getUrl());
        corpCustomerAcquisitionLink.setLinkId(wxCpLinkAddResp.getLink().getLinkId());

        corpCustomerAcquisitionLink.setChooseDutyUsers(corpCustomerAcquisitionLink.getUserList());
        this.save(corpCustomerAcquisitionLink);

        if (corpCustomerAcquisitionLink.getIsDuty() != null && corpCustomerAcquisitionLink.getIsDuty()) {
            handleCorpLinkSchedulerJob();
        }
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void up(CorpCustomerAcquisitionLink corpCustomerAcquisitionLink) throws Exception {
        CorpCustomerAcquisitionLink link = getById(corpCustomerAcquisitionLink.getId());
        link.setLinkName(corpCustomerAcquisitionLink.getLinkName());
        link.setUserList(corpCustomerAcquisitionLink.getUserList());

        WxCpLinkUpd wxCpLinkUpd = new WxCpLinkUpd();
        wxCpLinkUpd.setLinkName(corpCustomerAcquisitionLink.getLinkName());
        wxCpLinkUpd.setLinkId(corpCustomerAcquisitionLink.getLinkId());
        wxCpLinkUpd.setSkipVerify(corpCustomerAcquisitionLink.getSkipVerify());
        Range range = new Range();
        String userList = corpCustomerAcquisitionLink.getUserList();
        //值班客服
        List<String> followIds = sysCorpServiceRelateService.getFollowIdsByRelateIds(Jsons.parseList(userList, Integer.class));
        range.setUserList(followIds);
        wxCpLinkUpd.setRange(range);

        WxCpLinkAddResp wxCpLinkAddResp = corpOps.customerAcquisitionUpdateLink(null, wxCpLinkUpd);

        if (corpCustomerAcquisitionLink.getMsgId() == null) {
            corpCustomerAcquisitionLink.setMsgId(0l);
        }
        Boolean isDuty = Optional.ofNullable(corpCustomerAcquisitionLink.getIsDuty()).orElse(false);
        if (!isDuty) {
            corpCustomerAcquisitionLink.setChooseDutyUsers(null);
        } else {
            corpCustomerAcquisitionLink.setChooseDutyUsers(corpCustomerAcquisitionLink.getUserList());
        }

        this.updateById(corpCustomerAcquisitionLink);

        if (corpCustomerAcquisitionLink.getIsDuty() != null && corpCustomerAcquisitionLink.getIsDuty()) {
            handleCorpLinkSchedulerJob();
        }
    }

    @Override
    public void del(Long id) throws Exception {
        CorpCustomerAcquisitionLink link = getById(id);
        if (link == null) {
            throw BusinessRuntimeException.getInstance("该链接不存在.");
        }
        //查询该获客链接是否关联 推广链接
        Integer count = corpCustomerAcquisitionLinkPopularizeMapper.selectCount(Wrappers.lambdaQuery(CorpCustomerAcquisitionLinkPopularize.class).eq(CorpCustomerAcquisitionLinkPopularize::getCustomerAcquistionLinkId, id));
        if(count > 0){
            throw BusinessRuntimeException.getInstance("该获客链接还关联推广链接，无法删除.");
        }

        WxCpLinkUpd wxCpLinkUpd = new WxCpLinkUpd();
        wxCpLinkUpd.setLinkId(link.getLinkId());
        try {
            WxCpLinkAddResp wxCpLinkAddResp = corpOps.customerAcquisitionDeleteLink(null, wxCpLinkUpd);
        } catch (Exception e) {
        }
        removeById(id);
    }

    @Override
    public void handleCorpLinkSchedulerJob() throws Exception {
        //立即执行客服值班定时任务
        XxlJobUtil.executeMarkDynamicRuleTagJob(XxlJobInfo.getExecuteTaskInstance(Constant.CORP_LINK_JOB_ID, StrUtil.EMPTY).toString());
    }

    @Override
    public void syncDutyLinkUrl() throws Exception {
        //获取目前可用值班客服
        List<SysCorpFollowRelate> sysCorpFollowRelates = sysCorpFollowRelateMapper.selectList(Wrappers.lambdaQuery(SysCorpFollowRelate.class)
                .eq(SysCorpFollowRelate::getStatus, 1)
                .eq(SysCorpFollowRelate::getDeleted, 1));
        List<String> userIds = sysCorpFollowRelates.stream().map((e) -> e.getId().toString()).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(userIds)) {
            this.update(Wrappers.lambdaUpdate(CorpCustomerAcquisitionLink.class)
                    .set(CorpCustomerAcquisitionLink::getUserList, Jsons.toJson(userIds))
                    .eq(CorpCustomerAcquisitionLink::getIsDuty, 1));
        }
    }
}
