package com.cusc.nirvana.user.rnr.fp.service.impl;

import com.alibaba.fastjson.JSON;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.rnr.fp.common.ResponseCode;
import com.cusc.nirvana.user.rnr.fp.constants.BizTypeEnum;
import com.cusc.nirvana.user.rnr.fp.dto.*;
import com.cusc.nirvana.user.rnr.fp.service.IFpCardUnBindService;
import com.cusc.nirvana.user.rnr.fp.service.IFpRnrSmsInfoService;
import com.cusc.nirvana.user.rnr.fp.service.ShortMessageCheckService;
import com.cusc.nirvana.user.rnr.mg.client.ChangeOrUnbindIccidsClient;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrCardInfoClient;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrInfoClient;
import com.cusc.nirvana.user.rnr.mg.client.RnrOrderClient;
import com.cusc.nirvana.user.rnr.mg.dto.MgRnrCardInfoDTO;
import com.cusc.nirvana.user.rnr.mg.dto.MgRnrInfoDTO;
import com.cusc.nirvana.user.rnr.mg.dto.RnrOrderDTO;
import com.cusc.nirvana.user.rnr.mg.dto.RnrRelationDTO;
import com.cusc.nirvana.user.util.CuscStringUtils;
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 org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class FpCardUnBindServiceImpl implements IFpCardUnBindService {
    @Resource
    private MgRnrCardInfoClient cardInfoClient;

    @Resource
    private MgRnrInfoClient infoClient;

    @Autowired
    private ShortMessageCheckService messageCheckService;

    @Autowired
    private IFpRnrSmsInfoService smsInfoService;

    @Resource
    private RnrOrderClient orderClient;

    @Resource
    private ChangeOrUnbindIccidsClient iccidsClient;

    @Value("${message.callback.timeout:120}")
    private int timeOut;

    /**
     * 车主实名解绑
     * @return
     */
    @Override
    public Response<Boolean> ownerUnbind(RnrRelationDTO relationDTO){
        log.info("解绑fp入参: {}", JSON.toJSONString(relationDTO));
        Response orderResponse = orderClient.add(relationDTO.getOrder());
        if(!orderResponse.isSuccess()){
            return Response.createError("保存工单失败");
        }
        return cardInfoClient.updateBatch(relationDTO.getCardList());
    }

    @Override
    public Response<MgRnrInfoDTO> getUserInfo(FpVehicleCardRnrDTO cardRnrDTO){
        log.info("解绑fp获取实名信息入参: {}", JSON.toJSONString(cardRnrDTO));
        MgRnrInfoDTO mgRnrInfoDTO = new MgRnrInfoDTO();
        mgRnrInfoDTO.setUuid(cardRnrDTO.getRnrId());
        log.info("解绑mg获取实名信息入参: {}", JSON.toJSONString(mgRnrInfoDTO));
        Response<MgRnrInfoDTO> byUuid = infoClient.getByUuid(mgRnrInfoDTO);
        log.info("解绑mg获取实名信息出参: {}", JSON.toJSONString(byUuid));
        if(!byUuid.isSuccess() || byUuid.getData() == null){
            return Response.createError("获取实名人信息失败");
        }
        return byUuid;
    }

    //发送短信
    @Override
    public Response<FpRnrSmsInfoDTO> sendUnbindSMS(FpSendMessageDTO sendMessageDTO) {
        log.info("解绑fp发短信入参: {}", JSON.toJSONString(sendMessageDTO));
        Response<SmsResponseDTO> smsResponseDTOResponse = messageCheckService.sendUnbindSms(sendMessageDTO.getSmsRequestDTO(), sendMessageDTO.getRnrid(), sendMessageDTO.getIccidLists());
        if(!smsResponseDTOResponse.isSuccess() || smsResponseDTOResponse.getData() == null){
            return Response.createError("短信发送失败");
        }
        log.info("解绑短信返回值: {}",JSON.toJSONString(smsResponseDTOResponse));
        //短信入库
        SmsRequestDTO smsRequestDto = sendMessageDTO.getSmsRequestDTO();
        FpRnrSmsInfoDTO fpRnrSmsInfoDTO = new FpRnrSmsInfoDTO();
        fpRnrSmsInfoDTO.setIsDelete(0);
        fpRnrSmsInfoDTO.setCreateTime(new Date(System.currentTimeMillis()));
        fpRnrSmsInfoDTO.setUuid(CuscStringUtils.generateUuid());
        fpRnrSmsInfoDTO.setSendPhone(sendMessageDTO.getSmsRequestDTO().getPhone());
        fpRnrSmsInfoDTO.setSendSmsId(smsResponseDTOResponse.getData().getMessageId());
        fpRnrSmsInfoDTO.setRnrId(sendMessageDTO.getRnrid());
        fpRnrSmsInfoDTO.setIccids(sendMessageDTO.getIccidLists());
        fpRnrSmsInfoDTO.setSendContent(sendMessageDTO.getSmsRequestDTO().getParams().toString());
        fpRnrSmsInfoDTO.setBizType(wrapBizType(smsRequestDto.getBizType()));
        fpRnrSmsInfoDTO.setCreator(sendMessageDTO.getUser());
        fpRnrSmsInfoDTO.setOperator(sendMessageDTO.getUser());
        fpRnrSmsInfoDTO.setOrderId(sendMessageDTO.getOrderId());

        FpRnrSmsInfoDTO insert = smsInfoService.insert(fpRnrSmsInfoDTO);
        return Response.createSuccess(insert);
    }

    @Override
    public Response<List<MgRnrCardInfoDTO>> getCardList(FpVehicleCardRnrDTO cardRnrDTO) {
        log.info("解绑fp获取iccid列表入参: {}", JSON.toJSONString(cardRnrDTO));
        MgRnrCardInfoDTO bean =  new MgRnrCardInfoDTO();
        bean.setIotId(cardRnrDTO.getVin());
//        bean.setRnrBizzType(RnrBizzTypeEnum.Unbound.getCode());
        return  cardInfoClient.queryBindListByVin(bean);
    }

    @Override
    public Response<FpRnrSmsInfoDTO> getMessageStatus(FpRnrSmsInfoDTO bean) {
        log.info("解绑fp获取短信状态入参: {}", JSON.toJSONString(bean));
        FpRnrSmsInfoDTO poByMessageId = smsInfoService.getPoByPhoneNo(bean);
        return Response.createSuccess(poByMessageId);
    }

    //短信回调
    @Override
    public Response<FpRnrSmsInfoDTO> receiveMessage(UnbindReceiceSMSDTO receiceSMSDTO) {
        log.info("解绑fp获取短信回调入参: {}", JSON.toJSONString(receiceSMSDTO));
        FpRnrSmsInfoDTO fpRnrSmsInfoDTO = new FpRnrSmsInfoDTO();
        fpRnrSmsInfoDTO.setSendPhone(receiceSMSDTO.getPhoneNumber());
        fpRnrSmsInfoDTO.setSendSmsId(receiceSMSDTO.getMessageId());

        FpRnrSmsInfoDTO poByPhoneNo = smsInfoService.getPoByPhoneNo(fpRnrSmsInfoDTO);
        if(poByPhoneNo == null){
            return Response.createError("获取短信内容失败");
        }
        poByPhoneNo.setReceivePhone(receiceSMSDTO.getPhoneNumber());
        poByPhoneNo.setReceiveSmsId(receiceSMSDTO.getMessageId());
        poByPhoneNo.setReceiveContent(receiceSMSDTO.getReplyContent());
        return Response.createSuccess(smsInfoService.update(poByPhoneNo));
    }

    @Override
    public Response<RnrOrderDTO> insertOrder(RnrOrderDTO dto){
        Response response = orderClient.add(dto);
        if(!response.isSuccess()){
            return Response.createError(response.getMsg(),response.getCode());
        }
        iccidsClient.sendMSMToMQ(dto);
        return response;
    }


    @Override
    public Response<RnrOrderDTO> getOrderStatus(RnrOrderDTO dto){
        Response<RnrOrderDTO> dtoResponse = orderClient.getByUuid(dto);
        if(!dtoResponse.isSuccess()){
            return Response.createError(dtoResponse.getMsg(),dtoResponse.getCode());
        }
        return dtoResponse;
    }

    @Override
    public Response checkReceiveMessageTime(RnrOrderDTO dto){
        long currentTimeMillis = System.currentTimeMillis();
        //查询短信信息
        FpRnrSmsInfoDTO fpRnrSmsInfoDTO = new FpRnrSmsInfoDTO();
        fpRnrSmsInfoDTO.setOrderId(dto.getUuid());
        log.info("fp解绑查询短信状态:{}",JSON.toJSONString(fpRnrSmsInfoDTO));
        List<FpRnrSmsInfoDTO> fpRnrSmsInfoDTOS = smsInfoService.queryByOrderId(fpRnrSmsInfoDTO);
        log.info("fp解绑查询短信:{}",JSON.toJSONString(fpRnrSmsInfoDTOS));
        if (CollectionUtils.isEmpty(fpRnrSmsInfoDTOS)) {
            return Response.createError("获取短信信息失败");
        }
        //校验时间
        long time = fpRnrSmsInfoDTOS.get(0).getCreateTime().getTime();

        log.info("判断超时,{},{},{},{}", currentTimeMillis, timeOut, time, currentTimeMillis - timeOut * 1000);

        if (currentTimeMillis - timeOut * 1000 > time) {
            log.info("短信回复超时，设置成失败状态");
            return Response.createError("回复短信超时");
        }
        return Response.createSuccess("短信校验未超时");
    }

    @Override
    public Response<RnrOrderDTO> updateOrder(RnrOrderDTO dto){
        Response response = orderClient.updateOrderStatus(dto);
        if(!response.isSuccess()){
            //return Response.createError(response.getMsg(),response.getCode());
			throw new CuscUserException(ResponseCode.SYSTEM_ERROR.getCode(),"更新工单失败");
        }
        return response;
    }


    private Integer wrapBizType(String bizType) {
        Integer rv = MessageBizTypeEnum.UBIND.getCode();
        if (BizTypeEnum.CHANGETBOX.getCode().equalsIgnoreCase(bizType)) {
            rv = MessageBizTypeEnum.CHANGETBOX.getCode();
        }
        return rv;
    }
}
