package com.crm.ucard.service.impl;

import com.alibaba.fastjson.JSON;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.dto.base.PageDto;
import com.crm.rely.backend.core.dto.base.ResultWithPagerDto;
import com.crm.rely.backend.core.dto.ucard.CardFileDto;
import com.crm.rely.backend.core.entity.base.BaseDeleteEntities;
import com.crm.rely.backend.core.entity.ucard.CardFileAddEntity;
import com.crm.rely.backend.core.entity.ucard.CardFilePageEntity;
import com.crm.rely.backend.core.entity.ucard.CardFileUpdateEntity;
import com.crm.rely.backend.core.entity.ucard.CardWebSocketEntity;
import com.crm.rely.backend.core.entity.wasabi.WasabiTransactionSubmitRfiInfosEntity;
import com.crm.rely.backend.core.entity.websocket.WebsocketPushMessageByCustomIdEntity;
import com.crm.rely.backend.core.pojo.table.ucard.CardFileTable;
import com.crm.rely.backend.core.pojo.table.ucard.CardGlobalOrderDataTable;
import com.crm.rely.backend.core.pojo.table.ucard.CardMerchantUserTable;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.util.Base64Util;
import com.crm.rely.backend.util.BeanUtilPlus;
import com.crm.ucard.dao.mapper.CardFileMapper;
import com.crm.ucard.dao.repository.CardFileRepository;
import com.crm.ucard.dao.repository.CardGlobalOrderDataRepository;
import com.crm.ucard.dao.repository.CardMerchantUserRepository;
import com.crm.ucard.service.FIleFeignService;
import com.crm.ucard.service.PushMessageFeignService;
import com.crm.ucard.service.UcardFileService;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@Service
public class UcardFileServiceImpl implements UcardFileService {

    @Autowired
    private CardMerchantUserRepository merchantUserRepository;
    @Autowired
    private CardFileRepository cardFileRepository;
    @Autowired
    private PushMessageFeignService pushMessageFeignService;
    @Autowired
    private CardGlobalOrderDataRepository globalOrderDataRepository;
    @Autowired
    private CardFileMapper cardFileMapper;
    @Autowired
    private FIleFeignService fIleFeignService;


    /**
     * 扫码上传文件
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto scanCode(CardWebSocketEntity entity) throws ServiceException {
        if ("global".equals(entity.getType())){
            if (CollectionUtils.isNotEmpty(entity.getRfiInfos())){
                String orderNo = entity.getOrderNo();
                for (WasabiTransactionSubmitRfiInfosEntity rfiInfo : entity.getRfiInfos()){
                    CardGlobalOrderDataTable orderDataTable = globalOrderDataRepository.findByOrderNoAndRfiId(orderNo, rfiInfo.getRfiId());
                    BeanUtilPlus.copyPropertiesIgnoreNull(rfiInfo,orderDataTable);
                    globalOrderDataRepository.save(orderDataTable);
                }
            }
        } else if ("card".equals(entity.getType())){
            CardMerchantUserTable userTable = merchantUserRepository.findFirstByCustomId(entity.getCustomId());
            if (StringUtils.isNotEmpty(entity.getIdBackUrl())){
                userTable.setIdBackUrl(entity.getIdBackUrl());
            }
            if (StringUtils.isNotEmpty(entity.getIdFrontUrl())){
                userTable.setIdFrontUrl(entity.getIdFrontUrl());
            }
            if (StringUtils.isNotEmpty(entity.getIdHoldUrl())){
                userTable.setIdHoldUrl(entity.getIdHoldUrl());
            }
            merchantUserRepository.save(userTable);
        }
        pushMessage(entity);
        return BaseResultDto.success();
    }


    /**
     * 新增文件
     */
    @Override
    public BaseResultDto cardFileAdd(CardFileAddEntity entity) {
        CardFileTable table = new CardFileTable();
        BeanUtils.copyProperties(entity, table);
        cardFileMapper.insert(table);
        return BaseResultDto.success();
    }

    /**
     * 更新文件
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto cardFileUpdate(CardFileUpdateEntity entity) {
        CardFileTable table = cardFileRepository.findFirstById(entity.getId());
        if (table == null) {
            return BaseResultDto.error(Constants.INFO_NOT_FOUND);
        }
        BeanUtils.copyProperties(entity, table);
        cardFileRepository.save(table);
        return BaseResultDto.success();
    }

    /**
     * 删除文件
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResultDto cardFileDelete(BaseDeleteEntities entity) {
        List<CardFileTable> fileTables = Lists.newArrayList();
        for (Long id : entity.getIds()) {
            CardFileTable fileTable = new CardFileTable();
            fileTable.setId(id);
            fileTables.add(fileTable);
        }
        cardFileRepository.deleteInBatch(fileTables);
        return BaseResultDto.success();
    }

    /**
     * 文件分页列表
     */
    @Override
    public ResultWithPagerDto<CardFileDto> cardFileSearchList(CardFilePageEntity entity) throws ServiceException {

        try {
            // 获取总数
            Integer count = cardFileMapper.countList(entity);
            PageDto pageDto = PageDto.format(entity, count);
            if (count == null || count <= 0) {
                return ResultWithPagerDto.success(pageDto);
            }
            List<CardFileDto> dtos = cardFileMapper.pageList(entity);
            return ResultWithPagerDto.success(pageDto, dtos);
        } catch (Exception e) {
            log.error("获取文件分页列表失败", e);
            throw new ServiceException("获取文件分页列表失败");
        }
    }

    /**
     * 文件上传
     */
    @Override
    public String commonUpload(MultipartFile file, String middlePath) throws Exception {
        if (!Strings.isNullOrEmpty(middlePath) && !middlePath.startsWith("/")) {
            middlePath = "/" + middlePath;
        }
        try {
            return fIleFeignService.commonUpload(file, Base64Util.toBase64String(middlePath));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 推送消息
     */
    private void pushMessage(CardWebSocketEntity socketEntity) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = null;
        if (null != attributes) {
            HttpServletRequest request = attributes.getRequest();
            token = request.getHeader(Constants.ACCESS_TOKEN);
        }
        log.info("推送websocket token：{}", token);
        if (StringUtils.isEmpty(token)) {
            return;
        }
        WebsocketPushMessageByCustomIdEntity entity = new WebsocketPushMessageByCustomIdEntity();
        entity.setCustomId(socketEntity.getCustomId());
        entity.setData(socketEntity.getData());
        try {
            log.info("推送websocket entity：{}", JSON.toJSONString(entity));
            pushMessageFeignService.pushMessageUcardCustomIdNotice(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
