package com.fs.app.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fs.app.annotation.Login;
import com.fs.app.utils.JwtUtils;
import com.fs.call.config.CallApiConfig;
import com.fs.call.domain.CallNotifyResponse;
import com.fs.call.domain.CallResult;
import com.fs.call.service.ICallService;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.R;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.CompanyUser;
import com.fs.company.domain.CompanyVoiceApi;
import com.fs.company.domain.CompanyVoiceLogs;
import com.fs.company.domain.CompanyVoiceMobile;
import com.fs.company.service.*;
import com.fs.system.oss.CloudStorageService;
import com.fs.system.oss.OSSFactory;
import com.fs.voice.service.IVoiceService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static com.fs.common.constant.Constants.PAGE_SIZE;

@Api("呼叫接口")
@RestController
@RequestMapping("/app/voiceApi")
public class VoiceApiController extends AppBaseController {
    private Logger logger = LoggerFactory.getLogger(VoiceApiController.class);
    @Autowired
    private IVoiceService voiceService;
    @Autowired
    private ICompanyVoiceMobileService mobileService;
    @Autowired
    private ICompanyUserService companyUserService;

    @Autowired
    private ICompanyVoiceLogsService companyVoiceLogsService;

    @Autowired
    private ICompanyVoiceApiService companyVoiceApiService;
    @Autowired
    private ICompanyVoiceService companyVoiceService;
    @Autowired
    private ICompanyVoiceMobileService companyVoiceMobileService;
    @Autowired
    JwtUtils jwtUtils;
    @Login
    @ApiOperation("呼叫")
    @GetMapping("/callMobile")
    @RepeatSubmit
    public R callMobile(HttpServletRequest request,
                        @ApiParam(required = false, name = "mobile", value = "被叫号") @RequestParam(value = "mobile", required = false) String mobile,
                        @ApiParam(required = false, name = "customerId", value = "客户ID") @RequestParam(value = "customerId", required = false) Long customerId
    ) throws Exception
    {
        String headValue = request.getHeader("APPToken");
        Claims claims = jwtUtils.getClaimByToken(headValue);
        Long userId =Long.parseLong( claims.getSubject().toString());
        CompanyUser user=companyUserService.selectCompanyUserById(userId);
        return voiceService.voiceAppCall(user.getCompanyId(),customerId,user.getUserId(), mobile);
    }

    @ApiOperation("外呼挂断")
    @GetMapping("callOffMobile")
    public R callOffMobile(@RequestParam("voiceId") Long voiceId) throws Exception
    {
        return voiceService.voiceAppCallOff(voiceId);
    }


    @Login
    @ApiOperation("获取我的呼叫记录")
    @GetMapping("/getMyCallList")
    public R getMyCallList(
            HttpServletRequest request,
            @ApiParam(required = true, name = "page", value = "页号") @RequestParam(value = "page", required = true) Integer page,
            @ApiParam(required = false, name = "customerId", value = "客户ID") @RequestParam(value = "customerId", required = false) Long customerId
    ){
        PageHelper.startPage(page, PAGE_SIZE);
        String headValue = request.getHeader("APPToken");
        Claims claims=jwtUtils.getClaimByToken(headValue);
        String userId = claims.getSubject().toString();
        CompanyVoiceLogs logs=new CompanyVoiceLogs();
        logs.setCompanyUserId(Long.parseLong(userId));
        logs.setCustomerId(customerId);
        List<CompanyVoiceLogs> list=companyVoiceLogsService.selectCompanyVoiceLogsList(logs);
        PageInfo<CompanyVoiceLogs> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }

    //抖音 https://api.yjf.runtzh.com/app/common/douyinNotify

    @ApiOperation("外呼回调")
    @PostMapping(value="/callNotify",consumes = MediaType.APPLICATION_JSON_VALUE, produces = {"application/json; charset=UTF-8"})
    @Transactional
    public CallResult callNotify(@RequestBody String json) throws Exception {
        logger.info(json);
        CallNotifyResponse notifyResponse= JSONUtil.toBean(json, CallNotifyResponse.class);
        CompanyVoiceLogs logs = companyVoiceLogsService.selectCompanyVoiceLogsBySessionId(notifyResponse.getNotify().getUserData());
        if (logs != null) {
            if(StringUtils.isNotEmpty(notifyResponse.getNotify().getRecordFile())) {
                CompanyVoiceApi api = companyVoiceApiService.selectCompanyVoiceApiById(logs.getApiId());
                CallApiConfig apiConfig = JSONUtil.toBean(api.getApiJson(), CallApiConfig.class);
                if (StringUtils.isNotEmpty(notifyResponse.getNotify().getRecordFile())) {
                    String url=apiConfig.getUrl().replace("/openapi/V2.0.6","");
                    logs.setVoiceUrl(url + notifyResponse.getNotify().getRecordFile());
                }
                Long remain = notifyResponse.getNotify().getTimeLength() % 60;
                Long times = notifyResponse.getNotify().getTimeLength() / 60;
                if (remain > 0) {
                    times++;
                }
                logs.setStatus(1);
                logs.setTimes(notifyResponse.getNotify().getTimeLength());
                logs.setBillingTime(times);
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                logs.setStartTime(df.parse(notifyResponse.getNotify().getAnswerTime()));
                logs.setFinishTime(df.parse(notifyResponse.getNotify().getByeTime()));
                companyVoiceLogsService.updateCompanyVoiceLogs(logs);
                companyVoiceService.updateCompanyVoiceRemainTimes(logs.getCompanyId(), -times);
            }
            else{
                logs.setStatus(-1);
                companyVoiceLogsService.updateCompanyVoiceLogs(logs);
            }
        }
        CallResult result=new CallResult();
        result.setMsg("");
        result.setError("");
        return result;
    }

    @Login
    @ApiOperation("获取SIP")
    @GetMapping(value="/getSipAccount")
    public R getSipAccount() throws Exception
    {

        String userId=getUserId();
        return voiceService.getSipAccount(Long.parseLong(userId));
    }







}
