package com.gree.mall.manager.logic.unicom;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.druid.util.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.common.CallRecordOrderVo;
import com.gree.mall.manager.bean.common.CallRecordVo;
import com.gree.mall.manager.bean.workorder.IncreVO;
import com.gree.mall.manager.commonmapper.CommonMapper;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.constant.SysDictConstant;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.common.SysDictLogic;
import com.gree.mall.manager.plus.entity.AdminUser;
import com.gree.mall.manager.plus.entity.CallRecord;
import com.gree.mall.manager.plus.entity.CallSendRecord;
import com.gree.mall.manager.plus.entity.PgOrderBase;
import com.gree.mall.manager.plus.service.AdminUserService;
import com.gree.mall.manager.plus.service.CallRecordService;
import com.gree.mall.manager.plus.service.CallSendRecordService;
import com.gree.mall.manager.plus.service.PgOrderBaseService;
import com.gree.mall.manager.utils.RedisUtil;
import com.gree.mall.manager.utils.oss.OSSUtil;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 联通外呼，隐私号对接
 */
@Slf4j
@Service
public class UnicomLogic {

    //private final static String BASE_URL = "https://a5.7x24cc.com";

    @Value("${unicome.yunh.baseurl}")
    private String baseUrl;
    @Value("${unicome.yunh.account}")
    private String ACCOUNT;
    @Value("${unicome.yunh.secret}")
    private String SECRET;
    @Value("${unicome.yunh.appid}")
    private String APPID;

    @Autowired
    CommonLogic commonLogic;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    OSSUtil ossUtil;
    @Autowired
    SysDictLogic sysDictLogic;
    @Autowired
    AdminUserService adminUserService;
    @Autowired
    CallRecordService callRecordService;
    @Resource
    PgOrderBaseService pgOrderBaseService;

    @Resource
    CallSendRecordService callSendRecordService;
    @Autowired
    CommonMapper commonMapper;








    /**
     * 联通云呼请求token
     * @return
     */
    public  String getAccessToken(){
        String tokenKey = Constant.RedisPrefix.TOKEN_UNICOME_YUNH;
        if(redisUtil.get(tokenKey) != null){
            return (String)redisUtil.get(tokenKey);
        }
//        String ACCOUNT = "N000000015221";
//        String APPID = "69jpgmwqxyhtcsor";
//        String SECRET = "fe443fc0264411ec80212baafe602ea7";
        String s = HttpUtil.get(baseUrl + "/accessToken?account=" + ACCOUNT + "&appid=" + APPID + "&secret=" + SECRET);
        String accessToken = JSONObject.parseObject(s).getString("accessToken");
        log.info("【获取联通云呼token】:{}",accessToken);
        redisUtil.set(tokenKey,accessToken,9 * 60);
        return accessToken;
    }


    /**
     * 保存云呼配置
     */
    public void saveConfig(String unicomIntegratedId,String unicomIntegratedType){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        adminUser.setUnicomIntegratedId(unicomIntegratedId);
        adminUser.setUnicomIntegratedType(unicomIntegratedType);
        adminUser.updateById();
    }

