package com.engine.htxc.tycgsq.web;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Title: ecology-9
 * @Company: 泛微软件
 * @author: K1810027
 * @version: 1.0
 * @CreateDate: 2022-09-05 16:21
 * @Description:通用采购申请相关接口，原来的jsp转java
 * @ModifyLog:
 **/
public class GetDepartmentId {
    @GET
    @Path("/getDepartmentId")
    @Produces({MediaType.TEXT_PLAIN})
    public String getDepartmentId(@Context HttpServletRequest request, @Context HttpServletResponse response){
        String requestid = request.getParameter("requestid");
        JSONObject deptObj = new JSONObject();
        BaseBean bs = new BaseBean();
        HashMap<String, String> map = new HashMap<>();
        try{
            //1.获取用户id
            List<Integer> userList = new ArrayList<>();
            RecordSet userRs = new RecordSet();
            String userSql = "select userid from workflow_currentoperator where requestid = "+requestid+" and nodeid < 0";
            userRs.execute(userSql);
            while (userRs.next()){
                int userid = Util.getIntValue(userRs.getString("userid"));
                userList.add(userid);
            }
            String userIdStr = StringUtils.join(userList, ",");

            if ("".equals(userIdStr)){
                userIdStr = "-1";
            }
            //2.根据用户id获取部门Id
            RecordSet deptrs = new RecordSet();
            String deptSql = "select DISTINCT departmentid from  hrmresource where id in ("+userIdStr+") and status = 1";
            deptrs.execute(deptSql);

            List<Integer> deptIdList = new ArrayList<>();
            while (deptrs.next()){
                int departmentid = Util.getIntValue(deptrs.getString("departmentid"));
                deptIdList.add(departmentid);
            }
            String deptIdStr = StringUtils.join(deptIdList, ",");

            if ("".equals(deptIdStr)){
                deptIdStr = "-1";
            }
            deptObj.put("deptId",deptIdStr);
            map.put("code","200");
            map.put("msg","SUCCESS");
            map.put("data",deptIdStr);
        }catch (Exception e){
            e.printStackTrace();
            map.put("code","500");
            map.put("msg","ERROR");
            map.put("data",e.getMessage());
        }
        return JSONObject.toJSONString(map);
    }
}
