package com.example.demo.module.user;

import com.example.demo.common.GlobalRoot;
import com.example.demo.common.MD5Tool;
import com.example.demo.common.RequestResult;
import com.example.demo.module.login.LoginToken;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import pers.jc.sql.SQL;

@CrossOrigin
@RestController
@RequestMapping("/gameUser")
public class GameUserController {

    @PostMapping("/savePhone")
    public RequestResult savePhone(String token, String phone, long timestamp, String sign) {
        RequestResult requestResult = new RequestResult();
        LoginToken loginToken = LoginToken.parseClientToken(token);
        if (!loginToken.isMD5SignRight()) {
            requestResult.setFailCode();
            return requestResult;
        }
        boolean pass = MD5Tool.makeMD5(phone + "~happy~" + timestamp).equals(sign);
        if (pass) pass = System.currentTimeMillis() - timestamp < 30 * 1000;
        if (!pass) {
            requestResult.setFailCode();
            return requestResult;
        }
        int count = GlobalRoot.db.update(new SQL(){{
            UPDATE("user_info");
            SET("phone = " + PARAM(phone));
            WHERE("id = " + PARAM(loginToken.uid));
        }});
        if (count <= 0) requestResult.setFailCode();
        return requestResult;
    }

    @PostMapping("/saveEmail")
    public RequestResult saveEmail(String token, String email, long timestamp, String sign) {
        RequestResult requestResult = new RequestResult();
        LoginToken loginToken = LoginToken.parseClientToken(token);
        if (!loginToken.isMD5SignRight()) {
            requestResult.setFailCode();
            return requestResult;
        }
        boolean pass = MD5Tool.makeMD5(email + "~happy~" + timestamp).equals(sign);
        if (pass) pass = System.currentTimeMillis() - timestamp < 30 * 1000;
        if (!pass) {
            requestResult.setFailCode();
            return requestResult;
        }
        int count = GlobalRoot.db.update(new SQL(){{
            UPDATE("user_info");
            SET("email = " + PARAM(email));
            WHERE("id = " + PARAM(loginToken.uid));
        }});
        if (count <= 0) requestResult.setFailCode();
        return requestResult;
    }
}
