package com.gic.haoban.manage.service.service.contact.impl;

import cn.hutool.core.date.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.BusinessException;
import com.gic.api.base.commons.Constant;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.enterprise.api.service.StoreService;
import com.gic.haoban.manage.api.qdto.contact.ContactLogQDTO;
import com.gic.haoban.manage.service.dao.mapper.contact.TabContactFollowMapper;
import com.gic.haoban.manage.service.dao.mapper.contact.TabContactLogMapper;
import com.gic.haoban.manage.service.entity.contact.TabContactLog;
import com.gic.haoban.manage.service.service.contact.ContactFollowService;
import com.gic.haoban.manage.service.service.contact.ContactLogService;
import com.gic.member.api.dto.MemberStoreClerkDTO;
import com.gic.member.api.dto.MemberStoreDTO;
import com.gic.member.api.dto.es.MemberDataDTO;
import com.gic.member.api.service.MemberService;
import com.gic.search.engine.api.dto.ESResponse;
import com.gic.search.engine.api.dto.dynamic.DynamicDocDTO;
import com.gic.search.engine.api.service.dynamic.ESDataDynamicOperationApiService;
import com.gic.store.goods.service.StoreGoodsService;
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.Objects;

@Service("contactLogService")
public class ContactLogServiceImpl implements ContactLogService {

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

    @Autowired
    private TabContactLogMapper contactLogMapper;
    @Autowired
    private StoreGoodsService storeGoodsService;
    @Autowired
    private ClerkService clerkService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private ESDataDynamicOperationApiService esDataDynamicOperationApiService;


    @Override
    public void saveContactLog(ContactLogQDTO qdto) throws BusinessException {
        logger.info("保存建联记录:{}", JSON.toJSONString(qdto));
        String enterpriseId = qdto.getEnterpriseId();
        String storeId = qdto.getStoreId();
        String clerkId = qdto.getClerkId();
        String memberId = qdto.getMemberId();
        DateTime date = DateUtil.date();
        MemberStoreClerkDTO memberStoreClerk = memberService.getMemberStoreClerk(memberId);
        if (memberStoreClerk == null) {
            logger.info("无专属导购无法建联");
            throw new BusinessException("-1", "无专属导购无法建联");
        }
        String mainClerkId = memberStoreClerk.getClerkId();
        if (!Objects.equals(mainClerkId, clerkId)) {
            logger.info("非专属导购无法建联");
            throw new BusinessException("-1", "非专属导购无法建联");
        }
        // 是否周期内首次建联 同周期内是否有记录
        Integer contactCycle = 1;
        // 建联周期 14天内同周期/14天以上周期+1
        Integer contactCycleFirst = Constant.FLAG_TRUE;
        TabContactLog lastContactLog = contactLogMapper.queryLastLog(memberId, clerkId,null);
        if (lastContactLog != null) {
            Date contactTime = lastContactLog.getContactTime();
            if (DateUtil.between(date, contactTime, DateUnit.SECOND) > 14 * 24 * 60 * 60) {
                contactCycle = lastContactLog.getContactCycle() + 1;
            }else {
                contactCycle = lastContactLog.getContactCycle();
                contactCycleFirst = Constant.FLAG_FALSE;
            }
        }
        logger.info("建联周期:{},是否周期内首次:{}", contactCycle, contactCycleFirst);

        TabContactLog contactLog = new TabContactLog();
        ClerkDTO clerkDTO = clerkService.getClerkByClerkId(clerkId);
        contactLog.setClerkId(clerkId);
        contactLog.setStoreId(storeId);
        if (clerkDTO != null) {
            contactLog.setClerkCode(clerkDTO.getClerkCode());
            contactLog.setClerkName(clerkDTO.getClerkName());
        }
        if (StringUtils.isNotBlank(storeId)) {
            StoreDTO store = storeService.getStore(storeId);
            if (store != null) {
                contactLog.setStoreCode(store.getStoreCode());
            }
        }
        contactLog.setLogId(UniqueIdUtils.uniqueLong());
        contactLog.setMemberId(memberId);
        contactLog.setContactStatus(Constant.FLAG_TRUE);
        contactLog.setContactTime(date);
        contactLog.setContactCycle(contactCycle);
        contactLog.setContactCycleFirst(contactCycleFirst);
        // todo 建联时间
        contactLog.setPotentialTime(null);
        contactLog.setEnterpriseId(enterpriseId);
        contactLogMapper.insert(contactLog);
        // 刷新es建联时间
        Long clerkContactTime = Long.parseLong(DateUtil.format(date, DatePattern.PURE_DATETIME_PATTERN));
        refreshContactTime(enterpriseId, memberId, clerkContactTime);
    }

    @Override
    public void clearContactLog(String memberId,Integer clearType) {
        logger.info("清除建联状态:{},clearType:{}", memberId, clearType);
        TabContactLog lastContactLog = contactLogMapper.queryLastLog(memberId, null,null);
        if (lastContactLog == null) {
            return;
        }
        // clearType 1 消费清除 2 换绑主导购（不清除表建联状态）
        if (Objects.equals(clearType, 1)) {
            TabContactLog update = new TabContactLog();
            update.setLogId(lastContactLog.getLogId());
            update.setContactStatus(Constant.FLAG_FALSE);
            contactLogMapper.update(update);
        }
        // 清除es建联时间 -1
        refreshContactTime(lastContactLog.getEnterpriseId(), memberId, -1L);
    }

    private void refreshContactTime(String enterpriseId,String memberId, Long contactTime) {
        DynamicDocDTO dynamicDocDTO = new DynamicDocDTO();
        dynamicDocDTO.setEnterpriseId(enterpriseId);
        dynamicDocDTO.setColumnCategoryCode("member");
        MemberDataDTO memberDataDTO = new MemberDataDTO();
        memberDataDTO.setMemberId(memberId);
        memberDataDTO.setId(memberId);
        memberDataDTO.setClerkContactTime(contactTime);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(dynamicDocDTO));
        dynamicDocDTO.setDocJson(jsonObject);
        dynamicDocDTO.setRefresh(Constant.FLAG_TRUE);
        ESResponse res = esDataDynamicOperationApiService.updateDataSingle(dynamicDocDTO, false);
        logger.info("刷新建联时间返回:{}", res.getErrCode());
    }

    @Override
    public TabContactLog getClerkContactTime(String memberId) {
        TabContactLog lastContactLog = contactLogMapper.queryLastLog(memberId, null,null);
        if (lastContactLog == null) {
            return null;
        }
        Integer contactStatus = lastContactLog.getContactStatus();
        if (Objects.equals(contactStatus, Constant.FLAG_FALSE)) {
            return null;
        }
        String clerkId = lastContactLog.getClerkId();
        Date contactTime = lastContactLog.getContactTime();
        MemberStoreClerkDTO memberStoreClerk = memberService.getMemberStoreClerk(memberId);
        if (memberStoreClerk == null) {
            return null;
        }
        logger.info("建联导购id:{},专属导购id:{}", clerkId, memberStoreClerk.getClerkId());
        if (!Objects.equals(clerkId, memberStoreClerk.getClerkId())) {
            return null;
        }
        if (DateUtil.compare(contactTime, DateUtil.date().offset(DateField.DAY_OF_MONTH, -14)) < 0) {
            return null;
        }
        return lastContactLog;
    }

    @Override
    public TabContactLog getLastByTime(String memberId, Date beginTime) {
        return contactLogMapper.queryLastLog(memberId, null,beginTime);
    }
}
