package com.xinelu.manage.service.signpatientmanageroutenode.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.xinelu.common.config.AliYunSmsTwoConfig;
import com.xinelu.common.constant.PhoneMessageRemindConstants;
import com.xinelu.common.constant.TaskCreateTypeConstant;
import com.xinelu.common.constant.TaskStatisticsTypeConstants;
import com.xinelu.common.enums.NodeExecuteResultStatusEnum;
import com.xinelu.common.enums.NodeExecuteStatusEnum;
import com.xinelu.common.enums.PhoneDialMethodEnum;
import com.xinelu.common.enums.PhoneRedialTimesEnum;
import com.xinelu.manage.domain.patienttaskexecuterecord.PatientTaskExecuteRecord;
import com.xinelu.manage.domain.phonedialrecord.PhoneDialRecord;
import com.xinelu.manage.domain.signpatientmanageroute.SignPatientManageRoute;
import com.xinelu.manage.domain.signpatientmanageroutenode.SignPatientManageRouteNode;
import com.xinelu.manage.domain.signpatientrecord.SignPatientRecord;
import com.xinelu.manage.domain.textmessage.TextMessage;
import com.xinelu.manage.dto.patientquestionsubmitresult.PatientQuestionSubmitResultDTO;
import com.xinelu.manage.dto.signpatientmanageroutenode.TaskStatusDto;
import com.xinelu.manage.dto.signpatientmanageroutenode.UploadRobotPublishTaskDto;
import com.xinelu.manage.dto.smssend.SmsInfoDTO;
import com.xinelu.manage.mapper.patienttaskexecuterecord.PatientTaskExecuteRecordMapper;
import com.xinelu.manage.mapper.phonedialrecord.PhoneDialRecordMapper;
import com.xinelu.manage.mapper.signpatientmanageroute.SignPatientManageRouteMapper;
import com.xinelu.manage.mapper.signpatientmanageroutenode.SignPatientManageRouteNodeMapper;
import com.xinelu.manage.mapper.signpatientrecord.SignPatientRecordMapper;
import com.xinelu.manage.mapper.textmessage.TextMessageMapper;
import com.xinelu.manage.service.patienttaskstatistics.IPatientTaskStatisticsService;
import com.xinelu.manage.service.signpatientmanageroute.ISignPatientManageRouteService;
import com.xinelu.manage.service.signpatientmanageroutenode.IRobotPublishService;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

/**
 * @description: 爱医生接口对接Service实现
 * @author: haown
 * @create: 2024-08-16 09:16
 **/
@Slf4j
@Service
public class RobotPublishServiceImpl implements IRobotPublishService {

	@Value("${aifuv-robots.url}")
	private String url;

	@Value("${aifuv-robots.secrectKey}")
	private String secrectKey;

	@Resource
	private SignPatientRecordMapper signPatientRecordMapper;
	@Resource
	private SignPatientManageRouteMapper signPatientManageRouteMapper;
	@Resource
	private SignPatientManageRouteNodeMapper signPatientManageRouteNodeMapper;
	@Resource
	private PhoneDialRecordMapper phoneDialRecordMapper;
	@Resource
	private PatientTaskExecuteRecordMapper patientTaskExecuteRecordMapper;
	@Resource
	private IPatientTaskStatisticsService patientTaskStatisticsService;
	@Resource
	private AliYunSmsTwoConfig aliYunSmsTwoConfig;
	@Resource
	private ISignPatientManageRouteService signPatientManageRouteService;
	@Resource
	private TextMessageMapper textMessageMapper;

