package org.linlinjava.jz.admin.service;

import org.linlinjava.jz.admin.excel.CustomerExcelModel;
import org.linlinjava.jz.db.domain.CustomerClient;
import org.linlinjava.jz.db.domain.JzBuiltList;
import org.linlinjava.jz.db.service.CustomerClientService;
import org.linlinjava.jz.db.service.JzBuiltListService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author fuxubing
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AdminUploadService {
    @Resource
    private CustomerClientService customerClientService;
    @Resource
    private JzBuiltListService jzBuiltListService;

    public List<CustomerExcelModel> save(List<CustomerExcelModel> datas, Integer channelId, Integer campaignId) {

        List<CustomerExcelModel> failDatas = new ArrayList<>();

        datas.forEach(item -> {
            //手机号查询客户是否存在，不存在则插入
            CustomerClient customerClient = customerClientService.findUserByMobile(item.getTel());
            if (null == customerClient) {
                customerClient = new CustomerClient();
                customerClient.setCustomerNo(customerClientService.getRandNum());
                customerClient.setChannelId(channelId);
                customerClient.setSource("Other");
                BeanUtils.copyProperties(item, customerClient);
                customerClientService.add(customerClient);//入库
            }
            //查询客户任务数量
            Long count = jzBuiltListService.queryCountByExample(customerClient.getId().intValue(), campaignId);
            if (count == 0) {
                JzBuiltList builtList = new JzBuiltList();
                builtList.setCustomerId(customerClient.getId().intValue());
                builtList.setCreateTime(LocalDateTime.now());
                builtList.setCallResult((short) 0);
                builtList.setCampaignId(campaignId);
                builtList.setCallSource("Campaign");
                builtList.setNextCallTime(LocalDateTime.now());
                jzBuiltListService.add(builtList);
            } else {
                item.setRemark("客户任务已存在");
                failDatas.add(item);
            }
        });

        return failDatas;
    }
}
