package com.sifang.modules.taskdispatch.service.autod;

import com.sifang.modules.flowable.dao.ItemManageDao;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.taskdispatch.constant.ReviewDispatchConst;
import com.sifang.modules.taskdispatch.service.CrmReviewDispatchService;
import com.sifang.modules.taskdispatch.service.autod.vo.ItemTask;
import com.sifang.modules.taskdispatch.service.autod.vo.ItemTaskWorker;
import com.sifang.modules.taskdispatch.vo.ItemAssignReq;
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 java.util.Collections;
import java.util.Date;

/**
 * 自动派单
 */
@Service
public class ItemDispatchService {


    @Autowired
    CrmReviewDispatchService reviewDispatchService;
    @Autowired
    ItemManageDao itemManageDao;
    @Autowired
    ItemTaskEventBus itemTaskEventBus;

    private static final Logger log = LoggerFactory.getLogger(ItemDispatchService.class);

    public void dispatchByLuobote(String partnerId, ItemTask task, ItemTaskWorker worker) {
        String memberId = worker.getMemberId();
        try {
            ItemAssignReq req = new ItemAssignReq();
            req.setAuto(true);
            req.setMemberId(memberId);
            req.setItemIds(Collections.singletonList(task.getItemId()));
            reviewDispatchService.batchAssign(req);
            log.info("auto assign to member.id: {}, name: {}, task.id: {},partner_id: {}", memberId, worker.getName(), task.getItemId(), partnerId);
            itemTaskEventBus.notifyTaskItemDispatched(memberId, new Date());
        } catch (BusinessException bex) {
            if (StringUtils.equalsAny(bex.getErrorCode(), ReviewDispatchConst.ERR_CODE_MEMBER_OFFLINE)) {
                log.info("does not need inc fail times for user is offline ...");
            } else {
                itemManageDao.incFailTimes(task.getItemId());
            }
            throw bex;
        } catch (Exception ex) {
            itemManageDao.incFailTimes(task.getItemId());
            throw ex;
        }
    }
}
