package nccloud.api.uapbd.msg;

import com.alibaba.fastjson.JSONObject;
import nc.bs.dao.DAOException;
import nc.bs.logging.Logger;
import nc.bs.trade.business.HYSuperDMO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pub.msg.CommonMessageVO;
import nc.vo.pub.msg.UserNameObject;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.sm.UserVO;
import nccloud.api.rest.utils.ResultMessageUtil;
import nccloud.bs.pub.pf.PfMessageUtil;
import nccloud.commons.lang.StringUtils;
import nccloud.ws.rest.resource.AbstractNCCRestResource;
import org.json.JSONString;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * 消息发送api
 *
 * @author mzr
 * @date 2025/06/12
 */
@Path("uapbd/msg")
public class MsgResource extends AbstractNCCRestResource {
    private static final String DEFAULT_SENDER = "NC_USER0000000000000";

    public String getModule() {
        return "uapbd";
    }

    private HYSuperDMO superDMO;


    public HYSuperDMO getSuperDMO() {
        if (superDMO == null) {
            superDMO = new HYSuperDMO();
        }
        return superDMO;
    }

    @POST
    @Path("operation/save")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString save(JSONObject jsonObject) {
        String content = (String) jsonObject.get("content");
        String roleId = (String) jsonObject.get("roleId");
        try {
            // 通知消息字段，最大为4000位。
            if (content != null && content.length() > 1500) {
                content = content.substring(0, 1500);
            }

            // 定义接收消息人员信息集合
            ArrayList<UserNameObject> userList = new ArrayList<>();

            // 根据传递的角色查询要发送消息的用户信息
            UserVO[] userVOS = getUserByRole(roleId);
            if (userVOS == null || userVOS.length == 0) {
                return ResultMessageUtil.toJSON(false, "未查询到用户");
            }

            for (UserVO smUser : userVOS) {
                // 用户档案主键
                String cuserid = smUser.getCuserid();
                // 用户名称
                String user_name = smUser.getUser_name();
                // 用户编码
                String user_code = smUser.getUser_code();

                UserNameObject userNameObject = new UserNameObject(user_name);// 用户名称
                userNameObject.setUserCode(user_code);// 用户编码
                userNameObject.setUserPK(cuserid);// 用户档案主键
                userList.add(userNameObject);
            }
            UserNameObject[] users = userList.toArray(new UserNameObject[0]);

            CommonMessageVO commonMessageVO = new CommonMessageVO();
            commonMessageVO.setReceiver(users);
            commonMessageVO.setTitle("BOM变更信息通知");
            commonMessageVO.setSender(DEFAULT_SENDER);
            commonMessageVO.setSendDataTime(new UFDateTime());
            commonMessageVO.setPriority(1);
            commonMessageVO.setMessageContent(content);

            PfMessageUtil.sendNoticeMessage(commonMessageVO);

            return ResultMessageUtil.toJSON(true, "消息发送成功");
        } catch (Exception e) {
            Logger.error("MsgResource-exp:", e);
            return ResultMessageUtil.exceptionToJSON(new BusinessException(e.getMessage(), e));
        }
    }

    /**
     * 查询用户
     */
    private UserVO[] getUserByRole(String roleId) {
        UserVO[] vos = null;
        if (StringUtils.isEmpty(roleId) || "~".equals(roleId)) {
            return null;
        }
        String strWhere = " dr = 0 AND cuserid in (" +
                "select cuserid from sm_user_role where pk_role = '[roleId]' and (disabledate is null or disabledate >= '[now]') " +
                ")";
        strWhere = strWhere.replace("[roleId]", roleId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());
        strWhere = strWhere.replace("[now]", time);
        // NCCForUAPLogger.debug("time = " + time);
        try {
            vos = (UserVO[]) getSuperDMO().queryByWhereClause(UserVO.class, strWhere);
        } catch (DAOException e) {
            Logger.error("MsgResource-getUserByRole-exp:" + e.getMessage());
            ExceptionUtils.wrappBusinessException(e.getMessage());
        }
        return vos;

    }

}
