package com.glxp.mipsdl.client.ptxhyy;

import cn.hutool.core.thread.ThreadUtil;
import com.glxp.mipsdl.client.BaseFileClient;
import com.glxp.mipsdl.client.CommonFileClient;
import com.glxp.mipsdl.req.post.PostThrProductsRequest;
import com.glxp.mipsdl.res.BaseResponse;
import com.glxp.mipsdl.res.udiwms.UdiwmsProductInfoResponse;
import com.glxp.mipsdl.service.file.UdiInfoUploadService;
import com.glxp.mipsdl.util.ExcelUtil;
import com.glxp.mipsdl.util.ExecutorUtil;
import com.glxp.mipsdl.util.ResultVOUtils;
import com.glxp.mipsdl.vo.file.ptxhyy.PtxhyyProductEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 平潭协和医院物资系统文件接口
 */
@Slf4j
@Service(value = "100008FileClient")
public class PtxhyyFileClient extends CommonFileClient {

    @Resource
    private UdiInfoUploadService udiInfoUploadService;
    @Resource
    private ExecutorUtil executorUtil;

    @Override
    public BaseResponse uploadPi(List<MultipartFile> files, String thirdSys) {
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            if (file.isEmpty()) {
                return ResultVOUtils.error(500, "上传第" + (i++) + "个文件失败");
            }
            try {
                InputStream inputStream = file.getInputStream();
                ExcelUtil<PtxhyyProductEntity> util = new ExcelUtil(PtxhyyProductEntity.class);
                List<UdiwmsProductInfoResponse> udiwmsProductInfoResponses = util.importPi(inputStream);
                PostThrProductsRequest postThrProductsRequest = new PostThrProductsRequest();
                postThrProductsRequest.setDatas(udiwmsProductInfoResponses);
                postThrProductsRequest.setUploadType("文件导入");
                postThrProductsRequest.setThirdSys(thirdSys);
                executorUtil.getUploadExecutor().execute(ThreadUtil.newThread(() -> {
                    udiInfoUploadService.postProducts(postThrProductsRequest);
                }, "uploadPi"));
                log.error("上传完" + System.currentTimeMillis());
            } catch (IOException e) {
                log.error("解析上传excel文件IO异常，异常信息：{}", e);
                return ResultVOUtils.error(500, "数据异常");
            } catch (Exception e) {
                log.error("处理产品信息excel文件异常，异常信息：{}", e);
                return ResultVOUtils.error(500, "数据异常");
            }
        }
        return ResultVOUtils.success("文件解析成功，正在上传，请稍后刷新查看");
    }
}
