package com.yeejoin.amos.boot.module.tzs.biz.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertCalledFormDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.VoiceRecordFileDto;
import com.yeejoin.amos.boot.module.tzs.api.entity.VoiceRecordFile;
import com.yeejoin.amos.boot.module.tzs.api.service.ICtiService;
import com.yeejoin.amos.boot.module.tzs.biz.service.impl.AlertCalledServiceImpl;
import com.yeejoin.amos.boot.module.tzs.biz.service.impl.VoiceRecordFileServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 通话记录附件
 *
 * @author system_generator
 * @date 2021-08-03
 */
@RestController
@Api(tags = "通话记录附件Api")
@RequestMapping(value = "/voice-record-file")
public class VoiceRecordFileController extends BaseController {

    @Autowired
    VoiceRecordFileServiceImpl voiceRecordFileServiceImpl;

	@Autowired
	AlertCalledServiceImpl iAlertCalledService;

	@Autowired
	ICtiService ctiService;

    /**
     * 新增通话记录附件
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增通话记录附件", notes = "新增通话记录附件")
	public ResponseModel<VoiceRecordFileDto> save(@RequestBody VoiceRecordFileDto model) {
		if (ValidationUtil.isEmpty(model.getAlertId())
				|| ValidationUtil.isEmpty(model.getTel())){
			throw new BadRequest("参数校验失败.");
		}
		Calendar startTime = Calendar.getInstance();
		Calendar endTime = Calendar.getInstance();
		endTime.add(Calendar.MINUTE, 6);
		model.setTelStartTime(startTime.getTime());
		model.setTelEndTime(endTime.getTime());
		model.setFilePath(UUID.randomUUID().toString().replace("-",""));
		model.setFileType("");
		model.setSourceId(-1l);
		AlertCalledFormDto alertDto = iAlertCalledService.selectAlertCalledByIdNoCache(model.getAlertId());
		if(alertDto == null || alertDto.getAlertCalledDto() == null) {
			throw new BadRequest("未找到相关警情");
		}
		model.setAlertStage(alertDto.getAlertCalledDto().getAlertStage());
		model.setAlertStageCode(alertDto.getAlertCalledDto().getAlertStageCode());
		model = voiceRecordFileServiceImpl.createWithModel(model);
		return ResponseHelper.buildResponse(model);
	}

	/**
	 * 根据警情id 查找通话记录信息
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET",value = "根据警情id 查找通话记录信息",   notes = "根据警情id 查找通话记录信息")
	@GetMapping(value = "/list/alert/{alertId}")
	public ResponseModel<List<VoiceRecordFileDto>> selectForListByAlertId(@PathVariable Long alertId) {
		LambdaQueryWrapper<VoiceRecordFile> queryWrapper = new LambdaQueryWrapper<VoiceRecordFile>();
		queryWrapper.eq(VoiceRecordFile::getAlertId, alertId).orderByDesc(VoiceRecordFile::getRecDate);
		List<VoiceRecordFile> list = voiceRecordFileServiceImpl.list(queryWrapper);
		List<VoiceRecordFileDto> dtoList = new ArrayList<VoiceRecordFileDto>(list.size());
		list.stream().forEach(voiceRecord -> {
			// 创建新的对象实例
			VoiceRecordFileDto target = new VoiceRecordFileDto();
			// 把原对象数据拷贝到新对象
			BeanUtils.copyProperties(voiceRecord, target);
			if(voiceRecord.getTelStartTime() != null && voiceRecord.getTelEndTime() != null) {
				target.setTelTime(DateUtils.getTimestr( voiceRecord.getTelEndTime(),voiceRecord.getTelStartTime()));
			}
			dtoList.add(target);
		});
		return ResponseHelper.buildResponse(dtoList);
	}


	/**
	 * 新增通话记录
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/saveRecord")
	@ApiOperation(httpMethod = "POST", value = "新增通话记录附件", notes = "新增通话记录附件")
	public ResponseModel<VoiceRecordFileDto> saveRecord(@RequestBody VoiceRecordFileDto model) {
		if (ValidationUtil.isEmpty(model.getAlertId())
				|| ValidationUtil.isEmpty(model.getConnectId())){
			throw new BadRequest("参数校验失败.");
		}
		// 获取通话人信息
		JSONArray recordInfos = ctiService.getCallInfo(model.getConnectId());
		if(recordInfos == null || recordInfos.size() == 0) {
			throw new BadRequest("未找到通话详单信息");
		}
		JSONObject recordInfo = recordInfos.getJSONObject(0);
		model.setTel(recordInfo.getString("telephone"));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
		Date telStartTime = null;
		Date telEndTime = null;
		try {
			telStartTime = sdf.parse(recordInfo.getString("connectTime"));
			telEndTime = sdf.parse(recordInfo.getString("hangupTime"));
		} catch (ParseException e) {
			throw new BadRequest("日期转换错误");
		}
		model.setTelStartTime(telStartTime);
		model.setTelEndTime(telEndTime);
		if(1 == recordInfo.getInteger("callType")) {
			model.setFileType("客户呼入");
		} else if(2 == recordInfo.getInteger("callType")) {
			model.setFileType("坐席呼出");
		}

		// 获取附件
		Map<String, String> downloadFile = ctiService.downLoadRecordFile(model.getConnectId());
		if(downloadFile.isEmpty()) {
			throw new BadRequest("未找到附件文件");
		}
		for(Map.Entry<String,String> file : downloadFile.entrySet()) {
			model.setFilePath(file.getKey());
		}
		AlertCalledFormDto alertDto = iAlertCalledService.selectAlertCalledByIdNoCache(model.getAlertId());
		if(alertDto == null || alertDto.getAlertCalledDto() == null) {
			throw new BadRequest("未找到相关警情");
		}
		model.setAlertStage(alertDto.getAlertCalledDto().getAlertStage());
		model.setAlertStageCode(alertDto.getAlertCalledDto().getAlertStageCode());
		model.setSourceId(-1l);
		model = voiceRecordFileServiceImpl.createWithModel(model);
		return ResponseHelper.buildResponse(model);
	}
}
