package com.gree.mall.miniapp.logic.common;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.gree.mall.miniapp.constant.Constant;
import com.gree.mall.miniapp.logic.common.outside.WechatLogic;
import com.gree.mall.miniapp.plus.entity.User;
import com.gree.mall.miniapp.plus.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Service
@Slf4j
public class EventLogic {

    @Resource
    UserService userService;
    @Resource
    RedisLockRegistry redisLockRegistry;
    @Autowired
    WechatLogic wechatLogic;

    /**
     * 订阅绑定推荐人
     * @param params
     * @throws Exception
     */
    public void scanBringQrcode(Map<String, String> params,String appid) throws Exception {
        String eventKey = params.get("EventKey");
        String mpOpenId = params.get("FromUserName");

        if (eventKey.contains("qrscene_")) {
            eventKey = eventKey.replace("qrscene_", "");
        }

        User workerUser = userService.lambdaQuery()
                .eq(User::getUserId, eventKey)
                .last("limit 1")
                .one();

        if (Objects.isNull(workerUser)) {
            log.error("扫二维码关注公众号未找到师傅userId: " + eventKey);
            return;
        }

        String key = Constant.RedisPrefix.LOCK_AUTH + ":" + mpOpenId;
        Lock obtain = redisLockRegistry.obtain(key);
        if (!obtain.tryLock(2, TimeUnit.SECONDS)) {
            log.error("添加user锁失败, 师傅userId: " + eventKey + ", 用户openid: " + mpOpenId);
            return;
        }

        try {
            //如果用户不存在则新注册
            User user = userService.lambdaQuery()
                    .eq(User::getMpOpenId, mpOpenId)
                    .eq(User::getCompanyWechatId, workerUser.getCompanyWechatId())
                    .one();
            if (user == null) {
                user = new User();
                user.setUserId(IdWorker.getIdStr())
                        .setNickName("微信用户_" + RandomUtil.randomNumbers(4))
                        .setLastLoginTime(new Date())
                        .setOpenId(mpOpenId)
                        .setMpOpenId(mpOpenId)
                        .setFirstServiceId(workerUser.getUserId())
                        .setFirstServiceTime(new Date())
                        .setServiceId(workerUser.getUserId())
                        .setLastLoginTime(new Date())
                        .setCreateTime(new Date())
                        .setCompanyWechatId(workerUser.getCompanyWechatId())
                        .setCompanyName(workerUser.getCompanyName())
                        .insert();
            } else {
                if (StringUtils.isBlank(user.getFirstServiceId())) {
                    user.setFirstServiceId(workerUser.getUserId())
                            .setFirstServiceTime(new Date())
                            .setServiceId(workerUser.getUserId())
                            .setServiceTime(new Date())
                            .setIsExchangeCode(true)
                            .updateById();
                }
            }
        }finally {
            obtain.unlock();
        }
    }



    public String receText(String toUser,String fromUser,String appid,Integer createTime){

        String content = wechatLogic.getZdhf(appid);

//        String content = "Hi，您来啦-点击<a href=\"https://sxbh5.zfire.top/packageHome/pages/service/troubleshoot?appid="+appid+"\">【故障自查】</a>获取家电报修、使用情况贴心服务！-点击<a href=\"https://sxbh5.zfire.top/pages/goods/index?appid="+appid+"\">【家电商城】</a>家电商品、家电服务优惠抢先购！佳禾兴平台售修一站式服务竭诚为您提供更优质、舒适的服务！";
        //String content = "hello";
        String xmlStr = "<xml>\n" +
                "  <ToUserName><![CDATA["+toUser+"]]></ToUserName>\n" +
                "  <FromUserName><![CDATA["+fromUser+"]]></FromUserName>\n" +
                "  <CreateTime>"+createTime+"</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA["+content+"]]></Content>\n" +
                "</xml>";
        return xmlStr;
    }


}
