package com.bcxin.ferry.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bcxin.ferry.common.emus.FerryReceiveTaskStatusEnum;
import com.bcxin.ferry.common.utils.DateUtil;
import com.bcxin.ferry.common.utils.IdGeneratorSnowflake;
import com.bcxin.ferry.configs.FerryChannelConfig;
import com.bcxin.ferry.configs.FerrySwitchConfig;
import com.bcxin.ferry.configs.ReceiveConfig;
import com.bcxin.ferry.configs.SchedulingConfig;
import com.bcxin.ferry.dao.mapper.FerryReceiveTaskMapper;
import com.bcxin.ferry.dtos.baiduutil.FerryReceiveTaskPushResult;
import com.bcxin.ferry.entity.FerryReceiveTaskEntity;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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)服务实现类
 *
 * @author : linchunpeng
 * @date : 2024-3-6
 */
@Slf4j
@Service
public class FerryReceiveTaskService extends ServiceImpl<FerryReceiveTaskMapper, FerryReceiveTaskEntity> {

    @Autowired
    private ReceiveConfig receiveConfig;
    @Autowired
    private FerrySwitchConfig ferrySwitchConfig;
    @Autowired
    private IdGeneratorSnowflake snowflake;
    @Autowired
    private RetryService retryService;
    @Autowired
    private FerryTaskService ferryTaskService;
    @Autowired
    private FerryChannelConfig ferryChannelConfig;
    @Value("${spring.profiles.active}")
    private String activeFile;


    /**
     * description：接收摆渡任务文件
     * author：linchunpeng
     * date：2024/3/14
     */
    @Transactional
    public FerryReceiveTaskEntity receiveRequest(String requestId) {
        log.info("接收摆渡任务文件");
        LambdaQueryChainWrapper<FerryReceiveTaskEntity> lqw = this.lambdaQuery();
        lqw.eq(FerryReceiveTaskEntity::getRequestId, requestId);
        if (!lqw.exists()) {
            log.info("创建接收任务");
            FerryReceiveTaskEntity receiveTaskEntity = new FerryReceiveTaskEntity();
            receiveTaskEntity.setId(snowflake.snowflakeId());
            receiveTaskEntity.setRequestId(requestId);
            receiveTaskEntity.setPackageUrl(receiveConfig.getPackageUrl().concat(requestId).concat(".zip"));
            receiveTaskEntity.setTaskStatus(FerryReceiveTaskStatusEnum.RECEIVE_REQUEST.getCode());
            receiveTaskEntity.setCreateTime(new Date());
            receiveTaskEntity.setUpdateTime(new Date());
            this.save(receiveTaskEntity);
            return receiveTaskEntity;
        }
        return lqw.list().get(0);
    }

    /**
     * description：调用摆渡工具服务，推送数据
     * author：linchunpeng
     * date：2024/3/15
     */
    @Transactional
    public void pushData(FerryReceiveTaskEntity receiveTaskEntity) {
        log.info("调用摆渡工具服务，推送数据");
        if (receiveTaskEntity != null) {
            //调用摆渡工具服务，推送数据
            retryService.postToBaiduutilServerPush(receiveTaskEntity);
            receiveTaskEntity.setTaskStatus(FerryReceiveTaskStatusEnum.PUSH_DATA.getCode());
            receiveTaskEntity.setUpdateTime(new Date());
            this.updateById(receiveTaskEntity);
        }
    }

    /**
     * description：查询是否有摆渡完成的任务
     * author：linchunpeng
     * date：2024/3/15
     */
    @Transactional
    public void queryReceiveTaskIsComplete() {
        LambdaQueryChainWrapper<FerryReceiveTaskEntity> lqw = this.lambdaQuery();
        lqw.eq(FerryReceiveTaskEntity::getTaskStatus, FerryReceiveTaskStatusEnum.PUSH_DATA.getCode());
        List<FerryReceiveTaskEntity> list = lqw.list();
        if (CollectionUtil.isNotEmpty(list)) {
            for (FerryReceiveTaskEntity receiveTaskEntity : list) {
                if (receiveTaskEntity != null) {
                    log.info("查询是否有摆渡完成的任务，requestId：{}", receiveTaskEntity.getRequestId());
                    FerryReceiveTaskPushResult result = retryService.postToBaiduutilServerPushResult(receiveTaskEntity);
                    if (result != null && result.getTaskStatus() != null) {
                        receiveTaskEntity.setReceiveResult(result.getReceiveResult());
                        receiveTaskEntity.setTaskStatus(result.getTaskStatus());
                        receiveTaskEntity.setUpdateTime(new Date());
                        this.updateById(receiveTaskEntity);
                    }
                }
            }
        }
    }

    /**
     * description：查询是否有摆渡完成的任务
     * author：linchunpeng
     * date：2024/3/15
     */
    @Transactional
    public List<FerryReceiveTaskEntity> queryReceiveTaskComplete() {
        log.info("查询是否有摆渡完成的任务");
        LambdaQueryChainWrapper<FerryReceiveTaskEntity> lqw = this.lambdaQuery();
        lqw.eq(FerryReceiveTaskEntity::getTaskStatus, FerryReceiveTaskStatusEnum.FERRY_COMPLETE.getCode());
        return lqw.list();
    }

    /**
     * description：发送完文件到对端
     * author：linchunpeng
     * date：2024/9/23
     */
    @Transactional
    public void sendCompleteFile(FerryReceiveTaskEntity receiveTaskEntity) {
        log.info("生成.complete文件");
        String completeFile = receiveConfig.getPackageUrl().concat(receiveTaskEntity.getRequestId()).concat(".complete");
        try {
            if (ferrySwitchConfig.getEnablePull() != null && ferrySwitchConfig.getEnablePull()) {
                log.info("===================================有开启拉取摆渡包，才需要放入通道===================================");
                FileUtil.appendUtf8String(String.format("%s.zip摆渡完成，回调对端，告知摆渡完成，修改状态。", receiveTaskEntity.getRequestId()), completeFile);
                //目标服务器的地址，sendPath + 日期 + requestId.zip，如果是有摆渡到政务网的，需要在requestId前面添加：zw
                String targetFilePath = ferryChannelConfig.getSendPath().concat(File.separator)
                        .concat(DateUtil.formatDate(new Date())).concat(File.separator)
                        .concat(receiveTaskEntity.getRequestId()).concat(".complete");
                //开始复制文件到目标服务器上
                ferryTaskService.copyFileToFerryChannel(completeFile, targetFilePath);
            } else {
                log.info("===================================没有开启拉取摆渡包，不需要放入通道===================================");
            }
            receiveTaskEntity.setTaskStatus(FerryReceiveTaskStatusEnum.CALLBACK_COMPLETE.getCode());
            receiveTaskEntity.setUpdateTime(new Date());
            this.updateById(receiveTaskEntity);
        } catch (Exception e) {
            log.error("创建{}.complete文件失败，{}", receiveTaskEntity.getRequestId(), e.getMessage(), e);
            e.printStackTrace();
        }
    }
}