package com.diagbot.aop;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diagbot.entity.MedNewsNotice;
import com.diagbot.entity.SysUser;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.enums.NewsNoticeTypeEnum;
import com.diagbot.facade.MedNewsNoticeFacade;
import com.diagbot.facade.SysUserFacade;
import com.diagbot.util.DateUtil;
import com.diagbot.util.HttpUtils;
import com.diagbot.util.StringUtil;
import com.diagbot.util.SysUserUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Description:核查处理
 * @Author: songxl
 * @time: 2022/4/12 14:18
 */

@Aspect
@Component
public class CheckInfoAspect {
    @Autowired
    private MedNewsNoticeFacade medNewsNoticeFacade;
    @Autowired
    private SysUserFacade sysUserFacade;

    // 操作配置织入点
    @Pointcut("execution(public * com.diagbot.web.MedCheckInfoController.distributionJobs(..))")
    public void checkPointCut() {
    }

    /**
     * 操作后执行
     *
     * @param joinPoint
     * @param jsonResult
     * @Return void
     */
    @AfterReturning(pointcut = "checkPointCut()", returning = "jsonResult")
    public void operAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        try {
            //获取请求入参
            String params = getRequestParams(joinPoint);
            if (StringUtils.isNotBlank(params)) {
                //存储消息通知
                saveNewsNotice(params);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 存储消息通知
     *
     * @param params
     * @Return void
     */
    private void saveNewsNotice(String params) {
        //参数处理
        MedNewsNotice newsNotice = paramHandler(params);
        if (newsNotice != null) {
            medNewsNoticeFacade.save(newsNotice);
        }
    }

    /**
     * 参数处理
     *
     * @param params
     * @Return java.lang.String
     */
    private MedNewsNotice paramHandler(String params) {
        if (StringUtil.isNotEmpty(params) && "{".equals(params.substring(0, 1))) {
            JSONObject paramJSON = JSONObject.parseObject(params);
            if (paramJSON.getJSONArray("behospitalCodes") == null
                    || StringUtil.isBlank(paramJSON.getString("checkId"))
                    || StringUtil.isBlank(paramJSON.getString("distributionType"))
                    || StringUtil.isBlank(paramJSON.getString("checkName"))) {
                return null;
            }
            //获取分配者用户名
            SysUser user = sysUserFacade.getOne(new QueryWrapper<SysUser>()
                    .eq("is_deleted", IsDeleteEnum.N.getKey())
                    .eq("id", SysUserUtils.getCurrentPrincipleID())
                    .eq("status", 1));
            if (user != null) {
                StringBuffer out = new StringBuffer();
                out.append(paramJSON.getString("checkName"))
                        .append("您好：\r\n")
                        .append("您有")
                        .append(paramJSON.getJSONArray("behospitalCodes").size());
                MedNewsNotice newsNotice = new MedNewsNotice();
                newsNotice.setReceiver(paramJSON.getString("checkId"));
                newsNotice.setType(NewsNoticeTypeEnum.CHECK_NEWS_WORK.getKey());
                newsNotice.setGmtCreate(DateUtil.now());
                newsNotice.setCreator(SysUserUtils.getCurrentPrincipleID() == null ? "0" : SysUserUtils.getCurrentPrincipleID());
                newsNotice.setHospitalId(SysUserUtils.getCurrentHospitalID() == null ? 0l : Long.parseLong(SysUserUtils.getCurrentHospitalID()));
                if ("0".equals(paramJSON.getString("distributionType"))) {
                    newsNotice.setTitle("待核查质控任务提醒");
                    out.append("条来自")
                            .append(user.getLinkman())
                            .append("分配的待核查质控任务，请及时完成病历核查！");
                } else {
                    newsNotice.setTitle("待核查质控任务被移除提醒");
                    out.append("条待核查的质控任务已被")
                            .append(user.getLinkman())
                            .append("移除，请知悉！");
                }
                newsNotice.setNews(out.toString());
                return newsNotice;
            }
        }
        return null;
    }


    /**
     * /**
     * 获取请求的参数
     *
     * @param joinPoint
     * @Return java.lang.String
     */
    private String getRequestParams(JoinPoint joinPoint) throws Exception {
        Map<String, String[]> map = HttpUtils.getHttpServletRequest().getParameterMap();
        if (MapUtils.isNotEmpty(map)) {
            String params = JSONObject.toJSONString(map);
            return params;
        } else {
            Object args = joinPoint.getArgs();
            if (null != args) {
                return argsArrayToString(joinPoint.getArgs());
            }
        }
        return "";
    }

    /**
     * 参数拼装
     *
     * @param paramsArray
     * @Return java.lang.String
     */
    private String argsArrayToString(Object[] paramsArray) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (int i = 0; i < paramsArray.length; i++) {
                if (null != (paramsArray[i])) {
                    Object jsonObj = JSONObject.toJSONString(paramsArray[i]);
                    params += jsonObj.toString() + " ";
                }
            }
        }
        return params.trim();
    }
}


