package cn.wise.sc.cement.business.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.wise.sc.cement.business.entity.SysUser;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.LoginUser;
import cn.wise.sc.cement.business.service.ISysUserService;
import cn.wise.sc.cement.business.util.JwtUtil;
import cn.wise.sc.cement.business.util.RedisUtil;
import cn.wise.sc.cement.business.util.weixin.Global;
import cn.wise.sc.cement.business.util.weixin.WeiXinUtil;
import cn.wise.sc.cement.business.util.weixin.WeixinInterfaceUtil;
import cn.wise.sc.cement.business.util.weixin.message.send.BaseMessage;
import cn.wise.sc.cement.business.util.weixin.message.send.Text;
import cn.wise.sc.cement.business.util.weixin.message.send.TextMessage;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class WeiXinService {

    private static Logger log = LoggerFactory.getLogger(WeiXinService.class);
    @Autowired
    private ISysUserService userService;
    @Autowired
    RedisUtil redisUtil;

    @Value("${weixin.corpId}")
    private static String corpId;
    @Value("${weixin.agentId}")
    private static int agentId;
    @Value("${weixin.agentSecret}")
    private static String agentSecret;





    final static String ACCESS_TOKEN = "ACCESS_TOKEN";
    final static String JSAPITICKET = "JSAPITICKET";

    /**
     * 获取登录token 测试服务器部署
     *
     * @param code
     * @return
     */
    public BaseResponse<String> getTestToken(String code) {
        if (StrUtil.isEmpty(code)) {
            return BaseResponse.errorMsg("code为必填项!");
        }
        System.out.println("==================code===================");
        System.out.println(code);
        try {
            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", code);  //暂时用手机号代替code
            SysUser sysUser = userService.getOne(wrapper);
            if (sysUser == null) {
                return BaseResponse.errorMsg("非系统用户不允许登录!");
            }
            if (sysUser.getStatus() == 0) {
                return BaseResponse.errorMsg("用户被禁用!");
            }
            if (sysUser.getIsDelete() == 0) {
                return BaseResponse.errorMsg("用户被删除!");
            }
            //生成token,存入redis
            String token = JwtUtil.createToken(sysUser.getId(), sysUser.getUsername(),
                    sysUser.getName(), sysUser.getPhone());
            System.out.println(token);
            redisUtil.setString(sysUser.getId().toString(), token, 3600);
            return BaseResponse.okData(token);
        } catch (Exception e) {
            return BaseResponse.errorMsg(e.getMessage());
        }
    }

    /**
     * 获取登录token  正式服务器部署
     *
     * @param code
     * @param type PC管理端  APP小程序端
     * @return
     */
    public BaseResponse<String> getToken(String code, String type) {
        if (StrUtil.isEmpty(code)) {
            return BaseResponse.errorMsg("code为必填项!");
        }
        System.out.println("==================code===================");
        System.out.println(code);
        try {
            String accessToken = null;
            if (type.equals("PC")) {
                accessToken = getAccessToken();
            } else if (type.equals("APP")) {
                accessToken = getPCAccessToken();
            } else {
                return BaseResponse.errorMsg("参数错误");
            }
            String param = "access_token=%s&code=%s";
            param = String.format(param, accessToken, code);
            JSONObject jsonObject = WeixinInterfaceUtil.doGet(Global.USERINFOURL, param);
            if (jsonObject.get("errcode").toString().equals("40029")) {
                return BaseResponse.errorMsg("code失效!");
            }
            String UserId = jsonObject.getString("UserId");
            System.out.println("==================UserId===================");
            System.out.println(UserId);
            JSONObject userJson = getUser(accessToken, UserId);
            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", userJson.get("mobile"));
            SysUser sysUser = userService.getOne(wrapper);
            if (sysUser == null) {
                return BaseResponse.errorMsg("非系统用户不允许登录!");
            }
            if (sysUser.getStatus() == 0) {
                return BaseResponse.errorMsg("用户被禁用!");
            }
            if (sysUser.getIsDelete() == 0) {
                return BaseResponse.errorMsg("用户被删除!");
            }
            //生成token,存入redis
            String token = JwtUtil.createToken(sysUser.getId(), sysUser.getUsername(),
                    sysUser.getName(), sysUser.getPhone());
            System.out.println(token);
            redisUtil.setString(sysUser.getId().toString(), token, 3600);
            sysUser.setWxId(UserId);
            userService.updateById(sysUser);
            return BaseResponse.okData(token);
        } catch (Exception e) {
            return BaseResponse.errorMsg(e.getMessage());
        }
    }


    //获取accessToken信息
    public String getAccessToken() {
        try {
            return getToken();
        } catch (Exception e) {
            return null;
        }
    }


    public String getToken() {
        String accessToken;

        if (!redisUtil.existsKey(ACCESS_TOKEN)) {
            String param = "corpid=%s&corpsecret=%s";
            param = String.format(param, corpId, agentSecret);
            JSONObject jsonObject = WeixinInterfaceUtil.doGet(Global.ACCESSTOKENURL, param);
            accessToken = jsonObject.getString("access_token");
            redisUtil.setString(ACCESS_TOKEN, accessToken, 7100);
        }
        return redisUtil.getString(ACCESS_TOKEN) + "";
    }

    //获取accessToken信息
    public String getJsapiTicket() {
        try {
            String accessToken = getToken();
            String jsapiTicket;

            System.out.println("==================accessToken===================");
            System.out.println(accessToken);
            if (!redisUtil.existsKey(JSAPITICKET)) {
                String param3 = "access_token=%s&type=agent_config";
                param3 = String.format(param3, accessToken);
                JSONObject ticketJsonObject = WeixinInterfaceUtil.doGet(Global.userTicket, param3);
                jsapiTicket = ticketJsonObject.getString("ticket");
                redisUtil.setString(JSAPITICKET, jsapiTicket, 7100);
            }
            jsapiTicket = redisUtil.getString(JSAPITICKET) + "";
            return jsapiTicket;
        } catch (Exception e) {
            return null;
        }
    }

    public String getPCAccessToken() {
        try {
            return getToken();
        } catch (Exception e) {
            return null;
        }
    }


    //获取用户信息
    public JSONObject getUser(String accessToken, String userId) {
        try {
            String param = "access_token=%s&userid=%s";
            param = String.format(param, accessToken, userId);
            JSONObject jsonObject = WeixinInterfaceUtil.doGet(Global.USERURL, param);
            System.out.println("==================jsonObject===================");
            System.out.println(jsonObject);
            return jsonObject;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 当前登录用户
     *
     * @return
     */
    public BaseResponse<LoginUser> getLoginUser() {
        LoginUser loginUser = userService.getLoginUser();
        return BaseResponse.okData(loginUser);
    }


    /**
     * 发送消息
     * @param touser    指定接收消息的成员，成员ID列表（多个接收者用‘|’分隔，最多支持1000个）。
     * 特殊情况：指定为”@all”，则向该企业应用的全部成员发送
     * @param content  消息内容，最长不超过2048个字节，超过将截断（支持id转译）
     */
    public  void sendTextMessage(String touser, String content){
        //1.创建文本消息对象
        TextMessage message=new TextMessage();
        //1.1非必需
        message.setTouser(touser);  //不区分大小写
        //textMessage.setToparty("1");
        //txtMsg.setTotag(totag);
        //txtMsg.setSafe(0);

        //1.2必需
        message.setMsgtype("text");
        message.setAgentid(agentId);

        Text text=new Text();
        text.setContent(content);
        message.setText(text);

        //2.获取access_token:根据企业id和通讯录密钥获取access_token,并拼接请求url
//        String accessToken= WeiXinUtil.getAccessToken(corpid, WeiXinParamesUtil.agentSecret).getToken();
        String accessToken = getAccessToken();
        System.out.println("accessToken:"+accessToken);

        //3.发送消息：调用业务类，发送消息
        sendMessage(accessToken, message);
    }


    /**
     * @desc ：0.公共方法：发送消息
     *
     * @param accessToken
     * @param message void
     */
    public void sendMessage(String accessToken,BaseMessage message){

        //1.获取json字符串：将message对象转换为json字符串
        Gson gson = new Gson();
        String jsonMessage =gson.toJson(message);      //使用gson.toJson(user)即可将user对象顺序转成json
        System.out.println("jsonTextMessage:"+jsonMessage);

        //2.获取请求的url
        String url=Global.SENDMESSAGE.replace("ACCESS_TOKEN", accessToken);

        //3.调用接口，发送消息
        JSONObject jsonObject = WeiXinUtil.httpRequest(url, "POST", jsonMessage);
        System.out.println("jsonObject:"+jsonObject.toString());

        //4.错误消息处理
        if (null != jsonObject) {
            if (0 != jsonObject.getInteger("errcode")) {
                log.error("消息发送失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
            }
        }
    }


    public static void main(String[] args) {
        BigDecimal bigDecimal = NumberUtil.toBigDecimal(StrUtil.trim("111 "));
    }

}
