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

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
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.service.MemberService;
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;


    @Override
    public void saveContactLog(ContactLogQDTO qdto) {
        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();

        // 是否周期内首次建联 同周期内是否有记录
        Integer contactCycle = 1;
        // 建联周期 14天内同周期/14天以上周期+1
        Integer contactCycleFirst = Constant.FLAG_TRUE;
        TabContactLog lastContactLog = contactLogMapper.queryLastLog(memberId, clerkId);
        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);
        // todo 刷新es建联时间
    }

    @Override
    public void clearContactLog(String memberId,Integer clearType) {
        logger.info("清除建联状态:{},clearType:{}", memberId, clearType);
        TabContactLog lastContactLog = contactLogMapper.queryLastLog(memberId, 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);
        }
        // todo 清除es建联时间 -1
    }

    @Override
    public TabContactLog getClerkContactTime(String memberId) {
        TabContactLog lastContactLog = contactLogMapper.queryLastLog(memberId, 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;
    }
}
