package thyyxxk.webserver.service.medicalinsurance;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.envionment.MedinsurConfig;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.constants.sidicts.SiFunction;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.utils.ResultVoUtil;

/**
 * @description: 医保上传服务
 * @author: DingJie
 * @create: 2021/7/3015:34
 */
@Slf4j
@Service
public class SiUploadService {
    private static final String RESULT_CODE = "infcode";
    private static final String ERROR_MESSAGE = "err_msg";
    private static final String OUTPUT = "output";
    private final ExecService exec;
    private final MedinsurConfig cfg;

    @Autowired
    public SiUploadService(ExecService exec, MedinsurConfig cfg) {
        this.exec = exec;
        this.cfg = cfg;
    }

    public ResultVo<String> uploadFile(byte[] file, String fileName) {
        JSONObject input = exec.makeTradeHeader(SiFunction.UPLOAD_FILE);
        JSONObject fsUploadIn = new JSONObject();
        fsUploadIn.put("in", file);
        fsUploadIn.put("filename", fileName);
        fsUploadIn.put("fixmedins_code", cfg.getHospId());
        return getStringResultVo(input, fsUploadIn);
    }

    public ResultVo<String> uploadFile(JSONObject fsUploadIn) {
        JSONObject input = exec.makeTradeHeader(SiFunction.UPLOAD_FILE);
        return getStringResultVo(input, fsUploadIn);
    }

    private ResultVo<String> getStringResultVo(JSONObject input, JSONObject fsUploadIn) {
        input.getJSONObject("input").put("fsUploadIn", fsUploadIn);
        JSONObject result = exec.executeTrade(input, SiFunction.UPLOAD_FILE);
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        if (null == result.getInteger(RESULT_CODE)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医保中心报错：" + result.getString("message"));
        }
        if (result.getIntValue(RESULT_CODE) == 0) {
            JSONObject output = result.getJSONObject(OUTPUT);
            String fileQuryNo = output.getString("file_qury_no");
            return ResultVoUtil.success(fileQuryNo);
        }
        return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, result.getString(ERROR_MESSAGE));
    }
}
