package com.bcxin.ferry.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bcxin.ferry.common.CommonConstant;
import com.bcxin.ferry.common.emus.FerryTaskFileStatusEnum;
import com.bcxin.ferry.common.emus.FileTypeEnum;
import com.bcxin.ferry.common.emus.SendBoundaryUrlEnum;
import com.bcxin.ferry.common.utils.Base64Util;
import com.bcxin.ferry.common.utils.DateUtil;
import com.bcxin.ferry.common.utils.IdGeneratorSnowflake;
import com.bcxin.ferry.configs.ReceiveConfig;
import com.bcxin.ferry.dao.mapper.FerryReceiveTaskFileMapper;
import com.bcxin.ferry.dtos.FerryFileCallbackDto;
import com.bcxin.ferry.entity.FerryReceiveTaskEntity;
import com.bcxin.ferry.entity.FerryReceiveTaskFileEntity;
import com.bcxin.ferry.entity.FerryTaskFileEntity;
import lombok.extern.slf4j.Slf4j;
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 java.io.File;
import java.util.Date;
import java.util.List;

/**
 * 接收任务文件表(ferry_receive_task_file)服务实现类
 *
 * @author : linchunpeng
 * @date : 2024-3-6
 */
@Slf4j
@Service
public class FerryReceiveTaskFileService extends ServiceImpl<FerryReceiveTaskFileMapper, FerryReceiveTaskFileEntity> {

    @Autowired
    private ReceiveConfig receiveConfig;
    @Autowired
    private SendRequestToBoundaryService sendRequestToBoundaryService;
    @Autowired
    private IdGeneratorSnowflake snowflake;

    /**
     * 初始化接收文件
     */
    public FerryReceiveTaskFileEntity createFerryReceiveTaskFile(FerryReceiveTaskEntity receiveTaskEntity, FerryTaskFileEntity ferryTaskFileEntity) {
        FerryReceiveTaskFileEntity receiveTaskFileEntity = new FerryReceiveTaskFileEntity();
        BeanUtils.copyProperties(ferryTaskFileEntity, receiveTaskFileEntity);
        receiveTaskFileEntity.setId(ferryTaskFileEntity.getId());
        receiveTaskFileEntity.setTaskId(receiveTaskEntity.getId());
        receiveTaskFileEntity.setFileStatus(1);
        receiveTaskFileEntity.setMergeStatus(1);
        receiveTaskFileEntity.setCreateTime(new Date());
        receiveTaskFileEntity.setUpdateTime(new Date());
        return receiveTaskFileEntity;
    }

    /**
     * 接收明细文件
     */
    @Transactional
    public boolean receiveTaskDetailFile(Long id, String base64) {
        FerryReceiveTaskFileEntity receiveTaskFileEntity = this.getById(id);
        if (receiveTaskFileEntity.getFileStatus() == 2) {
            log.info("该明细文件已经接收了");
            return false;
        }
        if (StringUtils.isNotBlank(base64)) {
            File file = Base64Util.base64ToFile(base64, receiveConfig.getPackageUrl().concat(receiveTaskFileEntity.getFileUrl()),
                    receiveTaskFileEntity.getFileType() != FileTypeEnum.NORMAL.getCode());
            receiveTaskFileEntity.setReceiveFileMd5(MD5.create().digestHex16(file));
        }
        receiveTaskFileEntity.setReceiveResult("接收完成");
        receiveTaskFileEntity.setFileStatus(2);
        receiveTaskFileEntity.setMergeStatus(1);
        receiveTaskFileEntity.setUpdateTime(new Date());
        this.updateById(receiveTaskFileEntity);
        return true;
    }

    /**
     * description：查询未接收完成的文件数量
     * author：linchunpeng
     * date：2024/3/14
     */
    public long countNotCompleteByTaskId(Long taskId) {
        LambdaQueryChainWrapper<FerryReceiveTaskFileEntity> lqw = this.lambdaQuery();
        lqw.eq(FerryReceiveTaskFileEntity::getTaskId, taskId);
        lqw.eq(FerryReceiveTaskFileEntity::getIsSplit, 0);
        lqw.eq(FerryReceiveTaskFileEntity::getFileStatus, 1);
        return lqw.count();
    }

    /**
     * description：单个文件回调
     * author：linchunpeng
     * date：2024/3/13
     */
    @Transactional
    public void callbackToBoundary(Long id, SendBoundaryUrlEnum urlEnum) {
        FerryReceiveTaskFileEntity receiveTaskFileEntity = this.getById(id);
        FerryFileCallbackDto callbackDto = new FerryFileCallbackDto();
        callbackDto.setFerry_accept_url(urlEnum.getValue());
        callbackDto.setFileId(receiveTaskFileEntity.getId().toString());
        callbackDto.setFileStatus(FerryTaskFileStatusEnum.FERRY_COMPLETE.getCode());
        callbackDto.setFerryResult("摆渡完成");
        //调用边界服务接口
        sendRequestToBoundaryService.send(BeanUtil.beanToMap(callbackDto));
    }

    /**
     * description：查询已完成的摆渡的分割文件
     * author：linchunpeng
     * date：2024/3/15
     */
    public List<FerryReceiveTaskFileEntity> queryFerryCompleteList(Long taskId) {
        LambdaQueryChainWrapper<FerryReceiveTaskFileEntity> lqw = this.lambdaQuery();
        lqw.eq(FerryReceiveTaskFileEntity::getTaskId, taskId);
        lqw.eq(FerryReceiveTaskFileEntity::getIsSplit, 1);
        lqw.eq(FerryReceiveTaskFileEntity::getFileStatus, 2);
        return lqw.list();
    }

    /**
     * description：通过ids查询接收文件
     * author：linchunpeng
     * date：2024/3/15
     */
    public List<FerryReceiveTaskFileEntity> queryByIds(List<Long> ids) {
        LambdaQueryChainWrapper<FerryReceiveTaskFileEntity> lqw = this.lambdaQuery();
        lqw.in(FerryReceiveTaskFileEntity::getId, ids);
        return lqw.list();
    }

    /**
     * description：查询大于半小时小时还未摆渡完成的文件
     * author：linchunpeng
     * date：2024/3/20
     */
    public List<FerryReceiveTaskFileEntity> queryHalfHourNotCompleteList() {
        //大于半小时小时还未摆渡完成的文件
        Date intervalTime = DateUtil.getBeforeNumMinuteTime(new Date(), 30);

        LambdaQueryChainWrapper<FerryReceiveTaskFileEntity> lqw = this.lambdaQuery();
        lqw.ne(FerryReceiveTaskFileEntity::getFileStatus, 1);
        lqw.lt(FerryReceiveTaskFileEntity::getCreateTime, intervalTime);
        lqw.orderByAsc(FerryReceiveTaskFileEntity::getCreateTime);
        return lqw.list();
    }

}