package org.linlinjava.jz.admin.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.jz.admin.dto.CalllogAllinone;
import org.linlinjava.jz.admin.util.SecurityHelper;
import org.linlinjava.jz.core.system.SystemConfig;
import org.linlinjava.jz.core.util.ResponseUtil;
import org.linlinjava.jz.db.domain.*;
import org.linlinjava.jz.db.service.*;
import org.linlinjava.jz.db.util.CallResultConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.ws.soap.Addressing;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 电访结果处理类（呼入 呼出）
 * IB流程：-》进电响铃-》记录calllog_record->结束保存calllog(1:1)+更新电访record
 * OB流程:-》点击处理ob任务-->记录calllogrecord-》结束保存calllog(1:N)+更新电访record(外呼时 calllog和record 1对多关系；一个任务一次会有多个外呼 如外呼了老公客户 客户说不清楚这个事情，请打老婆号码）
 * -》更新built任务状态
 */
@Service
@Transactional
public class AdminCalllogService {

    private final Log logger = LogFactory.getLog(AdminCalllogService.class);

    @Autowired
    private JzCalllogService calllogService;

    @Autowired
    private JzCalllogRecordService recordService;

    @Autowired
    private JzBuiltListService builtListService;
    @Autowired
    private JzCallConfigService jzCallConfigService;

    @Autowired
    private JzTicketRelationService relationService;

    public List<JzCalllog> querySelective(String mobile, String callType, List<Short> callResultArray, Integer campaignId, Integer page, Integer limit, String sort, String order) {
        return calllogService.querySelective(mobile, callType, callResultArray, campaignId, page, limit, sort, order);
    }

    /***
     * 添加电访记录
     * @param allinone
     * @return
     */
    public Object create(CalllogAllinone allinone) {
        if (allinone == null || allinone.getCalllog() == null) {
            return ResponseUtil.badArgumentValue();
        }
        if (allinone.getCalllog().getCallType().equals("IB")) {
            return add_IB(allinone);
        } else {
            return add_OB(allinone);
        }
    }

    /**
     * 外拨任务结束 增加电访记录
     *
     * @param allinone
     * @return
     */
    private Object add_OB(CalllogAllinone allinone) {
        if (allinone.getCalllog() == null || allinone.getCalllog().getBuiltId() == null)
            return ResponseUtil.badArgumentValue();

        JzCalllog calllog = allinone.getCalllog();

        Integer record_id = 0;
        Integer call_id = 0;
        if (calllog != null && calllog.getBuiltId() != null && calllog.getBuiltId() > 0)//有关联任务
        {
            //获取电访任务
            JzBuiltList builtList = builtListService.findById(calllog.getBuiltId());

            calllog.setCreateUser(SecurityHelper.getAdminId());
            calllog.setCreateTime(LocalDateTime.now());
            calllog.setStartTime(LocalDateTime.now());
            calllog.setCampaignId(builtList.getCampaignId());
            call_id = calllogService.add(calllog);

            //未接通连续拨打次数
            JzCallConfig jzCallConfig = jzCallConfigService.selectByKeyName(SystemConfig.jz_CALL_NO_CONNECT_TIMES);
            int noConnectedTime = Integer.parseInt(jzCallConfig.getKeyValue());
            //int noConnectedTime = SystemConfig.getCallNoConnectedTimes();

            //根据电访结果不同 处理built
            builtList.setLastCallTime(LocalDateTime.now());//最后一次拨打时间
            builtList.setContactTimes(builtList.getContactTimes() + 1);//已拨打次数加1次

            //本次电访结果
            int callResult = calllog.getCallResult();

            /**
             * 根据电访结果不同 更新任务表built_list
             */
            if (callResult == CallResultConstant.RESULT_CALLBACK) { //需要下次回拨
                builtList.setNextCallTime(calllog.getCallbackTime());
                builtList.setRemark(calllog.getCallbackRemark());
                builtList.setCallResult(CallResultConstant.RESULT_CALLBACK);
            } else if (callResult == CallResultConstant.RESULT_NO_NULL ||
                    callResult == CallResultConstant.RESULT_SUCCESS ||
                    callResult == CallResultConstant.RESULT_REJECT) {//空号 成功 拒访
                builtList.setCallResult((short) (10 + callResult));//电访结果直接+10;表示结束 以后不再拨打
            } else {//忙线 关机 停机 无法接通 欠费
                if (builtList.getContactTimes() >= noConnectedTime)//已经达到最大拨打次数
                    builtList.setCallResult((short) (10 + callResult));//结束任务
                else {
                    //未达到最大拨打次数 将任务延后
                    int delay = getDelayHour((short) callResult);
                    builtList.setCallResult((short) callResult);
                    builtList.setLastCallTime(builtList.getLastCallTime().plusHours(delay));
                }
            }
            //更新built
            builtListService.update(builtList);
        }

        //将callid赋值给record中的外键
        if (allinone.getCalllogRecords() != null && allinone.getCalllogRecords().size() > 0) {
            recordService.update(allinone.getCalllogRecords(), call_id);
        }

        //电访和工单关联
        addRelation(call_id, allinone.getTickets());

        //刷新任务列表 将已处理的built中列表中清除
        return ResponseUtil.ok(call_id);
    }


    /**
     * 进电结束后 电访结果处理（保存电访及话务记录）
     *
     * @return
     */
    private Object add_IB(CalllogAllinone allinone) {

        if (allinone.getCalllog() == null || allinone.getCalllogRecords() == null || allinone.getCalllogRecords().size() == 0) {
            return ResponseUtil.badArgumentValue();
        }

        //电访记录
        JzCalllog calllog = allinone.getCalllog();
        calllog.setEndTime(LocalDateTime.now());
        calllog.setCreateTime(LocalDateTime.now());
        calllog.setCreateUser(SecurityHelper.getAdminId());
        if (calllog.getCallResult().equals(CallResultConstant.RESULT_CALLBACK)) {//需要回拨
            JzBuiltList builtList = new JzBuiltList();
            builtList.setCustomerId(calllog.getCustomerId());
            builtList.setCampaignId(1);
            builtList.setCreateTime(LocalDateTime.now());
            builtList.setRemark(calllog.getCallbackRemark());
            builtList.setNextCallTime(calllog.getCallbackTime());
            builtList.setCallResult((short) 0);
            builtList.setAssignedTime(LocalDateTime.now());
            builtList.setUserId(SecurityHelper.getAdminId());
            builtList.setIsCallback(true);
            builtList.setCallSource("IB");
            builtListService.add(builtList);
        }
        int call_Id = calllogService.add(calllog);

        //更新通话记录
        recordService.update(allinone.getCalllogRecords(), call_Id);

        //电访和工单关联
        addRelation(call_Id, allinone.getTickets());

        return ResponseUtil.ok(call_Id);

    }

    /**
     * 添加电访和工单关系
     *
     * @param callId
     * @param tickets
     */
    private void addRelation(int callId, List<Integer> tickets) {
        if (tickets == null || tickets.size() == 0) return;
        for (int id : tickets) {
            JzTicketRelation relation = new JzTicketRelation();
            relation.setType((short) 0);
            relation.setTicketId(id);
            relation.setfId(callId);
            relation.setCreateUser(SecurityHelper.getAdminId());
            relation.setCreateTime(LocalDateTime.now());
            relationService.add(relation);
        }
    }


    /**
     * 新增电访记录表（ib、ob）
     *
     * @param record
     * @return
     */
    public Object add_record(JzCalllogRecord record) {
        if (record.getCustomerId() == null || record.getCustomerId() == 0) return ResponseUtil.badArgumentValue();
        record.setCreateTime(LocalDateTime.now());
        record.setCreateUser(SecurityHelper.getAdminId());
        int id = recordService.add(record);
        return ResponseUtil.ok(id);
    }

    /**
     * 通话结束 更新通话记录表信息 时长 结果等
     *
     * @param record
     * @return
     */
    public Object updte_Record(JzCalllogRecord record) {
        if (record.getCustomerId() == null || record.getCustomerId() == 0) {
            return ResponseUtil.ok();
        }
        recordService.update(record);

        return ResponseUtil.ok();
    }


    /**
     * 根据电访结果 返回下次拨打的延后时长（小时）
     *
     * @param callResult
     * @return
     */
    int getDelayHour(short callResult) {
        if (callResult == CallResultConstant.RESULT_NO_ANSWER)
            return SystemConfig.getCallNoAnswer();
        if (callResult == CallResultConstant.RESULT_NO_CONTACT)
            return SystemConfig.getCallNoConnected();
        if (callResult == CallResultConstant.RESULT_BUSY)
            return SystemConfig.getCallBusy();
        if (callResult == CallResultConstant.RESULT_OVERDUE)
            return SystemConfig.getCallOverdue();
        if (callResult == CallResultConstant.RESULT_POWER_OFF)
            return SystemConfig.getCallPowerOff();

        return 0;
    }


}