	/**
	 * @description 上传任务
	 * @param uploadRobotPublishTaskDto 爱医声上传任务接口传输对象
	 * @Author haown
	 * @Date 2024-8-16 9:18
	*/
	@Override
	public void uploadRobotPublishTask(UploadRobotPublishTaskDto uploadRobotPublishTaskDto) {
		uploadRobotPublishTaskDto.setRobot_publish_id("RBP1820694580367073280uQ6");
		JSONObject params = new JSONObject();
		JSONObject telLine = new JSONObject();
		JSONObject variables = new JSONObject();
		variables.fluentPut("patient_name", "郝伟娜")
			.fluentPut("department_name", "山东省立医院");
		telLine.fluentPut("enable", "id")
			.fluentPut("id", "TL1466655883911110656")
			.fluentPut("gatewayaddress", "192.168.110.111");
		params.fluentPut("yw_task_id", "18")
			.fluentPut("user_name", "郝伟娜")
			.fluentPut("user_tel", "15166940975")
			.fluentPut("task_status_push_on", false)
			.fluentPut("task_status_push_url", "http://8.131.93.145:54011/api/push_robot_publish_task_status")
			.fluentPut("task_status_push_label", "VT01")
			.fluentPut("tel_line", telLine)
			.fluentPut("start_question_id", "QN1820702693098921984Yk2")
			.fluentPut("start_date_format", "2024-08-16")
			.fluentPut("end_date_format", "2024-08-16")
			.fluentPut("invalid_date_format", new ArrayList<>())
			.fluentPut("valid_date_format", new ArrayList<>())
			.fluentPut("start_time_format", "00:00:00")
			.fluentPut("end_time_format", "23:59:59")
			.fluentPut("invalid_time_format", new ArrayList<>())
			.fluentPut("valid_time_format", new ArrayList<>())
			.fluentPut("variables", variables);
		JSONObject task = new JSONObject();
		task.fluentPut("params", params);
		List<JSONObject> tasks = new ArrayList<>();
		tasks.add(task);
		uploadRobotPublishTaskDto.setTasks(tasks);

		System.out.println((JSONObject)JSON.toJSON(uploadRobotPublishTaskDto));
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		HttpEntity<JSONObject> requestEntity = new HttpEntity<>((JSONObject)JSON.toJSON(uploadRobotPublishTaskDto), headers);

		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<String> responseEntity = restTemplate.exchange(url + "api/upload_robot_publish_task/?secret_key=" + secrectKey, HttpMethod.POST, requestEntity, String.class);
		System.out.println(responseEntity.getBody());
		JSONObject.parseObject(responseEntity.getBody());
		//{"code": 200, "res": {"tasks": [{"id": "TK1824283980640428032IK4", "yw_task_id": "16"}]}, "msg": "success"}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int updateTaskStatus(TaskStatusDto body) throws ClientException {
		// 是否发送短信标识
		boolean needSendSms = false;
		// 根据id查询任务
		SignPatientManageRouteNode signPatientManageRouteNode = signPatientManageRouteNodeMapper.selectSignPatientManageRouteNodeById(Long.valueOf(body.getId()));
		if (ObjectUtils.isNotEmpty(signPatientManageRouteNode)) {
			// 标记任务执行状态
			signPatientManageRouteNode.setNodeExecuteStatus(NodeExecuteStatusEnum.EXECUTED.getInfo());
			// 获取电话已拨打次数
			PhoneDialRecord phoneDialRecordQuery = new PhoneDialRecord();
			phoneDialRecordQuery.setManageRouteNodeId(signPatientManageRouteNode.getId());
			List<PhoneDialRecord> phoneDialRecordList = phoneDialRecordMapper.selectPhoneDialRecordList(phoneDialRecordQuery);
			// 电话拨打未成功，判断是否需要重拨；电话拨打成功，设置电话拨通情况为成功
			if (!StringUtils.equals("2", body.getTask_status())) {
				// 已经拨打的次数
				int dialCount = CollectionUtils.isEmpty(phoneDialRecordList) ? 0 : phoneDialRecordList.size() + 1;
				if (PhoneRedialTimesEnum.getValueByInfo(signPatientManageRouteNode.getPhoneRedialTimes()).getValue() > dialCount) {
					// 需要重拨
				} else {
					// 不需要重拨，设置电话拨通情况
					signPatientManageRouteNode.setPhoneNodeExecuteResultStatus(NodeExecuteResultStatusEnum.FAILURE.getInfo());
				}
				//电话短信提醒
				if (StringUtils.equals(PhoneMessageRemindConstants.NOT_CONNECTED_SEND_MESSAGE, signPatientManageRouteNode.getPhoneMessageRemind())) {
					// 发送短信
					needSendSms = true;
				}
			} else {
				signPatientManageRouteNode.setPhoneNodeExecuteResultStatus(NodeExecuteResultStatusEnum.SUCCESS.getInfo());
				if (StringUtils.equals(PhoneMessageRemindConstants.CONNECTED_SEND_MESSAGE, signPatientManageRouteNode.getPhoneMessageRemind())) {
					// 发送短信
					needSendSms = true;
				}
			}

			PatientTaskExecuteRecord patientTaskExecuteRecord = new PatientTaskExecuteRecord();
			BeanUtils.copyProperties(signPatientManageRouteNode, patientTaskExecuteRecord);

			SignPatientManageRoute signPatientManageRoute = signPatientManageRouteMapper.selectSignPatientManageRouteById(signPatientManageRouteNode.getManageRouteId());
			if (ObjectUtils.isNotEmpty(signPatientManageRoute)) {
				patientTaskExecuteRecord.setPatientId(signPatientManageRoute.getPatientId());
				patientTaskExecuteRecord.setPatientName(signPatientManageRoute.getPatientName());
				// 就诊记录
				SignPatientRecord signPatientRecord = signPatientRecordMapper.selectByPrimaryKey(signPatientManageRoute.getSignPatientRecordId());
				if (ObjectUtils.isNotEmpty(signPatientRecord)) {
					patientTaskExecuteRecord.setVisitRecordId(signPatientRecord.getPatientVisitRecordId());
				}

				// 发送短信
				if (needSendSms) {
					sendSms(signPatientManageRoute.getPatientId(), signPatientManageRouteNode);
				}
			}
			// 增加任务执行记录
			patientTaskExecuteRecord.setManageRouteNodeId(signPatientManageRouteNode.getId());
			patientTaskExecuteRecord.setManageRouteNodeName(signPatientManageRouteNode.getRouteNodeName());
			patientTaskExecuteRecord.setExecuteResult(body.getTask_status());
			patientTaskExecuteRecord.setExecuteType(TaskCreateTypeConstant.MANUAL_MATCHE);
			patientTaskExecuteRecord.setExecuteTime(LocalDateTime.now());
			patientTaskExecuteRecord.setCreateTime(LocalDateTime.now());

			// 修改任务统计表数据
			if (patientTaskExecuteRecordMapper.insertPatientTaskExecuteRecord(patientTaskExecuteRecord) > 0) {
				// 任务统计表修改
				patientTaskStatisticsService.updateNum(signPatientManageRoute.getPatientId(), TaskStatisticsTypeConstants.TASK_EXECUTE_NUM, 1);
			}
		}
		return 0;
	}