    /**
     * 拨打云呼
     * @param phone
     */
    public void commonlnte(String phone,String orderBaseId,String flag){
        String token = getAccessToken();

        AdminUserCom adminUser = commonLogic.getAdminUser();
        AdminUser noCacheAdminUser = adminUserService.getById(adminUser.getAdminUserId());
        String integratedid = noCacheAdminUser.getUnicomIntegratedId();

        if(StringUtils.isEmpty(integratedid))
            throw new RemoteServiceException("检测到您暂未绑定外呼帐号，请右键点击【拨打】进行设置");

        //自定义业务参数，通话记录可以回传 例如    ExternalData = main:0001 推送url的后面就会带上参数 &main=0001
        String externalData = "orderBaseId:"+orderBaseId+",msgerName:"+adminUser.getNickName();
        String url = baseUrl + "/commonInte?flag=104&account="
                + ACCOUNT + "&phonenum=" + phone + "&integratedid=" + integratedid + "&accessToken=" + token
                +"&ExternalData="+externalData;
        log.info("【拨打外呼】request url:{}",url);
        String s = HttpUtil.get(url);

        //拨打记录
        String liucheng = StringUtils.equals("A",flag)?"回访":"";
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderBaseId);
        CallSendRecord callSendRecord = new CallSendRecord();
        callSendRecord.setName(pgOrderBase.getOrderTypeText()+"-"+liucheng);
        callSendRecord.setOrderBaseId(orderBaseId);
        callSendRecord.setWebsitId(pgOrderBase.getWebsitId());
        callSendRecord.setWebsitName(pgOrderBase.getWebsitName());
        callSendRecord.setUserName(pgOrderBase.getUserName());
        callSendRecord.setUserMobile(pgOrderBase.getUserMobile());
        callSendRecord.setStatus(s.equals("200")?"回访成功":"回访失败");
        callSendRecord.setTag("");
        callSendRecord.insert();

