package com.cyksj.service.corp.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.snowflake.Sequence;
import com.cyksj.common.util.Jsons;
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.request.corp.link.Range;
import com.cyksj.model.request.corp.link.WxCpLinkUpd;
import com.cyksj.redis.RedisService;
import com.cyksj.service.corp.CorpCustomerAcquistionService;
import com.cyksj.service.corp.WxCorpOps;
import com.cyksj.service.sys.SysConfigService;
import com.cyksj.service.sys.SysCorpServiceRelateService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

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

/**
 * @author chan
 * @date 2023/11/28 14:59
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CorpCustomerAcquistionServiceImpl implements CorpCustomerAcquistionService {


    private static final Sequence SEQUENCE = new Sequence(0);

    private final RedisService redisService;

    private final CorpCustomerAcquisitionLinkPopularizeMapper corpCustomerAcquisitionLinkPopularizeMapper;

    private final CorpCustomerAcquisitionLinkMapper corpCustomerAcquisitionLinkMapper;

    private final SysConfigService sysConfigService;

    private final SysCorpServiceRelateService sysCorpServiceRelateService;

    private final WxCorpOps corpOps;


    @Override
    public String getUrlByLinkId(Long linkId) throws Exception {
        CorpCustomerAcquisitionLinkPopularize corpCustomerAcquisitionLinkPopularize = corpCustomerAcquisitionLinkPopularizeMapper.selectById(linkId);
        Long customerAcquistionLinkId = corpCustomerAcquisitionLinkPopularize.getCustomerAcquistionLinkId();
        CorpCustomerAcquisitionLink corpCustomerAcquisitionLink = corpCustomerAcquisitionLinkMapper.selectById(customerAcquistionLinkId);
        return corpCustomerAcquisitionLink.getUrl();
    }

    @Override
    public String saveClickid(String projectid, String clickid, String callback, Long linkId) {
        CorpCustomerAcquisitionLinkPopularize corpCustomerAcquisitionLinkPopularize = corpCustomerAcquisitionLinkPopularizeMapper.selectById(linkId);

        if (corpCustomerAcquisitionLinkPopularize == null) {
            throw BusinessRuntimeException.getInstance("系统出现异常.");
        }
        if(StringUtils.isBlank(callback) && StringUtils.isNotBlank(clickid)){
            callback = "https://nf.video" + "?clickid=" + clickid + "&projectid=" + projectid;
        }
        JSONObject params = new JSONObject();
        params.putOpt("linkId", linkId);
        params.putOpt("callback", callback);
        params.putOpt("postApp", "OE");
        String key = SEQUENCE.nextId().toString();
        redisService.set(String.format(RedisService.key.CORP_CUSTOMER_ACQUISTION_CLICKID.getName(), key), params.toString(), corpCustomerAcquisitionLinkPopularize.getTime() * 60 * 60);

        return key;
    }

    @Override
    public String getActiveCustomerAcquistionById(Long acLinkId) throws Exception {
        CorpCustomerAcquisitionLink corpCustomerAcquisitionLink = corpCustomerAcquisitionLinkMapper.selectById(acLinkId);
        return corpCustomerAcquisitionLink.getUrl();
    }


    public void resetAcLinkConfigIfDuty(CorpCustomerAcquisitionLink corpCustomerAcquisitionLink) throws Exception {
        if (corpCustomerAcquisitionLink == null) {
            throw BusinessRuntimeException.getInstance("获客链接不存在.");
        }
        //寻找值班客服
        if (corpCustomerAcquisitionLink.getIsDuty()) {
            String userList = corpCustomerAcquisitionLink.getUserList();

            List<Integer> users = Jsons.parseList(userList, Integer.class);
            if (users.size() > 1) {
                List<Integer> dutyServices = sysConfigService.getDutyServices();
                //值班
                if (CollUtil.isNotEmpty(dutyServices)) {

                    String chooseDutyUsers = corpCustomerAcquisitionLink.getChooseDutyUsers();
                    if (chooseDutyUsers == null) {
                        chooseDutyUsers = userList;
                    }

                    Set<Integer> fitUsers = dutyServices.stream().filter(e -> users.contains(e)).collect(Collectors.toSet());
                    if (CollUtil.isNotEmpty(fitUsers)) {

                        corpCustomerAcquisitionLink.setChooseDutyUsers(Jsons.toJson(fitUsers));

                        //更新获客链接
                        WxCpLinkUpd wxCpLinkUpd = new WxCpLinkUpd();
                        wxCpLinkUpd.setLinkName(corpCustomerAcquisitionLink.getLinkName());
                        wxCpLinkUpd.setLinkId(corpCustomerAcquisitionLink.getLinkId());
                        wxCpLinkUpd.setSkipVerify(corpCustomerAcquisitionLink.getSkipVerify());
                        Range range = new Range();
                        List<Integer> userIndxList = Jsons.parseList(corpCustomerAcquisitionLink.getChooseDutyUsers(), Integer.class);
                        List<String> followIds = sysCorpServiceRelateService.getFollowIdsByRelateIds(userIndxList);

                        range.setUserList(followIds);
                        wxCpLinkUpd.setRange(range);
                        corpOps.customerAcquisitionUpdateLink(null, wxCpLinkUpd);

                        corpCustomerAcquisitionLinkMapper.updateById(corpCustomerAcquisitionLink);
                    }

                }
            }
        }
    }
}
