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

import com.gic.haoban.manage.api.dto.StaffClerkRelationDTO;
import com.gic.haoban.manage.api.enums.SyncTaskTypeEnum;
import com.gic.haoban.manage.api.service.DealSyncOperationApiService;
import com.gic.haoban.manage.service.dao.mapper.TabHaobanClerkMainStoreRelatedMapper;
import com.gic.haoban.manage.service.entity.TabHaobanClerkMainStoreRelated;
import com.gic.haoban.manage.service.entity.TabHaobanStaff;
import com.gic.haoban.manage.service.service.ClerkMainStoreRelatedService;
import com.gic.haoban.manage.service.service.ExternalClerkRelatedService;
import com.gic.haoban.manage.service.service.StaffClerkRelationService;
import com.gic.haoban.manage.service.service.StaffService;
import com.gic.redis.data.util.RedisUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

import static org.slf4j.LoggerFactory.getLogger;

@Service
public class ClerkMainStoreRelatedServiceImpl implements ClerkMainStoreRelatedService {

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

    @Autowired
    private TabHaobanClerkMainStoreRelatedMapper mapper;

    @Autowired
    private StaffClerkRelationService staffClerkRelationService;

    @Autowired
    private ExternalClerkRelatedService externalClerkRelatedService;

    @Autowired
    private DealSyncOperationApiService dealSyncOperationApiService;

    @Autowired
    private StaffService staffService;
    
    @Override
    public TabHaobanClerkMainStoreRelated selectByWxEnterpriseIdAndStoreId(String staffId, String wxEnterpriseId) {
        return mapper.selectByWxEnterpriseIdAndStoreId(staffId, wxEnterpriseId, null);
    }
    
    @Override
    public TabHaobanClerkMainStoreRelated selectStaffMainStore(String staffId, String wxEnterpriseId) {
        return mapper.selectByWxEnterpriseIdAndStoreId(staffId, wxEnterpriseId, null);
    }

    @Override
    public void setMainStore(String staffId, String storeId, String wxEnterpriseId) {
        List<StaffClerkRelationDTO> staffClerkRelationDTOS = staffClerkRelationService.listManageBindByStaffId(staffId);
        if (CollectionUtils.isNotEmpty(staffClerkRelationDTOS)) {
            logger.info("区经无需设置主门店：{}", staffId);
            return;
        }
        String uuId = com.gic.haoban.common.utils.StringUtil.randomUUID();
        Date now = new Date();
        TabHaobanClerkMainStoreRelated t = new TabHaobanClerkMainStoreRelated();
        t.setStaffId(staffId);
        t.setWxEnterpriseId(wxEnterpriseId);
        t.setStoreId(storeId);
        t.setCreateTime(now);
        t.setUpdateTime(now);
        t.setStatusFlag(1);
        t.setFreshFriendFlag(1);
        t.setClerkMainStoreRelatedId(uuId);
        mapper.insert(t);
    }
    
    @Override
    public void reflushExternal(String wxEnterpriseId ,String staffId) {
        TabHaobanStaff staff = staffService.selectById(staffId);
        if (staff == null) {
            logger.info("员工不存在：{}", staffId);
            return;
        }
        String taskName = "自动刷新企业微信好友（" + staff.getStaffName() + "）";
        String taskId = dealSyncOperationApiService.createWxFriendTaskSingle(wxEnterpriseId, taskName, staffId, staff.getStaffName(), SyncTaskTypeEnum.FRIEND_SINGLE.getType());
        if (StringUtils.isBlank(taskId)) {
            logger.info("刷新好友失败或正在刷新：{},{}", staffId);
            return;
        }
        dealSyncOperationApiService.dealWxFriendClerkSingle(taskId, staffId, staffId, wxEnterpriseId);
        logger.info("开始自动刷新好友任务id={},staffId={}", taskId,staffId);
    }

    @Override
    public TabHaobanClerkMainStoreRelated getMainStoreByStaffId(String staffId, String wxEnterpriseId) {
       return this.getMainStoreByStaffId(staffId, wxEnterpriseId,null);
    }

    @Override
    public TabHaobanClerkMainStoreRelated getMainStoreByStaffId(String staffId, String wxEnterpriseId,
                                                                List<String> storeIdList) {
        TabHaobanClerkMainStoreRelated mainStoreRelated = mapper.selectByWxEnterpriseIdAndStoreId(staffId, wxEnterpriseId, storeIdList);
        if (null != mainStoreRelated) {
            return mainStoreRelated;
        }
        this.mapper.delStaffMainStore(staffId, wxEnterpriseId);
        return setStaffMainStore(staffId, wxEnterpriseId, storeIdList);
    }

    /**
     * 随机设置主门店
     *
     * @param staffId
     * @param wxEnterpriseId
     * @return
     */
    private TabHaobanClerkMainStoreRelated setStaffMainStore(String staffId, String wxEnterpriseId, List<String> storeIdList) {
        List<StaffClerkRelationDTO> clerkRelationDTOS = staffClerkRelationService.listByStaffId(wxEnterpriseId, staffId, storeIdList);
        if (CollectionUtils.isEmpty(clerkRelationDTOS)) {
            return null;
        }
        StaffClerkRelationDTO staffClerkRelationDTO = clerkRelationDTOS.get(0);
        String lockKey = "set-main-store:" + staffId;
        RedisUtil.lock(lockKey, 3L);
        TabHaobanClerkMainStoreRelated mainStoreRelated = mapper.selectByWxEnterpriseIdAndStoreId(staffId, wxEnterpriseId, null);
        if (null == mainStoreRelated) {
            this.setMainStore(staffId, staffClerkRelationDTO.getStoreId(), wxEnterpriseId);
            mainStoreRelated = mapper.selectByWxEnterpriseIdAndStoreId(staffId, wxEnterpriseId, null);
        }
        RedisUtil.unlock(lockKey);
        return mainStoreRelated;
    }

    @Override
    public TabHaobanClerkMainStoreRelated delMainStore(String staffId, String storeId, String wxEnterpriseId) {
        //删除主门店
        mapper.delMainStore(staffId, storeId, wxEnterpriseId);
        //删除主门店外部联系人 好友
        externalClerkRelatedService.delByStoreIdAndStaffId(storeId, staffId);
        //设置主门店
        return this.setStaffMainStore(staffId, wxEnterpriseId, null);
    }

    @Override
    public void delMainStoreByStoreIds(Set<String> storeIds) {
        //删除主门店
        mapper.delByStoreIds(storeIds);
        //删除外部联系人
        externalClerkRelatedService.delByStoreIds(storeIds);
    }

    @Override
    public void update(TabHaobanClerkMainStoreRelated r) {
        r.setUpdateTime(new Date());
        mapper.updateByPrimaryKeySelective(r);
    }



}