	public void sendSms(Long patientId, SignPatientManageRouteNode signPatientManageRouteNode) throws ClientException {
		TextMessage textMessage = textMessageMapper.selectTextMessageById(signPatientManageRouteNode.getPhoneMessageTemplateId());
		if (ObjectUtils.isNotEmpty(textMessage)) {
			// 发送短信
			SmsInfoDTO smsInfoDTO = new SmsInfoDTO();
			String patientPhone = signPatientManageRouteMapper.selectPatientPhone(patientId);
			smsInfoDTO.setPhoneNumbers(patientPhone);
			smsInfoDTO.setSignName(aliYunSmsTwoConfig.getSignName());
			smsInfoDTO.setTemplateCode(textMessage.getTextMessageId());
			Boolean b = signPatientManageRouteService.sendSms(smsInfoDTO);
			//发送记录
			PatientQuestionSubmitResultDTO dto = new PatientQuestionSubmitResultDTO();
			dto.setPatientId(patientId);
			dto.setPatientPhone(patientPhone);
			dto.setManageRouteNodeId(signPatientManageRouteNode.getId());
			dto.setPhoneMessageTemplateCode(textMessage.getTextMessageId());
			dto.setPhoneMessageTemplateContent(signPatientManageRouteNode.getPhoneMessageTemplateContent());
			signPatientManageRouteService.shortMessageSendRecordExtracted(dto, LocalDateTime.now(), b, PhoneDialMethodEnum.AI.getInfo());

			if (!b) {
				log.info("短信发送失败");
			} else {
				log.info("短信发送成功");
			}
		} else {
			log.info("短信发送成功");
		}
	}
}
