package com.ruixuan.salesLeads.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import com.ruixuan.common.core.domain.ResultResponse;
import com.ruixuan.common.core.page.TableDataInfo;
import com.ruixuan.common.core.redis.RedisCache;
import com.ruixuan.common.utils.DateUtils;
import com.ruixuan.common.utils.PageUtils;
import com.ruixuan.common.utils.StringUtils;
import com.ruixuan.common.utils.file.FileTypeUtils;
import com.ruixuan.common.utils.http.HttpUtil;
import com.ruixuan.salesLeads.constant.RobotConstant;
import com.ruixuan.salesLeads.listener.ImportExcelListener;
import com.ruixuan.salesLeads.mapper.*;
import com.ruixuan.salesLeads.pojo.*;
import com.ruixuan.salesLeads.pojo.vo.SaleRecordVo;
import com.ruixuan.salesLeads.pojo.vo.SaleTaskInfoVo;
import com.ruixuan.salesLeads.service.ISaleClueInfoService;
import com.ruixuan.salesLeads.service.ITelephoneRobotService;
import com.ruixuan.salesLeads.utils.CsvImportUtil;
import com.ruixuan.system.domain.SysAreaInfo;
import com.ruixuan.system.domain.SysIndustryInfo;
import com.ruixuan.system.mapper.SysAreaInfoMapper;
import com.ruixuan.system.mapper.SysIndustryInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * ***************************************************
 *
 * @Auther: zianY
 * @Descipion: 外呼机器人api
 * @CreateDate: 2022-07-01
 * ****************************************************
 */
@Service
@Slf4j
public class TelephoneRobotServiceImpl implements ITelephoneRobotService {

    @Value("${telephoneRobot.appKey}")
    private String rebotAppkey;
    @Value("${telephoneRobot.secret}")
    private String rebotSecret;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SaleClueInfoMapper saleClueInfoMapper;

    @Autowired
    private SaleClueCallRecordMapper saleClueCallRecordMapper;

    @Autowired
    private SaleClueCallResultMapper saleClueCallResultMapper;


    /**
     *
     * @description: 外呼机器人获取token
     *
     * @param
     * @return: com.ruixuan.common.core.domain.ResultResponse
     * @author: zianY
     */
    @Override
    public JSONObject getTelephoneRobotToken(){

        JSONObject tokenObj = redisCache.getCacheObject("salesLeads:robotToken:str");
        if (!StringUtils.isEmpty(tokenObj)){
            log.info("外呼机器人获取redis中的token信息----->>>{}",tokenObj);
            return tokenObj;
        }
        Map<String,Object> params = new HashMap<>();
        params.put("appKey",rebotAppkey);
        params.put("secret",rebotSecret);
        /*Map<String,String> headers = new HashMap<>();
        params.put("Auth-Token",);
*/
        String content = HttpUtil.httpPostRequest(RobotConstant.REFRESH_TOKEN,params,null);
        JSONObject jsonObject = JSONObject.parseObject(content);
        redisCache.setCacheObject("salesLeads:robotToken:str",jsonObject,2, TimeUnit.HOURS);
        log.info("外呼机器人获取token信息----->>>{}",jsonObject);
        return jsonObject;
    }





