package com.cyl.manager.staff.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyl.manager.staff.domain.Staff;
import com.cyl.manager.staff.domain.StaffWechat;
import com.cyl.manager.staff.mapper.StaffWechatMapper;
import com.cyl.manager.staff.service.IStaffService;
import com.cyl.manager.staff.service.IStaffWechatService;
import com.cyl.manager.ums.domain.Member;
import com.cyl.manager.ums.domain.MemberWechat;
import com.cyl.wechat.WechatPayData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.sql.Wrapper;

@Service
@Slf4j
public class StaffWechatServiceImpl extends ServiceImpl<StaffWechatMapper, StaffWechat> implements IStaffWechatService {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IStaffService staffService;

    private static String LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=#{APPID}&secret=#{SECRET}&js_code=#{JSCODE}&grant_type=authorization_code";


    public JSONObject getSessionId(String code) {
        String url = LOGIN_URL.replace("#{APPID}", WechatPayData.staffAppId)
                .replace("#{SECRET}", WechatPayData.staffSecret)
                .replace("#{JSCODE}", code);
        log.info("获取openid，url：{}", url);
        try {
            ResponseEntity<String> res = restTemplate.getForEntity(url, String.class);
            String body = res.getBody();
            if (com.ruoyi.common.utils.StringUtils.isEmpty(body)) {
                throw new Exception("获取openid出错");
            }
            return JSONObject.parseObject(body);
        } catch (Exception e) {
            log.error("获取openid报错", e);
            return null;
        }
    }

    @Override
    public Staff isRegister(String openId) {
        if (StringUtils.isEmpty(openId)) {
            return null;
        }
        LambdaQueryWrapper<StaffWechat> wrapper
                = Wrappers.lambdaQuery(StaffWechat.class).eq(StaffWechat::getOpenid, openId);
        StaffWechat staffWechat = this.getOne(wrapper);
        if(ObjectUtil.isNull(staffWechat)){
            return null;
        }

        // 2、查询员工是否注册
        Staff staff = staffService.getById(staffWechat.getStaffId());
        if(ObjectUtil.isNull(staff)){
            return null;
        }
        return staff;
    }
}
