package psdi.app.iface.oa;

import com.alibaba.fastjson.JSONObject;
import com.dbms.dbcon.DBCon;
import com.dbms.dbcon.QueryResult;
import psdi.app.iface.comm.AESUtil;
import psdi.security.ConnectionKey;
import psdi.server.MXServer;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.UUID;

import static psdi.app.iface.comm.AESUtil.createCiphertext;

/**
 * OA获取EAM提供的token
 * @author liuxingqiang
 */
@Path("/singleSign")
public class Eam2OAService {
    @POST
    @Path("/getToken")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public JSONObject getToken(String received) {
        final String eamAppid= "OA2EAMIFACE";//EAM颁布的appid
        JSONObject returnDate = new JSONObject();
        JSONObject jsonObject = JSONObject.parseObject(received);
        String appid = jsonObject.getString("appid");//appid
        String secret = jsonObject.getString("secret");//secret 密钥
        try {
            if(eamAppid.equals(appid)){
                String secretJM = AESUtil.getPlaintext(secret);//解密:0113290-OA2EAMIFACE
                String userid = secretJM.substring(0,secretJM.indexOf("-"));
                //去数据库查询该员工是否存在
                String sql = "select USERID,STATUS from MAXUSER where userid='"+userid+"'";
                ConnectionKey connectionKey = MXServer.getMXServer().getSystemUserInfo().getConnectionKey();
                QueryResult sqlList = DBCon.runQuery(sql.toString(), connectionKey);
                if (sqlList.size()>0) {
                    String tokenMW = String.valueOf(UUID.randomUUID());
                    String token = createCiphertext(tokenMW);//生成token值，将token值存起来
                    returnDate.put("code","0");//响应码 0：成功
                    returnDate.put("msg", "success");//相应信息
                    returnDate.put("status", "true");//相应状态：成功：true
                    returnDate.put("token", token);//token值
                    returnDate.put("expirationtime", "7200");//token的过期时间设置（2小时）单位：秒
                } else {
                    returnDate.put("code","1");
                    returnDate.put("msg", "failure");
                    returnDate.put("status", "false");
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return returnDate;
    }

}