    /**
     *
     * @description: 外呼机器人-导入号码-master
     *
     * @param sellerIds
     * @param userId
     * @return: com.ruixuan.common.core.domain.ResultResponse
     * @author: zianY
     */
    @Override
    @Transactional
    public ResultResponse importRobotTelephone(List<Long> sellerIds,String userId) throws Exception{
        Map<String,String> headers = new HashMap<>();
        Map<String,Object> result = new HashMap<>();
        //日期8位数 自增
        String flowCode = redisCache.getFlowCode();
        log.info("task------>>>>{}",flowCode);
        result.put("taskId",Integer.valueOf(flowCode));
        result.put("batchId",Integer.valueOf(flowCode));
        result.put("callBackUrl",RobotConstant.CALL_BACK_URL);
        result.put("canCover",true);
        List customerList = new ArrayList();
        for (Long sellerId : sellerIds) {
            //SaleRecordVo saleInfo = saleClueInfoMapper.selectSaleClueInfoBySellerId(sellerId);
            //销售线索id查询
            SaleRecordVo saleInfo = saleClueInfoMapper.selectSaleClueInfoById(sellerId.intValue());
            if (saleInfo == null){
                //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                log.info("销售线索查询为空或已导入过联系方式---》》》线索id---{}",sellerId);
                continue;
            }
            Map<String,Object> param = new HashMap<>();
            param.put("id",saleInfo.getId());
            param.put("name",saleInfo.getSellerId());
            param.put("companyName",saleInfo.getSellerName());
            param.put("phone",saleInfo.getTelephone());
            param.put("website","");

            customerList.add(param);
        }

        if (customerList.isEmpty()){
            return ResultResponse.error("销售线索查询为空或已导入。");
        }

        result.put("customerList",customerList);
        //headers.put("Auth-Token","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJndW95YW5saW5nIiwiZXhwIjoxNjU4MTMyMjEyfQ.OyhpastRRzBxAlSc8JOfdxO3rK3NG592U3Qlh752xDQ");
        JSONObject tokenObj = redisCache.getCacheObject("salesLeads:robotToken:str");
        if (!StringUtils.isEmpty(tokenObj)){
            log.info("导入时获取redis中的token信息----->>>{}",tokenObj);

        }else {
            tokenObj = getTelephoneRobotToken();
            log.info("导入时redis中的token信息已失效,重新获取token----->>>{}");
        }
        headers.put("Auth-Token",JSONObject.parseObject(tokenObj.getString("data")).getString("token"));
        String content = HttpUtil.httpPostRequest(RobotConstant.CUSTOMER_IMPORT,result,headers);
        log.info("调用第三方接口------入参---{}-----返回信息---》》》》{}",result,content);
        JSONObject jsonObject = JSONObject.parseObject(content);
        if (!"0".equals(jsonObject.getString("code"))){
            log.info("导入数据接口异常======>>>>>{}"+jsonObject);
            return ResultResponse.error("访问过于频繁，请稍后再试。");
        }

        Thread.sleep(500);
        //更新最新的记录 用户信息
        //1分钟只能调取导入接口一次 所以可以保证最新的记录就是刚通过回调接口回来的数据信息
        saleClueCallRecordMapper.updateCallRecordUser(userId,flowCode);

        log.info("------更新操作用户-------");
        //查询 最新的记录
        SaleClueCallRecordPojo recordPojo = saleClueCallRecordMapper.selectCallRecordInfo();
        JSONObject jsonContent = JSONObject.parseObject(recordPojo.getContent());
        JSONArray success = jsonContent.getJSONArray("success");
        recordPojo.setSuccessList(success);
        JSONArray error = jsonContent.getJSONArray("error");
        recordPojo.setErrorList(error);
        return ResultResponse.successMsg("本次导入记录，成功"+ (StringUtils.isEmpty(success) ? 0 : success.size()) + "条；失败"+
        (StringUtils.isEmpty(error) ? 0 : error.size())+"条。",recordPojo);


    }



    /**
     *
     * @description: 外呼记录查询
     *
     * @param
     * @return: com.ruixuan.common.core.domain.ResultResponse
     * @author: zianY
     */
    @Override
    public ResultResponse getRobotTelephoneRecordList(){

        PageUtils.startPage();
        //查询导入记录
        List<SaleClueCallRecordPojo> callRecordList = saleClueCallRecordMapper.getSaleClueCallRecordInfo();
        for (SaleClueCallRecordPojo recordPojo : callRecordList) {
            String record = recordPojo.getContent();
            JSONObject recordJson = JSONObject.parseObject(record);
            recordPojo.setSuccessList(recordJson.getJSONArray("success"));
            recordPojo.setErrorList(recordJson.getJSONArray("error"));
        }
        return ResultResponse.successMsg("查询导入记录成功。",new TableDataInfo(callRecordList,new Long(new PageInfo(callRecordList).getTotal()).intValue()));
    }

    /**
     *
     * @description: 通话记录
     *
     * @param createTime 创建时间
     * @param state 销售线索状态 1-未开始 2-进行中 3-已结束
     * @return: com.ruixuan.common.core.domain.ResultResponse
     * @author: zianY
     */
    @Override
    public ResultResponse getRobotTelephoneResultList(String createTime,Integer state){

        PageUtils.startPage();
        //查询导入记录
        List<SaleClueCallResultPojo> callResultList = saleClueCallResultMapper.getSaleClueCallResultList(createTime,state);

        for (SaleClueCallResultPojo resultPojo : callResultList) {
            List<Map> contentList = JSONObject.parseArray(resultPojo.getContent(),Map.class);
            Map<String,List<Map>> map = contentList.stream().collect(Collectors.groupingBy(m -> m.get("speaker").toString()));
            resultPojo.setSpeakerContent(map == null ? null : map.get("Contact"));
            resultPojo.setRobotContent(map == null ? null : map.get("Robot"));
        }


        return ResultResponse.successMsg("查询通话记录成功。",new TableDataInfo(callResultList,new Long(new PageInfo(callResultList).getTotal()).intValue()));
    }



}
