package org.linlinjava.jz.db.service;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.SecurityUtils;
import org.linlinjava.jz.db.dao.JzBuiltListBatchMapper;
import org.linlinjava.jz.db.dao.JzBuiltListCountMapper;
import org.linlinjava.jz.db.dao.JzBuiltListMapper;
import org.linlinjava.jz.db.domain.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.time.LocalDateTime;

import javax.annotation.Resource;

@Service
public class JzBuiltListService {

    @Resource
    private JzBuiltListMapper builtListMapper;

    @Resource
    private JzBuiltListCountMapper countMapper;

    @Autowired
    private CustomerClientService customerClientService;

    @Resource
    private JzBuiltListBatchMapper batchMapper;


    public List<JzBuiltList> querySelective(Integer userId, String mobile, Integer campaignId, List<Short> callResultArray, Integer page, Integer size, String sort, String order) {
        JzBuiltListExample example = new JzBuiltListExample();
        JzBuiltListExample.Criteria criteria1 = example.createCriteria();
        //JzBuiltListExample.Criteria criteria2 = example.createCriteria();

        //任务id
        criteria1.andCampaignIdEqualTo(campaignId);
        //criteria2.andCampaignIdEqualTo(campaignId);


        if (!StringUtils.isEmpty(mobile)) {
            CustomerClient customerClient = customerClientService.findUserByMobile(mobile);
            if (customerClient != null) {
                criteria1.andCustomerIdEqualTo(customerClient.getId().intValue());
                //criteria2.andCustomerIdEqualTo(customerClient.getId().intValue());
            } else
                criteria1.andCustomerIdEqualTo(-1);
        }
        if (callResultArray != null && callResultArray.size() != 0) {
            criteria1.andCallResultIn(callResultArray);
        }
/*        List<Short> success= Lists.newArrayList();
        success.add(CallResultConstant.RESULT_CALLBACK);//回拨
        success.add(CallResultConstant.RESULT_SUCCESS);
        criteria1.andCallResultNotIn(success)*/

        //固定条件:任务拨打时间和状态条件
        criteria1.andNextCallTimeLessThan(LocalDateTime.now());
        criteria1.andCallResultLessThan((short) 10);
        criteria1.andUserIdEqualTo(userId);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, size);
        return builtListMapper.selectByExample(example);
    }

    /**
     * 返回坐席任务名及未拨打数量
     *
     * @param userId
     * @return
     */
    public List<JzBuiltListCount> countByCampaignName(Integer userId) {
        return countMapper.campaignsCount(userId);
    }

    public JzBuiltList findById(Integer id) {

        return builtListMapper.selectByPrimaryKey(id);
    }

    /**
     * 执行campaign中的sql 返回bulit对象
     *
     * @param sql 注意要去重
     * @return
     */
    public List<JzBuiltList> runSql(String sql, Integer campaignId) {
        List<JzBuiltList> lists = batchMapper.builtList(sql);
        for (JzBuiltList builtList : lists) {
            builtList.setCreateTime(LocalDateTime.now());
            builtList.setCallResult((short) 0);
            builtList.setCampaignId(campaignId);
            builtList.setCallSource("Campaign");
            builtList.setNextCallTime(LocalDateTime.now());
        }

        return lists;
    }

    /**
     * 执行built的批量插入 （任务数据拉取时 使用）
     *
     * @param lists
     */
    public void runInsertBatch(List<JzBuiltList> lists) {
        if (lists == null || lists.size() == 0) return;

        List<JzBuiltList> tempList = new ArrayList<JzBuiltList>();
        for (JzBuiltList jb : lists) {

            tempList.add(jb);
            if (tempList.size() > 500) {
                batchMapper.insertBuiltBatch(tempList);
                tempList.clear();
            }
        }

        if (tempList.size() > 0) {
            batchMapper.insertBuiltBatch(lists);
        }

    }

    /**
     * 批量更新任务数据（分配归属客服时使用）
     *
     * @param builtLists
     */
    public void runUpdateBuiltBatch(List<JzBuiltList> builtLists) {
        if (builtLists == null || builtLists.size() == 0) return;

        List<JzBuiltList> tempList = new ArrayList<JzBuiltList>();
        for (JzBuiltList jb : builtLists) {
            tempList.add(jb);
            if (tempList.size() > 500) {
                batchMapper.updateBuiltBatch(tempList);
                tempList.clear();
            }
        }

        if (tempList.size() > 0) {
            batchMapper.updateBuiltBatch(tempList);
        }
    }

    /**
     * 获取所有可以分配的任务数据列表
     *
     * @param campaignId
     * @return
     */
    public List<JzBuiltList> queryCanAssignedByCampaignId(Integer campaignId) {
        JzBuiltListExample example = new JzBuiltListExample();
        JzBuiltListExample.Criteria criteria1 = example.createCriteria();

        criteria1.andCampaignIdEqualTo(campaignId);
        criteria1.andUserIdIsNull();

        return builtListMapper.selectByExample(example);
    }

    /**
     * 获取所有可以分配的任务数据列表
     *
     * @param campaignId
     * @return
     */
    public List<JzBuiltList> queryCanAssignedByCampaignId(Integer campaignId,List<Integer> shops) {
        JzBuiltListExample example = new JzBuiltListExample();
        JzBuiltListExample.Criteria criteria1 = example.createCriteria();

        criteria1.andCampaignIdEqualTo(campaignId);
        criteria1.andUserIdIsNull();
        if(shops!=null&&shops.size()>0)
            criteria1.andShopIdIn(shops);

        return builtListMapper.selectByExample(example);
    }


    public long queryCountByCampaignId(Integer campaignId, Integer userId) {
        JzBuiltListExample example = new JzBuiltListExample();
        JzBuiltListExample.Criteria criteria1 = example.createCriteria();
        if (null != campaignId) {
            criteria1.andCampaignIdEqualTo(campaignId);
        }
        if (null != userId) {
            criteria1.andUserIdEqualTo(userId);
        }

        criteria1.andNextCallTimeLessThan(LocalDateTime.now());
        criteria1.andCallResultLessThan((short) 10);

        return builtListMapper.countByExample(example);
    }

    public void add(JzBuiltList builtList) {
        builtList.setCreateTime(LocalDateTime.now());
        builtListMapper.insertSelective(builtList);
    }

    public void update(JzBuiltList builtList) {
        builtListMapper.updateByPrimaryKeySelective(builtList);
    }

    /*
     * //离职人员 未拨打的任务数量
     */
    public int countByUserId(Integer userId) {
        JzBuiltListExample example = new JzBuiltListExample();
        example.or().andUserIdEqualTo(userId).andCallResultEqualTo((short) 0);
        return (int) builtListMapper.countByExample(example);
    }

    public List<JzBuiltList> selectByUserId(Integer userId, Integer campaignId) {
        JzBuiltListExample example = new JzBuiltListExample();
        example.or().andUserIdEqualTo(userId).andCampaignIdEqualTo(campaignId)
                .andCallResultEqualTo((short) 0);
        return builtListMapper.selectByExample(example);
    }

    public List<Map<Object, Object>> getGroupCampaignCount(Integer userId) {
        return builtListMapper.getGroupCampaignCount(userId);
    }

    public Long queryCountByExample(Integer customerId, Integer campaignId) {
        JzBuiltListExample example = new JzBuiltListExample();
        example.or().andCampaignIdEqualTo(campaignId).andCustomerIdEqualTo(customerId);
        return builtListMapper.countByExample(example);
    }
}
