package com.gic.haoban.manage.service.service.out.impl.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.hologres.client.HoloClient;
import com.alibaba.hologres.client.Put;
import com.alibaba.hologres.client.model.TableSchema;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.haoban.app.customer.dto.ChildDTO;
import com.gic.haoban.app.customer.dto.CustomerDTO;
import com.gic.haoban.app.customer.dto.FilterListDTO;
import com.gic.haoban.app.customer.dto.MemberInfoListParamsDTO;
import com.gic.haoban.app.customer.dto.contact.ContactParamDTO;
import com.gic.haoban.app.customer.dto.contact.ContactSumDTO;
import com.gic.haoban.app.customer.service.api.service.CustomerApiService;
import com.gic.haoban.common.utils.DateUtil;
import com.gic.haoban.manage.api.service.common.RouterApiService;
import com.gic.haoban.manage.service.dao.mapper.content.holo.HoloDataSource;
import com.gic.haoban.manage.service.pojo.bo.contact.ContactDataBO;
import com.gic.haoban.manage.service.service.contact.ContactLogService;
import com.gic.member.api.dto.event.clerk.ClerkAddEventParam;
import com.gic.store.goods.dto.potential.PlatformPotentialCustomerOutDTO;
import com.gic.store.goods.service.potential.PlatformPotentialCustomerApiService;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service("routerApiService")
public class RouterApiServiceImpl implements RouterApiService {

    private static final Logger logger = LogManager.getLogger(RouterApiService.class);


    @Autowired
    private ContactLogService contactLogService;
    @Autowired
    private PlatformPotentialCustomerApiService platformPotentialCustomerApiService;
    @Autowired
    private ClerkService clerkService;
    @Autowired
    private CustomerApiService customerService;
    @Autowired
    private HoloDataSource holoDataSource;

    @Override
    public ServiceResponse<Void> memberClerkEvent(String params) {
        if (StringUtils.isBlank(params)) {
            return ServiceResponse.success();
        }
        ClerkAddEventParam clerkAddEventParam = JSONObject.parseObject(params, ClerkAddEventParam.class);
        String memberId = clerkAddEventParam.getMemberId();
        Integer changeType = clerkAddEventParam.getChangeType();
        if (Objects.equals(changeType, 1)) {
            // 换绑主导购清除建联状态
            contactLogService.clearContactLog(memberId, 2);
        }
        return ServiceResponse.success();
    }

    @Override
    public ServiceResponse<Void> contactDataRefreshMQ(String param) {
        if (StringUtils.isBlank(param)) {
            return ServiceResponse.success();
        }
        List<ContactDataBO> list = JSONObject.parseArray(param, ContactDataBO.class);
        if (CollectionUtils.isEmpty(list)) {
            return ServiceResponse.success();
        }
        ContactDataBO contactDataBO = list.get(0);
        String enterpriseId = contactDataBO.getEnterpriseId();
        ServiceResponse<PlatformPotentialCustomerOutDTO> potentialResponse = platformPotentialCustomerApiService.getPotentialCustomerOutRule(enterpriseId);
        if (!potentialResponse.isSuccess() || potentialResponse.getResult() == null) {
            return ServiceResponse.success();
        }
        for (ContactDataBO dataBO : list) {
            boolean unassigned = Objects.equals(dataBO.getClerkId(), "-1");
            Integer noConnPotCusNum = getNoConnPotCusNum(potentialResponse.getResult(), dataBO.getEnterpriseId(), dataBO.getStoreId(), dataBO.getClerkId(), unassigned);
            dataBO.setNoConnPotCusNum(noConnPotCusNum);
        }
        try {
            HoloClient client = holoDataSource.getClient();
            if (client == null) {
                logger.error("数仓数据源链接异常, 请检查！！！！{}", param);
                return ServiceResponse.success();
            }
            TableSchema tableSchema = client.getTableSchema("ads_gic_mbr_no_conn_mbr_1d");

            SerializeConfig serializeConfig = new SerializeConfig();
            serializeConfig.setPropertyNamingStrategy(PropertyNamingStrategy.SnakeCase);
            List<Put> puts = list
                    .stream()
                    .map(item -> {
                        Put temp = new Put(tableSchema);
                        temp.setObject("ent_id", item.getEnterpriseId());
                        temp.setObject("store_id", item.getStoreId());
                        temp.setObject("clerk_id", item.getClerkId());
                        temp.setObject("no_conn_pot_cus_num", item.getNoConnPotCusNum());
                        // 时间戳格式不行
                        temp.setObject("create_time", DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
                        return temp;
                    })
                    .collect(Collectors.toList());
            client.put(puts);
            logger.info("写数据组完成");
        } catch (Exception ex) {
            logger.info("数据组写入异常 {}", param, ex);
        }
        return ServiceResponse.success();
    }

    private Integer getNoConnPotCusNum(PlatformPotentialCustomerOutDTO result, String enterpriseId, String storeId, String clerkId, boolean unassigned) {
        if (StringUtils.isBlank(storeId) && StringUtils.isBlank(clerkId)) {
            return 0;
        }
        ClerkDTO clerkDTO = null;
        if (StringUtils.isNotBlank(clerkId)) {
            clerkDTO = clerkService.getClerkByClerkId(clerkId);
        }
        String clerkTypeStr = "1";
        CustomerDTO params = new CustomerDTO();
        if (clerkDTO != null) {
            clerkTypeStr = "0";
            clerkId = clerkDTO.getClerkId();
            Integer clerkType = clerkDTO.getClerkType();
            if (clerkType == 0 || clerkType == 1) {
                storeId = clerkDTO.getStoreId();
            }
        }
        ContactParamDTO contact = new ContactParamDTO();
        contact.setRuleJSON(JSON.toJSONString(result));
        contact.setContactType(0);
        params.setStoreId(storeId);
        params.setClerkId(clerkId);
        params.setClerkType(clerkTypeStr);
        params.setEnterpriseId(enterpriseId);
        params.setContactParamDTO(contact);
        MemberInfoListParamsDTO memberInfoListParamsDTO = new MemberInfoListParamsDTO();
        // 查询无归属数据
        if (unassigned) {
            FilterListDTO filterListDTO = new FilterListDTO();
            filterListDTO.setFilterType("1");
            ChildDTO child = new ChildDTO();
            child.setId("-1");
            filterListDTO.setChild(child);
            memberInfoListParamsDTO.setFilterList(Lists.newArrayList(filterListDTO));
        }
        ServiceResponse<ContactSumDTO> noContactResponse = customerService.contactMemberSum(new com.gic.haoban.base.api.common.BasePageInfo(), params, memberInfoListParamsDTO);
        return noContactResponse.getResult() != null ? noContactResponse.getResult().getTotalCount() : 0;
    }
}
