package com.tuoheng.admin.service.third.dsp;

import com.alibaba.fastjson.JSONObject;
import com.tuoheng.admin.constant.SystemConstant;
import com.tuoheng.admin.entity.Inspection;
import com.tuoheng.admin.entity.InspectionFile;
import com.tuoheng.admin.entity.QuestionType;
import com.tuoheng.admin.mapper.UserMapper;
import com.tuoheng.admin.service.workorder.generate.GenerateWorkorderService;
import com.tuoheng.common.core.config.common.CommonConfig;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class NoticeWeChatMiniProgramService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 通知微信小程序
     *
     * @param inspection
     * @param questionType
     *
     * @return
     */
    @Transactional
    public void notice(Inspection inspection, QuestionType questionType) {
        log.info("任务发现第一个问题，推送给微信小程序：inspection：{}, questionType:{}", inspection.getId(), questionType);

        String url = CommonConfig.wechatURL +  SystemConstant.API_WEIXIN_SEND_MESSAGE;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("tenantId", inspection.getTenantId());
        jsonObject.put("deptId", inspection.getDeptId());
        jsonObject.put("inspectionId", inspection.getId());
        jsonObject.put("questionName", questionType.getName());
        jsonObject.put("questionDesc", questionType.getContent());
        jsonObject.put("createTime", DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));

        log.info("任务发现第一个问题，推送给微信小程序：url:{}", url);
        log.info("任务发现第一个问题，推送给微信小程序：jsonObject:{}", jsonObject);

        String airPortStr = HttpUtils.doSend(url, jsonObject, null, "POST");
        if (StringUtils.isEmpty(airPortStr)) {
            log.info("任务发现第一个问题，推送给微信小程序：返回数据为空");
            throw new com.aliyun.oss.ServiceException("微信小程序返回数据为空");
        }
        JsonResult jsonResult = JacksonUtil.json2pojo(airPortStr, JsonResult.class);
        if (0 != jsonResult.getCode()) {
            log.info("任务发现第一个问题，推送给微信小程序：返回失败，jsonResult：{}", jsonResult.getMsg());
            throw new ServiceException("推送给微信小程序，返回失败");
        }
        log.info("任务发现第一个问题，推送给微信小程序：成功，inspection：{}, questionType:{}", inspection.getId(), questionType);
    }
}
