package com.xhpc.evcs.api;

import com.xhpc.evcs.dto.CommonRequest;
import com.xhpc.evcs.dto.CommonResponse;
import com.xhpc.evcs.dto.QueryTerminalCodeRequest;
import com.xhpc.evcs.dto.QueryTerminalCodeResponse;
import com.xhpc.evcs.encryption.EvcsConst;
import com.xhpc.evcs.utils.JSONUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @Author HongYun on 2021/11/11
 */
@RestController
public class QueryTerminalCodeController {

    @PostMapping(value = "/v1/query_terminal_code")
    public CommonResponse queryTerminalCode(@RequestBody CommonRequest<QueryTerminalCodeRequest> commonRequest) throws IOException {

        CommonResponse resp = new CommonResponse();
        resp.setRet(EvcsConst.RET_FAIL);
        QueryTerminalCodeRequest queryTerminalCodeRequest = JSONUtil.readParams(commonRequest.getData(),
                QueryTerminalCodeRequest.class);
        if (queryTerminalCodeRequest == null) {
            resp.setMsg("Request or token params validation failed");
        } else {
            resp.setMsg("Please check the qrcode format");
            QueryTerminalCodeResponse queryTerminalCodeResponse = new QueryTerminalCodeResponse();
            String qRCode = queryTerminalCodeRequest.getQRCode();
            if (null != qRCode) {
                String[] terminalId = qRCode.split("=");
                if (terminalId.length == 2) {
                    resp.setRet(EvcsConst.RET_SUCC);
                    resp.setMsg("success");
                    queryTerminalCodeResponse.setTerminalCode(terminalId[1]);
                    resp.setData(JSONUtil.toJSONString(queryTerminalCodeResponse));
                }
            }
        }
        return resp;
    }

}
