package com.mortals.xhx.modules.supplement.task;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.common.code.ExcelUploadEnum;
import com.mortals.xhx.modules.supplement.service.SupplementService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author
 * @Date: 2021-08-2021/8/16-11:03
 * @Description: 通过文件地址去读取文件内容，读取完成后，存储在清洗表中，等待清洗
 */
@Slf4j
@Component("excelUploadTaskImpl")
public class ExcelUploadTaskImpl implements ITaskExcuteService {

    @Autowired
    private UploadService uploadService;

    @Autowired
    private ICacheService iCacheService;

    @Autowired
    private SupplementService supplementService;

    @Override
    public void excuteTask(ITask task) throws AppException {
        Map<String, String> map = iCacheService.hgetAll(ExcelUploadEnum.UPLOAD_PATH.getCode());
        if (!map.isEmpty()){
            for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
                JSONObject jsonObject = JSONObject.parseObject(stringStringEntry.getValue());
                String sysCode = jsonObject.getString("sysCode");
                if (ExcelUploadEnum.未处理的文件路径.getCode().equals(jsonObject.getString("status"))){
                    Map<String, String> objectObjectHashMap = new HashMap<>();
                    objectObjectHashMap.put("sysCode",sysCode);
                    objectObjectHashMap.put("status",ExcelUploadEnum.已处理的文件路径.getCode());
                    iCacheService.hset(ExcelUploadEnum.UPLOAD_PATH.getCode(),stringStringEntry.getKey(),objectObjectHashMap);
                    //存储方法
                    this.storageCleaningTable(stringStringEntry.getKey(),sysCode);
                }
            }
        }
    }

    @Override
    public void stopTask(ITask task) throws AppException {

    }

    private void storageCleaningTable(String filePath,String sysCode) {
        String fileAbsolutePath= uploadService.getFilePath(filePath);
        BufferedInputStream inputStream = FileUtil.getInputStream(fileAbsolutePath);
        try {
            //存储到临时表
            supplementService.importOfficeInformation(inputStream,sysCode);
            //删除redis里面的值
            iCacheService.hdel(ExcelUploadEnum.UPLOAD_PATH.getCode(),filePath);
            //删除本地文件里面的值
            FileUtil.del(fileAbsolutePath);
        }catch (Exception e){
            log.error("操作出错，出错原因：",e);
        }
    }

}
