package com.ruoyi.web.work.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.work.api.util.AppUtil;
import com.ruoyi.web.work.domain.FollowRecord;
import com.ruoyi.web.work.domain.dto.FollowRecordDto;
import com.ruoyi.web.work.domain.dto.VisitDto;
import com.ruoyi.web.work.domain.vo.FollowRecordVoList;
import com.ruoyi.web.work.domain.vo.VisitVoList;
import com.ruoyi.web.work.mapper.FollowRecordMapper;
import com.ruoyi.web.work.service.IFollowRecordService;
import com.ruoyi.web.work.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lsw
 * @date 2024-07-18
 */
@Service
public class FollowRecordServiceImpl extends ServiceImpl<FollowRecordMapper, FollowRecord> implements IFollowRecordService {
    @Autowired
    private FollowRecordMapper followRecordMapper;

    @Autowired
    IUserService userService;

    @Autowired
    private Environment env;

    @DataScope(deptAlias = "k",userAlias = "k")
    @Override
    public List<FollowRecord> selectList(FollowRecord followRecord) {
        return followRecordMapper.selectList(followRecord);
    }

    @Override
    public AjaxResult detail(Long id) {
        FollowRecord followRecord = getById(id);
        if (followRecord == null || !followRecord.getPatientId().equals(AppUtil.getUser().getPatientId())) {
            return AjaxResult.error("回访不存在或非法操作");
        }
        return AjaxResult.success(followRecord);
    }

    @Override
    public AjaxResult push(FollowRecordDto dto) {
        FollowRecord followRecord = getById(dto.getId());
        if (followRecord == null || !followRecord.getPatientId().equals(AppUtil.getUser().getPatientId())) {
            return AjaxResult.error("回访不存在或非法操作");
        }
        followRecord.setOp(dto.getOp());
        followRecord.setState(1);
        if (!updateById(followRecord)) {
            throw new ServiceException("提交回访记录失败");
        }
        return AjaxResult.success();
    }

    @Override
    public List<VisitVoList> selectVisitList(VisitDto dto) {
        return followRecordMapper.selectVisitList(dto);
    }

    @Override
    public List<FollowRecordVoList> selectAppList(FollowRecord followRecord) {
        return followRecordMapper.selectAppList(followRecord);
    }

    @Override
    public AjaxResult add(FollowRecord followRecord) {
        if (followRecord.getPatientList().size() == 0) {
            return AjaxResult.error("请选择推送的患者");
        }
        List<FollowRecord> followRecordList = new ArrayList<>();
        followRecord.getPatientList().forEach(e -> {
            FollowRecord record = new FollowRecord();
            record.setType(followRecord.getType());
            record.setTemplateName(followRecord.getTemplateName());
            record.setOp(followRecord.getOp());
            record.setPatientId(e.getId());
            record.setPatientName(e.getName());
            followRecordList.add(record);
        });
        if (!saveBatch(followRecordList)) {
            throw new ServiceException("新增回访记录失败");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult read(Long id) {
        FollowRecord followRecord = getById(id);
        if (followRecord == null || !followRecord.getPatientId().equals(AppUtil.getUser().getPatientId())) {
            return AjaxResult.error("复诊提醒不存在或非法操作");
        }
        followRecord.setState(1);
        updateById(followRecord);
        return AjaxResult.success();
    }

    @Override
    public void sendMessage(FollowRecord record) {
        JSONObject jsonObject = JSONUtil.parseObj(HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + env.getProperty("wx.appid") + "&secret=" + env.getProperty("wx.appSecret")));
        JSONObject body = new JSONObject();
        body.set("appid", env.getProperty("wx.appid"));
        JSONObject content = new JSONObject();
        //复诊提醒
        if (record.getType() == 0) {
           /* User user = userService.getById(record.getPatientId);
            body.set("touser", user.getOpenId());
            body.set("template_id", "PtdKbqfzmpvGsJPx_YekDX4-cljbhOXcvoUB3XJaVLg");
            body.set("page", "pages/user/money/index");
            content.set("amount3", new JSONObject().set("value", pay.getMoney() + "元"));//提现金额
            content.set("character_string4", new JSONObject().set("value", pay.getNums()));//交易单号
            content.set("time2", new JSONObject().set("value", DateUtils.getTime())); //提现时间*/
        }
        //随访提醒
        if (record.getType() == 1) {
           /* User user = userService.getById(pay.getUserId());
            body.set("touser", user.getOpenId());
            body.set("template_id", "NIqSQq0j765o9Iz9gMiSelnuxMgPIPeCnk3lvEnWJlo");
            body.set("page", "pages/user/money/index");
            content.set("amount3", new JSONObject().set("value", pay.getMoney() + "元"));//提现金额
            content.set("character_string4", new JSONObject().set("value", pay.getNums()));//交易单号
            content.set("thing5", new JSONObject().set("value", pay.getMsg())); //失败原因
            content.set("time2", new JSONObject().set("value", DateUtils.getTime())); //提现时间*/
        }
        body.set("data", content);
        String result = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + jsonObject.getStr("access_token"), body.toString());
        System.out.println("body：" + body);
        System.out.println("小程序订阅消息：" + result);
    }
}
