package thyyxxk.webserver.controller.medicalinsurance;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import thyyxxk.webserver.config.auth.PassToken;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.constants.Capacity;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.medicalinsurance.inpatient.RdCrdRslt;
import thyyxxk.webserver.utils.ResultVoUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description: 读卡
 * @author: DingJie
 * @create: 2021/8/1910:15
 */
@Slf4j
@RestController
@RequestMapping("/siReadCard")
public class SiRdCrdController {
    private final Map<String, RdCrdRslt> map = new HashMap<>(Capacity.DEFAULT);

    @PassToken
    @GetMapping("/request")
    public ResultVo<RdCrdRslt> request(@RequestParam("prm") String prm) throws Exception {
        log.info("读卡请求：{}", prm);
        String patNo = prm.split("_")[1];
        int count = 0;
        RdCrdRslt rslt = null;
        while (null == rslt && count < 40) {
            TimeUnit.MILLISECONDS.sleep(1500);
            rslt = map.remove(patNo);
            count++;
        }
        if (null == rslt) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "读卡失败。");
        }
        if (rslt.getCode() != 0) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, rslt.getMessage());
        }
        return ResultVoUtil.success(rslt);
    }

    @PassToken
    @PostMapping("/callback")
    public String callback(@RequestBody RdCrdRslt rslt) {
        log.info("读卡回调：{}", rslt);
        map.put(rslt.getPatNo(), rslt);
        return "回调成功。";
    }

}
