package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.CustomerCallbackLogEntity;
import com.house365.beans.entity.CustomerEntity;
import com.house365.beans.entity.ReceiveCallRecordEntity;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.IllegalServiceParameterException;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestObject;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.ws.beans.response.CustomerResponse;
import com.house365.ws.service.interfaces.ICustomerCallbackLogService;
import com.house365.ws.service.interfaces.IReceiveCallRecordService;
import com.house365.ws.system.ReturnAppResult;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * <p>Title: 接收录音文件</p>
 * <p>Description: </p>
 * <p>Date: 16/9/15</p>
 *
 * @author XN
 * @version 1.0
 */
@Service("receiveCallRecord")
public class ReceiveCallRecordImpl implements IReceiveCallRecord {
    private static final Logger LOGGER = LoggerFactory.getLogger("sysLog");

    @Autowired
    private IReceiveCallRecordService receiveCallRecordService;
    @Autowired
    private ICustomerCallbackLogService callbackLogService;

    @Override
    public Object rollback() {
        return null;
    }

    @Override
    public void commit() {

    }

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerResponse> response = new House365RestResponse<CustomerResponse>();
        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doBusiness(map);
            String msg = ReturnAppResult.APP_SUCCESS.getResultMessage();
            if (data.getParaMap() != null && data.getParaMap().containsKey("msg")) {
                msg = ReturnAppResult.APP_SUCCESS.getResultMessage() + "[" + String.valueOf(
                        data.getParaMap().get("msg") + "]");
            }

            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(msg);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        return result;
    }

    @Override
    public boolean isControlService() {
        return false;
    }

    @Override
    public boolean isLogService() {
        return false;
    }

    @Override
    public boolean isMonitorService() {
        return false;
    }

    /**
     * 业务层统逻辑处理
     */
    private House365RestObject<CustomerEntity> doBusiness(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<CustomerEntity> restObject = new House365RestObject<>();
        String call = getMapValueByKey("call", map, "");//短号
        String pid = getMapValueByKey("pid", map, "");//pid 业务
        String ctrStarttime = getMapValueByKey("ctr_starttime", map, "");//通话开始时间
        String ctrEndtime = getMapValueByKey("ctr_endtime", map, "");//通话结束时间
        String ctrDuration = getMapValueByKey("ctr_duration", map, "");//通话时长 s
        String ctrRecord = getMapValueByKey("ctr_record", map, "");//录音文件名称
        String ctrStatus = getMapValueByKey("ctr_status", map, "");//接通状态 1接通 0未接通

        LOGGER.info("receive call record call:[{}]pid:[{}]statrttime:[{}]endtime:[{}]duration:[{}]record:[{}]status:[{}]",
                call, pid, ctrStarttime, ctrEndtime, ctrDuration, ctrRecord, ctrStatus);

        //保存录音文件信息
        ReceiveCallRecordEntity receiveCallRecordEntity = new ReceiveCallRecordEntity();
        receiveCallRecordEntity.setCaller(call);
        receiveCallRecordEntity.setPid(Integer.valueOf(pid));
        receiveCallRecordEntity.setStartTime(new Date(Long.valueOf(ctrStarttime)));
        receiveCallRecordEntity.setEndTime(new Date(Long.valueOf(ctrEndtime)));
        receiveCallRecordEntity.setDuration(Integer.valueOf(ctrDuration));
        receiveCallRecordEntity.setRecord(ctrRecord);
        receiveCallRecordEntity.setStatus(Integer.valueOf(ctrStatus));
        receiveCallRecordService.save(receiveCallRecordEntity);

        //更新回访记录-录音信息
        CustomerCallbackLogEntity callbackLogEntity = (CustomerCallbackLogEntity) callbackLogService.getById(Integer.valueOf(pid));
        callbackLogEntity.setCallRecordId(receiveCallRecordEntity.getId());
        callbackLogEntity.setCallRecordName(ctrRecord);
        callbackLogEntity.setCallRecordDuration(Integer.valueOf(ctrDuration));
        callbackLogService.update(callbackLogEntity);
        return restObject;
    }

    /**
     * 获取map中的值
     *
     * @param key          key
     * @param map          map
     * @param defaultValue 默认值
     * @return value
     */
    private String getMapValueByKey(String key, Map<String, Object> map, String defaultValue) {
        String value = "";
        if (map.containsKey(key) && map.get(key) != null && !Strings.isNullOrEmpty(((String[]) map.get(key))[0])) {
            value = ((String[]) map.get(key))[0];
        }

        if (Strings.isNullOrEmpty(value)) {
            value = defaultValue;
        }
        return value;
    }

    /**
     * 业务层统校验自己所需参数是否存在
     * 所有参数都要存在
     *
     * @author hqc
     */
    protected void checkInterfaceParameter(
            Map<String, Object> map, String[] checkParams
    ) throws IllegalServiceParameterException {
        // 方法所需参数
        for (String str : checkParams) {
            // 如果不存在跳出 同时抛出相应异常
            if (!map.containsKey(str)) {
                throw new IllegalServiceParameterException("业务入口参数异常：" + str + "参数为空!");
            }
        }
    }

}