        if(!s.equals("200")){
            if (s.equals("301"))
                throw new RemoteServiceException("拨打云呼失败错误码【"+s+"】,参数缺失");

            if (s.equals("303"))
                throw new RemoteServiceException("拨打云呼失败错误码【"+s+"】,电话错误");

            if (s.equals("309"))
                throw new RemoteServiceException("拨打云呼失败错误码【"+s+"】,token过期");

            if (s.equals("401"))
                throw new RemoteServiceException("拨打云呼失败错误码【"+s+"】,账户不存在");

            if (s.equals("402"))
                throw new RemoteServiceException("拨打云呼失败错误码【"+s+"】,参数错误");

            if (s.equals("404"))
                throw new RemoteServiceException("拨打云呼失败错误码【"+s+"】,登录号错误");

            if (s.equals("405"))
                throw new RemoteServiceException("拨打云呼失败错误码【"+s+"】,key不存在");

            if (s.equals("407"))
                throw new RemoteServiceException("拨打云呼失败错误码【"+s+"】,坐席未登录");


            if (s.equals("408"))
                throw new RemoteServiceException("拨打云呼失败错误码【"+s+"】,坐席忙碌");

            if (s.equals("409"))
                throw new RemoteServiceException("拨打云呼失败错误码【"+s+"】,时间错误");


            if (s.equals("410"))
                throw new RemoteServiceException("拨打云呼失败错误码【"+s+"】,外呼防骚扰上限，号码为限制外呼好卖");

            if (s.equals("412"))
                throw new RemoteServiceException("拨打云呼失败错误码【"+s+"】,坐席没有绑定sip号");

            if (s.equals("603"))
                throw new RemoteServiceException("拨打云呼失败错误码【"+s+"】,flag参数错误");

        }
    }


    /**
     * 获取云呼通话记录
     */
    public void syncMsgRecord(Date startTime,Date endTime){

//        String ACCOUNT = "N000000015221";
//        String APPID = "69jpgmwqxyhtcsor";
//        String SECRET = "fe443fc0264411ec80212baafe602ea7";
        if(startTime == null || endTime == null)
            return;
        String sTime = DateUtil.formatDateTime(startTime);
        String eTime = DateUtil.formatDateTime(endTime);

        String token = getAccessToken();
        String s = HttpUtil.get(baseUrl + "/commonInte?flag=1000&accessToken=" + token + "&account=" + ACCOUNT + "&limit=1000&startTime="+sTime+"&endTime="+eTime);
        log.info("【同步外呼通话记录】response:{}",s);
        Integer result = JSONObject.parseObject(s).getInteger("result");
        if(result != 0)
            return;
        List<CallRecord> callRecords = new ArrayList<>();

        JSONArray data = JSONObject.parseObject(s).getJSONArray("data");
        for(Object o : data){
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(o));

            String callSheetID = jsonObject.getString("CallSheetID");
            String callID = jsonObject.getString("CallID");
            //String callType = jsonObject.getString("CallType");
            String callType = "呼出";
            String callNo = jsonObject.getString("CallNo");
            String calledNo = jsonObject.getString("CalledNo");
            Date ring = jsonObject.getDate("Ring");
            Date ringingTime = jsonObject.getDate("RingingTime");
            Date begin = jsonObject.getDate("Begin");
            Date end = jsonObject.getDate("End");
            String callTimeLength = jsonObject.getString("CallTimeLength");
            String agent = jsonObject.getString("Agent");//坐席登录名
            String agentName = jsonObject.getString("AgentName");//坐席姓名
            String exten = jsonObject.getString("Exten");//坐席工号
            String monitorFilename = jsonObject.getString("MonitorFilename");//录音文件
            JSONObject interfaceData = jsonObject.getJSONObject("InterfaceData");
            if(StringUtils.isEmpty(monitorFilename))
                continue;
            String filepath = ossUtil.getFilePath()+"/" + IdWorker.getIdStr() + UUID.randomUUID() + ".mp3";
            try {
                InputStream inputStream = commonLogic.getFileInputStreamByUrl(monitorFilename);
                boolean b = ossUtil.uploadFile(filepath, inputStream);
                if(!b)
                    log.error("【外呼通话记录附件上传oss失败】:{},ossUrl:{}",monitorFilename,filepath);
            }catch(Exception e){
                log.error("转换通话记录附件失败");
            }
            CallRecord callRecord = new CallRecord();
            callRecord.setId(callSheetID);
            callRecord.setCallType1(callType);
            callRecord.setWorkerMobile(callNo);
            callRecord.setStartTime(ring);
            callRecord.setStart(begin);
            callRecord.setEnd(end);
            callRecord.setPhone(calledNo);
            if(interfaceData != null) {
                //自定义参数
                callRecord.setOrderBaseId(interfaceData.getString("orderBaseId"));
                agentName = interfaceData.getString("msgerName");
                callRecord.setCallType2(!StringUtils.isEmpty(agentName) ? "后台呼叫客户" : "服务人员呼叫客户");
            }
            callRecord.setPromoter(agentName+",坐席工号:"+exten);
            callRecord.setCallTimestamp(StringUtils.isEmpty(callTimeLength)?0:Integer.parseInt(callTimeLength));
            if(ring != null && ringingTime != null) {
                callRecord.setRingTimestamp((int)DateUtil.betweenMs(ring,ringingTime));
            }
            String ossUrl = ossUtil.getAccessUrl()+filepath;
            callRecord.setFileUrl(ossUrl);
            if(callRecord.getCallTimestamp() > 0){
                callRecord.setStatus("回访成功");
            }else{
                callRecord.setStatus("回访失败");
            }
            callRecords.add(callRecord);

        }
        callRecordService.saveOrUpdateBatch(callRecords);

    }


    public IPage<CallRecordVo> list(Page page, ZfireParamBean zfireParam) {

        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();

        List<String> websitIds = adminUser.getAdminWebsitIds();
        //1.组装查询条件
        zfireParam = FieldUtils.supplyParam(zfireParam, CallRecordVo.class);

        IPage<CallRecordVo> callRecordVoIPage = commonMapper.list(page, zfireParam,websitIds);
        return callRecordVoIPage;
    }

    public IPage<CallRecordOrderVo> listOrder(Page page, ZfireParamBean zfireParam) {
        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();

        //1.组装查询条件
        zfireParam = FieldUtils.supplyParam(zfireParam, CallRecordOrderVo.class);

        IPage<CallRecordOrderVo> callRecordVoIPage = commonMapper.listOrder(page, zfireParam);
        return callRecordVoIPage;
    }
}
