/**
 * 
 */
package com.foc.sound.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.foc.conf.Constants;
import com.foc.conf.GConstants;
import com.foc.sound.entity.CallPhoneInfoListEntity;
import com.foc.sound.entity.CallRecordsEntity;
import com.foc.sound.entity.SoundRecordingEntity;
import com.foc.sound.entity.UserInfo;
import com.foc.util.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 
 * @team IT Team
 * @author zhanglg
 * @version 1.0
 * @time 2017年2月23日
 */

public class SoundService {
    private static final String PATH_FORMAt = GConstants.getValue("file.path.format", "{yyyy}{mm}{dd}");
    QueryRunner run = null;

    public SoundService() {
        try {
            this.run = new QueryRunner(DBHelper.getDataSource());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private List<SoundRecordingEntity> getList(JSONObject result) {

        String status = (String) result.get("status");
        JSONObject dataJson = (JSONObject) result.get("data");
        JSONArray jsonArray = (JSONArray) dataJson.get("list");
        if ("2000".equals(status)) {
            List<SoundRecordingEntity> list = JSONObject.parseArray(jsonArray.toJSONString(),
                    SoundRecordingEntity.class);
            /*
             * SoundRecordingResponseEntity responseEntity =
             * JSON.parseObject(jsonArray, SoundRecordingResponseEntity.class);
             * if (responseEntity != null) {
             * 
             * return responseEntity.getList();
             * 
             * }
             */
            return list;
        }
        return null;
    }

    public void insertData(SoundRecordingEntity entity) {
        
        int count = MapCounter.add(entity.getId(), 1);
        
        if(count>1){
            
            System.out.println(JSON.toJSONString(entity));
        }
//        if("76fef4ea009347daec8effb7826b1eae".equals(entity.getId())){
//            
//            System.out.println("76fef4ea009347daec8effb7826b1eae:"+JSON.toJSONString(entity));
//        }
        if (StringUtils.isNoneBlank(entity.getId())) {
            Date createDate = new Date(System.currentTimeMillis());
            entity.setCurrent(createDate);
            entity.setCurrentTimeMillis(createDate.getTime());

            entity.setFocTimeMillis(createDate.getTime());
            entity.setCreateDate(createDate);

            long focDiffMillis = entity.getCurrentTimeMillis() - entity.getFocTimeMillis()
                    + GConstants.getIntValue("add.diff.millis", 100);

            entity.setFocDiffMillis((int) focDiffMillis);
            Date start = new Date(entity.getBeginTime().getTime() - focDiffMillis);
            entity.setFocBeginTime(start);
            if (entity.getEndTime() != null) {

                Date end = new Date(entity.getEndTime().getTime() - focDiffMillis);
                entity.setFocEndTime(end);
            }
            // 判断数据是否已经存在
            SoundRecordingEntity soundEntity = existSound(entity.getId());
            if (soundEntity == null) {

                /*
                 * if (StringUtils.isNoneBlank(entity.getCallNo()) &&
                 * StringUtils.isNoneBlank(entity.getAcceptNo())) {//
                 * 呼叫、接受号码不为空时
                 * 
                 * CallRecordsEntity callentity =
                 * getCallRecords(entity.getCallNo(), entity.getAcceptNo(),
                 * entity.getBeginTime());// 匹配最近通话记录
                 * 
                 * if (callentity != null) {
                 * entity.setFocBeginTime(callentity.getStartTime());
                 * entity.setFocEndTime(callentity.getEndTime());
                 * entity.setCallRecordId(callentity.getRecordId());
                 * 
                 * updateCallPhone(callentity.getId(), entity.getDownloadUrl(),
                 * id);// 将录音地址更新 if ("USER".equals(callentity.getCallType()) ||
                 * callentity.getDuration() >= 0) {
                 * updateCallRECORDS(callentity.getRecordId(),
                 * entity.getDuration(), entity.getDownloadUrl()); } else if
                 * (entity.getDuration()>=0) {// 群组会议时 if
                 * (callentity.getDuration()>=0) {
                 * updateCallRECORDS(callentity.getRecordId(),
                 * entity.getDuration(), entity.getDownloadUrl()); } else { int
                 * dur = callentity.getDuration();//
                 * Integer.parseInt(callentity.getDuration()); int newd =
                 * entity.getDuration();//
                 * Integer.parseInt(entity.getDuration()); if (newd > dur) {
                 * updateCallRECORDS(callentity.getRecordId(),
                 * entity.getDuration(), entity.getDownloadUrl()); } } } } }
                 */
                inserSoundtData(entity);// 插入
            }
        }
        return;
    }

    /**
     * 更新foc_call_records表数据
     * 
     * @author zhanglg
     * @time 2017年2月24日
     * @param recordId
     * @param duration
     * @param downloadUrl
     */

    private void updateCallRECORDS(String recordId, int duration, String downloadUrl) {
        DBHandler dBHandler = new DBHandler();
        Map<String, Object> columnMap = new TreeMap<String, Object>();
        Map<String, Object> whereMap = new TreeMap<String, Object>();

        // 字段和值绑定
        columnMap.put("duration", duration);
        columnMap.put("download_url", downloadUrl);
        whereMap.put("id", recordId);

        dBHandler.update(Constants.FOC_CALL_RECORDS, columnMap, whereMap);

    }

    /**
     * 更新foc_call_phone表数据
     * 
     * @author zhanglg
     * @time 2017年2月24日
     * @param id
     * @param downloadUrl
     */

    private void updateCallPhone(String id, String downloadUrl, String soundId) {
        DBHandler dBHandler = new DBHandler();
        Map<String, Object> columnMap = new TreeMap<String, Object>();
        Map<String, Object> whereMap = new TreeMap<String, Object>();

        // 字段和值绑定
        columnMap.put("center_records_id", soundId);
        columnMap.put("download_url", downloadUrl);
        whereMap.put("id", id);

        dBHandler.update(Constants.FOC_CALL_PHONES, columnMap, whereMap);

    }

    /**
     * 得到最近的通话记录
     * 
     * @author zhanglg
     * @time 2017年2月24日
     * @param start
     * @param end
     * @param flag
     * @return
     */

    public List<CallRecordsEntity> getCallRecords(String start, String end, String flag) {
        ResultSetHandler<List<CallRecordsEntity>> handler = new BeanListHandler<CallRecordsEntity>(
                CallRecordsEntity.class);
        String url = Constants.FOC_CALL_RECORDS;
        String url2 = Constants.FOC_CALL_PHONES;
        if (flag.equals(GConstants.NO)) {
            url = Constants.FOC_SOUND_RECORDS;
            url2 = Constants.FOC_SOUND_PHONES;
        }
        StringBuilder query = new StringBuilder();
        query.append(
                "SELECT t.id,s.id AS recordId ,call_type AS callType,duration,s.create_by AS callId,t.user_id AS acceptId, ");
        query.append(
                "s.start_time AS startTime,s.end_time AS endTime,center_records_id AS centerRecordsId,t.phone AS acceptNo,s.create_phone AS callNo");
        query.append(" FROM ").append(url).append(" s ");
        query.append("LEFT JOIN ").append(url2).append(" t ON s.id=t.record_id ");
        query.append("WHERE s.start_time BETWEEN ? and ? ");
        // query.append(" AND (center_records_id is null or s.download_url is
        // null) ");

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date beginTime;
            try {
                beginTime = sdf.parse(start);
                Date endTime = sdf.parse(end);
                Date lowerTime = new Date(beginTime.getTime() - 10 * 60 * 1000);// 时间漂移范围下限
                Date upTime = new Date(endTime.getTime() + 10 * 60 * 1000);// 时间漂移范围上限
                List<CallRecordsEntity> list = run.query(query.toString(), handler, lowerTime, upTime);
                return list;
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 查询最大的id
     * 
     * @author jinjb
     * @time 2017年2月24日
     * @return
     */

    public Long getSoundMaxId(final Long defaultId) {
        
        try {
            StringBuilder query = new StringBuilder();
//            query.append("SELECT id FROM foc_soundmax_id");
            query.append("SELECT MAX(`id`) AS id FROM `dbocdr` ");
            Long maxId = run.query(query.toString(), new ResultSetHandler<Long>(){

                @Override
                public Long handle(ResultSet paramResultSet) throws SQLException {
                    // TODO Auto-generated method stub
                    if(paramResultSet == null || paramResultSet.next() == false)
                        return null;
                    return paramResultSet.getLong(1);
                }
            });
            
            return maxId == null ? defaultId : maxId;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return defaultId;
    }
    /**
     * 更新foc_soundmax_id表数据
     * 
     * @author jin
     * @time 2017年2月24日
     * @param recordId
     * @param duration
     * @param downloadUrl
     */

//    public void updateSoundmaxId(Long newMaxId) {
//        DBHandler dBHandler = new DBHandler();
//        Map<String, Object> columnMap = new TreeMap<String, Object>();
//        Map<String, Object> whereMap = new TreeMap<String, Object>();
//
//        // 字段和值绑定
//        columnMap.put("id", newMaxId);
////        whereMap.put("id", oldMaxId);
//
//        dBHandler.update("foc_soundmax_id", columnMap, whereMap);
//
//    }
    /**
     * 插入foc_sound_records数据
     * 
     * @author zhanglg
     * @time 2017年2月24日
     * @param entity
     */

    private void inserSoundtData(SoundRecordingEntity entity) {

        List<Map<String, Object>> columnMapList = new ArrayList<Map<String, Object>>();
        Map<String, Object> columnMap = new TreeMap<String, Object>();
        columnMap.put("id", entity.getId());
        columnMap.put("download_size", 0);
        columnMap.put("call_no", entity.getCallNo());
        // columnMap.put("call_name", entity.getSize());
        // columnMap.put("call_user_no", entity.getSize());
        columnMap.put("accept_no", entity.getAcceptNo());
        // columnMap.put("accept_name", entity.getSize());
        // columnMap.put("accept_user_no", entity.getAcceptUserNo());
        columnMap.put("begin_time", entity.getBeginTime());
        columnMap.put("end_time", entity.getEndTime());
        columnMap.put("duration", entity.getDuration());
        columnMap.put("result", entity.getResult());
        columnMap.put("download_url", entity.getDownloadUrl());
        columnMap.put("foc_begin_time", entity.getFocBeginTime());
        columnMap.put("foc_end_time", entity.getFocEndTime());
        columnMap.put("call_record_id", entity.getCallRecordId());
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // final String create = sdf.format(new Date());

        columnMap.put("current", entity.getCurrent());
        columnMap.put("current_time_millis", entity.getCurrentTimeMillis());
        columnMap.put("channel_type", "CRON");

        columnMap.put("foc_time_millis", entity.getFocTimeMillis());
        columnMap.put("foc_diff_millis", entity.getFocDiffMillis());

        columnMap.put("create_date", entity.getCreateDate());

        columnMapList.add(columnMap);

        /**
         * 单条插入，保证一条语句插入报错，还能往下执行
         */
        DBHandler dBHandler = new DBHandler();
        dBHandler.batchInsert(Constants.FOC_CALLCENTER_RECORDS, columnMapList);
    }

    /**
     * 判断是否已经保存本条数据
     * 
     * @author zhanglg
     * @time 2017年2月24日
     * @param id
     * @return
     */

    private SoundRecordingEntity existSound(String id) {

        ResultSetHandler<List<SoundRecordingEntity>> handler = new BeanListHandler<SoundRecordingEntity>(
                SoundRecordingEntity.class);
        String query = "SELECT * FROM foc_callcenter_records WHERE id =? ";
        try {
            List<SoundRecordingEntity> list = run.query(query, handler, id);
            if (list != null && list.size() > 0) {
                return list.get(0);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 
     * @author zhanglg
     * @time 2017年2月27日
     * @param result
     * @param end
     * @param start
     */

    public void insertDataBak(JSONObject result, String start, String end, String flag) {
        List<SoundRecordingEntity> list = getList(result);
        List<CallRecordsEntity> ls = getCallRecords(start, end, flag);
        for (SoundRecordingEntity entity : list) {
            entity.setDownloadUrl(targetPath(entity.getDownloadUrl()));
            String content = entity.getCallNo() + entity.getAcceptNo() + entity.getBeginTime() + entity.getEndTime()
            + entity.getDuration() + entity.getDownloadUrl();
            // 根据MD5生成主键
            String id = DigestUtils.md5Hex(content);
            entity.setId(id);
    
            insertData(entity);
            updateRecordsAndPhone(entity, ls, flag);
        }

    }
    /**
     * 
     * @author zhanglg
     * @time 2017年2月27日
     * @param list
     * @param end
     * @param start
     * @param flag
     */

    public void insertData(List<SoundRecordingEntity> list, String start, String end, String flag) {
        List<CallRecordsEntity> ls = getCallRecords(start, end, flag);
        for (SoundRecordingEntity entity : list) {
            entity.setDownloadUrl(targetPath(entity.getDownloadUrl()));
            String content = entity.getCallNo() + entity.getAcceptNo() + entity.getBeginTime() + entity.getEndTime()
            + entity.getDuration() + entity.getDownloadUrl();
            // 根据MD5生成主键
            String id = DigestUtils.md5Hex(content);
            entity.setId(id);
    
            insertData(entity);
            updateRecordsAndPhone(entity, ls, flag);
        }

    }
    /**
     * 更新
     * 
     * @author zhanglg
     * @time 2017年3月13日
     * @param entity
     * @param ls
     */

    public void updateRecordsAndPhone(SoundRecordingEntity entity, List<CallRecordsEntity> ls, String flag) {
        /*
         * UserInfo callUser = new UserInfo();
         * if(StringUtils.isNoneBlank(entity.getCallNo())){ callUser =
         * GetIdByPhone(entity.getCallNo());
         * 
         * if(callUser ==null){ callUser = new UserInfo(); callUser.setId("1");
         * callUser.setName(entity.getCallNo()); }
         * 
         * }else{ return; }
         * 
         * String callId = callUser.getId()==null?"1":callUser.getId(); UserInfo
         * acceptUser = new UserInfo();
         * if(StringUtils.isNoneBlank(entity.getAcceptNo())){ acceptUser =
         * GetIdByPhone(entity.getAcceptNo()); if(acceptUser ==null){ acceptUser
         * = new UserInfo(); acceptUser.setId(""); acceptUser.setName(""); }
         * }else{ return; }
         * 
         * String acceptId = acceptUser.getId();
         * if(StringUtils.isBlank(acceptId)){ acceptId=""; }
         */
        if (StringUtils.isBlank(entity.getCallNo()) || StringUtils.isBlank(entity.getAcceptNo())) {
            return;
        }

        if (ls != null && ls.size() > 0) {
            for (CallRecordsEntity e : ls) {
                try {
                    // 已经保存则跳过
                    if (StringUtils.isNoneBlank(e.getCenterRecordsId())
                            && e.getCenterRecordsId().equals(entity.getId())) {
                        return;
                    }
                    if (GConstants.YES.equals(flag)) {
                        if (entity.getCallNo().equals(e.getCallNo()) && entity.getAcceptNo().equals(e.getAcceptNo())) {
                            Date lowerTime = new Date(entity.getBeginTime().getTime() - 60 * 1000);// 时间漂移范围下限
                            Date upperTime = new Date(entity.getBeginTime().getTime() + 60 * 1000);// 时间漂移范围上限
                            if (lowerTime.before(e.getStartTime()) && upperTime.after(e.getStartTime())) {
                                updateCallPhone(e.getId(), entity.getDownloadUrl(), entity.getId());// 将录音地址更新
                                if ("USER".equals(e.getCallType()) || e.getDuration() >= 0) {
                                    updateCallRECORDS(e.getRecordId(), entity.getDuration(), entity.getDownloadUrl());
                                } else if (entity.getDuration() >= 0) {// 群组会议时
                                    if (e.getDuration() >= 0) {
                                        updateCallRECORDS(e.getRecordId(), entity.getDuration(),
                                                entity.getDownloadUrl());
                                        return;
                                    } else {
                                        int dur = e.getDuration();// Integer.parseInt(callentity.getDuration());
                                        int newd = entity.getDuration();// Integer.parseInt(entity.getDuration());
                                        if (newd > dur) {
                                            updateCallRECORDS(e.getRecordId(), entity.getDuration(),
                                                    entity.getDownloadUrl());
                                            return;
                                        }
                                    }
                                }
//                                return;
                            }
                        }
                    }
                } catch (Exception ex) {
                    
                    ex.printStackTrace();
                }
            }
//            insert(entity, flag);
        } 
//        else {
//            insert(entity, flag);
//        }
        insert(entity, flag);
    }

    public void insert(SoundRecordingEntity entity, String flag) {
    	
        UserInfo callUser = new UserInfo();
        if (StringUtils.isNoneBlank(entity.getCallNo())) {
            callUser = GetIdByPhone(entity.getCallNo());

            if (callUser == null) {
                callUser = new UserInfo();
                callUser.setId("1");
                callUser.setName(entity.getCallNo());
            }

        } else {
            return;
        }
        UserInfo acceptUser = new UserInfo();
        if (StringUtils.isNoneBlank(entity.getAcceptNo())) {
            acceptUser = GetIdByPhone(entity.getAcceptNo());
            if (acceptUser == null) {
                acceptUser = new UserInfo();
                acceptUser.setId("1");
                acceptUser.setName(entity.getAcceptNo());
            }
        } else {
            return;
        }

        String acceptId = acceptUser.getId();
        if (StringUtils.isBlank(acceptId)) {
            acceptId = "";
        }
        String recordId = IdWorker.getNextId();
        insertCallRECORDS(entity, callUser, recordId, flag);
        insertCallPHONE(entity, acceptUser, recordId, flag, callUser.getName());

        // 查询是否有重复记录（create_name,username,start_time）
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("SELECT id,\n" +
                             "\t     create_by,\n" +
                             "\t     create_name,\n" +
                             "\t     create_phone,\n" +
                             "\t     call_type,\n" +
                             "\t     end_status,\n" +
                             "\t     user_count,\n" +
                             "\t     start_time,\n" +
                             "\t     end_time\n");
        String tableName = Constants.FOC_CALL_RECORDS;
        if (GConstants.NO.equals(flag)) {
            tableName = Constants.FOC_SOUND_RECORDS;
        }
        stringBuilder.append("FROM ").append(tableName).append("\n")
                .append("WHERE end_status != 'INIT'\n")
                .append("AND create_name = '").append(callUser.getName()).append("'\n")
                .append("AND start_time <= '").append(entity.getEndTime()).append("'\n")
                .append("AND id != '").append(recordId).append("'\n")
                .append("ORDER BY start_time DESC");
        List<Map<String, Object>> soundRecordsList = DBHelper.fetch("foc", stringBuilder.toString());
        // 过滤掉了id，所以查出的数据就是重复的
        if (soundRecordsList != null && soundRecordsList.size() > 0) {
            for (Map<String, Object> map : soundRecordsList) {
                // 将重复数据复制到备份表，并将原表数据删除

            }
        }
    }

    public UserInfo GetIdByPhone(String phone) {
        Map<String, Object> contents = new HashMap<String, Object>();
        contents.put("phoneNumer", phone);
        
        List<CallPhoneInfoListEntity> list = Util.arrayApi("/api/call/findPhoneInfo", contents, CallPhoneInfoListEntity.class);
        if (list == null || list.size() == 0) {
            return null;
        }
        CallPhoneInfoListEntity info = list.get(0);
        if(info != null && StringUtils.isNotEmpty(info.getName())){
            if(StringUtils.isEmpty(info.getUserId())){
            	info.setUserId("1");
            }
            UserInfo userInfo = new UserInfo();
            userInfo.setId(info.getUserId());
            userInfo.setName(info.getName());
            return userInfo;
        }
        return null;
        /*
        ResultSetHandler<List<UserInfo>> handler = new BeanListHandler<UserInfo>(UserInfo.class);
        String mobileNubmer0 = "0" + phone;
        String mobileNubmer00 = "00" + phone;
        StringBuilder query = new StringBuilder();
        query.append("SELECT a.id,a.name ");
        query.append("FROM sys_user a  ");
        query.append(" WHERE a.phone=?");
        query.append(" OR a.phone_number=?");
        query.append(" OR a.huawei_num=?");
        query.append(" OR a.mobile=?");
        query.append(" OR a.mobile_nubmer=?");
        query.append(" OR a.mobile_nubmer=?");
        query.append(" UNION ");
        query.append(" SELECT s.id,seat_name AS name ");
        query.append(" FROM foc_seats s ");
        query.append("  WHERE s.huawei_num =?");
        query.append(" OR s.seat_phone_number =?");
        query.append(" OR s.seat_phone =?");
        query.append(" OR s.seat_phone=?");
        try {
            List<UserInfo> list = run.query(query.toString(), handler, phone, phone, phone, phone, mobileNubmer0,
                    mobileNubmer00, phone, phone, mobileNubmer0, mobileNubmer00);

            if (list != null && list.size() > 0)
                return list.get(0);
            else
                return null;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
        */
    }

    private void insertCallRECORDS(SoundRecordingEntity entity, UserInfo callUser, String recordId, String flag) {

        List<Map<String, Object>> columnMapList = new ArrayList<Map<String, Object>>();
        Map<String, Object> columnMap = new TreeMap<String, Object>();
        // 字段和值绑定

        columnMap.put("id", recordId);
        columnMap.put("app_code", "30011");
        columnMap.put("platform", "JAVA");
        columnMap.put("version_name", "1.0");
        columnMap.put("channel_type", "ANKE");
        columnMap.put("call_type", "USER");
        columnMap.put("user_count", "2");
        columnMap.put("end_status", "FAILD");
        if ("0".equals(entity.getResult())) {
            columnMap.put("end_status", "SUCCESS");
        } else if("117".equals(entity.getResult())){
            columnMap.put("end_status", "FAILD");
        }else if("118".equals(entity.getResult())){
            columnMap.put("end_status", "INIT");
        }
        columnMap.put("create_by", callUser.getId());
        columnMap.put("create_name", callUser.getName());
        columnMap.put("create_phone", entity.getCallNo());
        columnMap.put("phone_type", getPhoneType(entity.getCallNo()));
        columnMap.put("start_time", entity.getBeginTime());
        columnMap.put("end_time", entity.getEndTime());
        columnMap.put("download_url", entity.getDownloadUrl());
        columnMap.put("duration", entity.getDuration());

        columnMapList.add(columnMap);

        /**
         * 单条插入，保证一条语句插入报错，还能往下执行
         */
        DBHandler dBHandler = new DBHandler();
        String url = Constants.FOC_CALL_RECORDS;
        if (flag.equals(GConstants.NO)) {
            url = Constants.FOC_SOUND_RECORDS;
        }
        dBHandler.batchInsert(url, columnMapList);

    }

    private void insertCallPHONE(SoundRecordingEntity entity, UserInfo acceptUser, String recordId, String flag,
            String name) {

        List<Map<String, Object>> columnMapList = new ArrayList<Map<String, Object>>();
        Map<String, Object> columnMap = new TreeMap<String, Object>();
        // 字段和值绑定

        columnMap.put("id", IdWorker.getNextId());
        columnMap.put("record_id", recordId);
        columnMap.put("title", name);

        columnMap.put("user_id", acceptUser.getId());
        columnMap.put("username", acceptUser.getName());
        columnMap.put("phone", entity.getAcceptNo());
        columnMap.put("phone_type", getPhoneType(entity.getAcceptNo()));
        columnMap.put("flow", "CALLED");

        columnMap.put("download_url", entity.getDownloadUrl());
        columnMap.put("center_records_id", entity.getId());

        columnMapList.add(columnMap);

        /**
         * 单条插入，保证一条语句插入报错，还能往下执行
         */
        DBHandler dBHandler = new DBHandler();
        String url = Constants.FOC_CALL_PHONES;
        if (flag.equals(GConstants.NO)) {
            url = Constants.FOC_SOUND_PHONES;
        }
        dBHandler.batchInsert(url, columnMapList);

    }

    private String getPhoneType(String phone) {
        // 未知
        if (StringUtils.isEmpty(phone)) {
            return "UNKNOWN";
        }
        // 手机号
        if (phone.startsWith("1") && phone.length() == 11) {
            return "MOBILE";
        }
        // 手机号
        if (phone.startsWith("01") && phone.length() == 12) {
            return "MOBILE";
        }
        // 手机号
        if (phone.startsWith("001") && phone.length() == 13) {
            return "MOBILE";
        }
        // 华为短号
        if (phone.startsWith("6") && phone.length() == 4) {
            return "HWNUBMER";
        }
        return "PHONE";// 座机
    }
    private String targetPath(String downloadUrl){
        File downloadFile = new File(downloadUrl);
        String path=null;
        // 根据MD5生成主键
        String md5 = DigestUtils.md5Hex(downloadUrl)+".mp3";
        String baseDatePath = PathFormatUtils.parse(PATH_FORMAt);
        String childPath=baseDatePath+GConstants.FS+"MP3"+GConstants.FS;
        File baseUploadDir = new File(GConstants.FILE_UPLOAD_DIR, childPath);
        if(!baseUploadDir.exists()){// 如果文件夹不存在则创建
            baseUploadDir.mkdirs();
        }
        path = baseUploadDir.getPath()+md5;
        try {
            WavToMp3.execute(downloadFile, path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return GConstants.FILE_PREFIX_URL+childPath+md5;
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    public void inserSoundtDataFromDb(SoundRecordingEntity entity) {

        Date createDate = new Date(System.currentTimeMillis());
        entity.setCurrent(createDate);
        entity.setCurrentTimeMillis(createDate.getTime());

        entity.setFocTimeMillis(createDate.getTime());
        entity.setCreateDate(createDate);
        
        List<Map<String, Object>> columnMapList = new ArrayList<Map<String, Object>>();
        Map<String, Object> columnMap = new TreeMap<String, Object>();
        columnMap.put("id", entity.getId());
        columnMap.put("download_size", entity.getDownloadSize());
        columnMap.put("call_no", entity.getCallNo());
        // columnMap.put("call_name", entity.getSize());
        // columnMap.put("call_user_no", entity.getSize());
        columnMap.put("accept_no", entity.getAcceptNo());
        // columnMap.put("accept_name", entity.getSize());
        // columnMap.put("accept_user_no", entity.getAcceptUserNo());
        columnMap.put("begin_time", entity.getBeginTime());
        columnMap.put("end_time", entity.getEndTime());
        columnMap.put("duration", entity.getDuration());
        columnMap.put("result", entity.getResult());
        columnMap.put("download_url", entity.getDownloadUrl());
        columnMap.put("foc_begin_time", entity.getBeginTime());
        columnMap.put("foc_end_time", entity.getEndTime());
        columnMap.put("call_record_id", entity.getId());
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // final String create = sdf.format(new Date());

        columnMap.put("current", entity.getCurrent());
        columnMap.put("current_time_millis", entity.getCurrentTimeMillis());
        columnMap.put("channel_type", "CRON");

        columnMap.put("foc_time_millis", entity.getBeginTime().getTime());
        columnMap.put("foc_diff_millis", 0);

        columnMap.put("create_date", entity.getCreateDate());

        columnMapList.add(columnMap);

        /**
         * 单条插入，保证一条语句插入报错，还能往下执行
         */
        DBHandler dBHandler = new DBHandler();
        dBHandler.batchInsert(Constants.FOC_CALLSOUND_RECORDS, columnMapList);
    }
}

