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

import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.ToolUtil;
import com.gic.member.ext.api.dto.growth.req.MemberGrowthChangeValueReq;
import com.gic.member.ext.api.dto.growth.resp.MemberGrowthOperateResp;
import com.gic.member.ext.api.service.MemberGrowthWriteApiService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gic.commons.util.DateUtil;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.haoban.manage.api.dto.ExternalMemberLogDTO;
import com.gic.haoban.manage.service.dao.mapper.ExternalMemberLogMapper;
import com.gic.haoban.manage.service.dao.mapper.TabHaobanExternalClerkRelatedMapper;
import com.gic.haoban.manage.service.entity.TabExternalMemberLog;
import com.gic.haoban.manage.service.entity.TabHaobanExternalClerkRelated;
import com.gic.haoban.manage.service.service.ExternalMemberService;
import com.gic.member.api.dto.MemberDTO;
import com.gic.member.api.service.MemberOpenCardBusinessService;
import com.gic.member.api.service.MemberService;

@Service
public class ExternalMemberServiceImpl implements ExternalMemberService {
    
    private static final Logger logger = LoggerFactory.getLogger(ExternalMemberService.class);
    
    @Autowired
    private ExternalMemberLogMapper externalMemberLogMapper;
    @Autowired
    private MemberOpenCardBusinessService memberOpenCardBusinessService ;
    @Autowired
    private TabHaobanExternalClerkRelatedMapper tabHaobanExternalClerkRelatedMapper ;
    @Autowired
    private MemberService memberService ;
    @Autowired
    private MemberGrowthWriteApiService memberGrowthWriteApiService ;

    @Override
    public int insert(ExternalMemberLogDTO log) {
        TabExternalMemberLog entity = EntityUtil.changeEntity(TabExternalMemberLog.class, log);
        TabExternalMemberLog old = this.externalMemberLogMapper.selectRelationKey(log.getEnterpriseId(),
                log.getRelationKey());
        if (null != old) {
            return 0;
        }
        entity.setLogId(UniqueIdUtils.uniqueLong());
        this.externalMemberLogMapper.insert(entity);
        return 0;
    }

    public int updateStatus(String enterpriseId, long id, int statusFlag) {
        return this.externalMemberLogMapper.updateStatus(enterpriseId, id, statusFlag);
    }

    @Override
    public TabExternalMemberLog selectRelationKey(String enterpriseId, String relationKey) {
        TabExternalMemberLog log = this.externalMemberLogMapper.selectRelationKey(enterpriseId, relationKey);
        return log;
    }
    
    @Override
    public void welcomeForMember() {
        logger.info("欢迎语处理会员定时");
        Date end = DateUtil.getStartTimeOfDay() ;
        Date start = DateUtil.addNumForDay(end, -1) ;
        List<TabExternalMemberLog> list = this.externalMemberLogMapper.listForTimer(start, end) ;
        for(TabExternalMemberLog log : list) {
            String relationKey = log.getRelationKey() ;
            TabHaobanExternalClerkRelated related = tabHaobanExternalClerkRelatedMapper.getByRelationKey(relationKey,0);
            if (related == null) {
                logger.info("好友记录不存在relationKey={}",relationKey);
                continue ;
            }
            String enterpriseId = log.getEnterpriseId() ;
            if(StringUtils.isNotEmpty(related.getMemberId())) {
                this.externalMemberLogMapper.updateStatus(enterpriseId, log.getLogId(), 2) ;
                continue ;
            }
          
            String unionid = log.getUnionid() ;
            MemberDTO member = this.memberService.getMemberByUnionid(unionid, enterpriseId) ;
            if(null == member) {
                logger.info("会员记录不存在relationKey={},{}",relationKey,unionid);
                continue ;
            }
            String memberId =member.getMemberId() ;
            this.memberOpenCardBusinessService.memberClerkProcessByQywxFriend(enterpriseId, memberId, unionid, relationKey);
            this.externalMemberLogMapper.updateStatus(enterpriseId, log.getLogId(), 2) ;
        }
    }


    public void updateMemberGrowth(String enterpriseId , String memberId , String ruleCode , String title , String remark) {
        try {
            MemberGrowthChangeValueReq req = new MemberGrowthChangeValueReq();
            req.setEnterpriseId(enterpriseId);
            req.setMemberId(memberId);
            req.setRuleCode(ruleCode);
            req.setChannelCode(com.gic.enterprise.api.enums.PlatformChannelEnum.C_WORK_WECHAT.getChannelCode());
            req.setOuterChangeId(ToolUtil.randomUUID());
            req = req.desc(title, remark);
            ServiceResponse<MemberGrowthOperateResp> resp = this.memberGrowthWriteApiService.updateMemberGrowthChangeValue(req) ;
            logger.info("调用成长值={},{}", JSONObject.toJSONString(req), JSONObject.toJSONString(resp));
        }catch (Exception e) {
            logger.info("异常",e);
        }
    }

}
