package com.jzdsh.auto.biz;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jzdsh.auto.model.*;
import com.jzdsh.util.Api;
import com.jzdsh.util.CommonCons;
import com.jzdsh.util.MapUtils;
import com.jzdsh.util.SM4;
import com.jzdsh.vo.UserStatus;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;

/**
 * @ProjectName: auto
 * @Package: com.jzdsh.auto.biz
 * @ClassName: UserInfoService
 * @Author: Jzdsh
 * @Description:
 * @Date: 2020/3/20 15:59
 * @Version: 1.0
 */
@Log4j2
public class UserInfoService {

    @Inject
    private ShopService shopService;
    @Inject
    private AuthenticationService authService;


    /**
     * @param code
     * @param nickName
     * @param img
     * @return
     */
    @Before(Tx.class)
    public Ret wxLogin(String code, String nickName, String img) {
        try {
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + PropKit.get("appid") + "&secret=" + PropKit.get("secret") + "&js_code=" + code + "&grant_type=authorization_code";
            String json = HttpKit.get(url);
            JSONObject jsonObject = JSONObject.parseObject(json);
            Object errorCode = jsonObject.get("errcode");
            String token;

            if (errorCode != null) {
                log.info("code不合法");
                return Ret.fail("data", Api.fail(jsonObject));
            } else {
                String openid = jsonObject.getString("openid");
                UserInfo user = getByOpenId(openid);
                if (user != null) {
                    token = user.getToken( );
                    if (user.getLongitude( ) != null && !CommonCons.ZERO.equals(user.getLongitude( ))) {
                        MapUtils.getRegeoUrl(user.getLongitude( ) + "," + user.getLatitude( ));
                        String jsonStr = MapUtils.sendGet(url);
                        String province = MapUtils.getProvince(jsonStr);
                        String city = MapUtils.getCity(jsonStr);
                        if (CommonCons.BRACKETS.equals(city)) {
                            city = province;
                        }
                        String district = MapUtils.getDistrict(jsonStr);
                        String street = MapUtils.getAddressNameByGeocoder(jsonStr);
                        user.setProvince(province);
                        user.setCity(city);
                        user.setDistrict(district);
                        user.setStreet(street);
                    }
                    user.setNickName(nickName);
                    user.setImg(img);
                    user.setModifyTime(new Date());
                    user.update( );
                    //保存登录日记
                    addLoginLog(user.getId( ));
                } else {
                    token = new SM4( ).encode(openid, CommonCons.SM4KEY);
                    UserInfo u = new UserInfo( );
                    u.setToken(token);
                    u.setOpenid(openid);
                    u.setRole(CommonCons.ROLE_ZERO + "");
                    u.setStatus(CommonCons.USER_INFO_STATUS_ZERO);
                    u.setNickName(nickName);
                    u.setImg(img);
                    u.setCreateTime(new Date( ));
                    u.setModifyTime(new Date( ));
                    u.save( );
                    //保存登录日志
                    addLoginLog(u.getId( ));
                    //消息提示
                    addMessage(CommonCons.SYSTEM_MESSAGE, CommonCons.SYSTEM_MESSAGE_NEW_USER, u.getId( ));
                }
            }
            return Ret.ok("data", Api.ok(token));
        } catch (Exception e) {
            log.info(e);
        }
        return Ret.fail("data", Api.fail(null));
    }

    /**
     * 根据openid 查找用户信息
     *
     * @param openId
     * @return
     */
    public UserInfo getByOpenId(String openId) {
        try {
            return UserInfo.dao.findFirst("select * from user_info where openid = ?", openId);
        } catch (Exception e) {
            log.info(e);
        }
        return null;
    }

    /**
     * 根据token查询当前用户信息
     *
     * @param token
     * @return
     */
    public UserInfo getByToken(String token) {
        if (StringUtils.isBlank(token)) {
            log.info("token is null!");
            return null;
        }

        try {
            token = token.trim( );
            return UserInfo.dao.findFirst("select * from user_info where token = ?", token);
        } catch (Exception e) {
            log.info("com.jzdsh.auto.biz.UserInfoService.findByToken" + e);
        }
        return null;
    }

    /**
     * 添加登录日志
     *
     * @param uid
     */
    public void addLoginLog(Integer uid) {
        try {
            new LoginLog( ).set("uid", uid).set("loginTime", new Date( )).save( );
        } catch (Exception e) {
            log.info(" 登录日记增加 " + e);
        }
    }

    /**
     * 添加系统消息
     *
     * @param title   消息标题
     * @param content 消息内容
     * @param uid     用户id
     */
    public void addMessage(String title, String content, Integer uid) {
        //系统消息提示
        if (StringUtils.isBlank(title)) {
            title = "系统消息";
        }
        if (StringUtils.isBlank(content)) {
            content = "";
        }
        if (uid == null) {
            return;
        }
        Message ms = new Message( );
        ms.setTitle(title);
        ms.setContent(content);
        ms.setIsRead(CommonCons.MESSAGE_IS_READ_ZERO);
        ms.setCreateTime(new Date( ));
        ms.setUserId(uid);
        ms.save( );
    }

    /**
     * 返回当前用户状态信息
     *
     * @param userId
     * @return
     */
    public UserStatus getUserStatus(Integer userId) {
        UserStatus userStatus = new UserStatus( );
        try {
            Shop shop = shopService.getByUserId(userId);
            Authentication authentication = authService.getByUserId(userId);

            if (shop != null) {
                userStatus.setIsEnter("1");
            }
            // 认证资料的判断

            if (authentication != null) {
                // 判断是否 已上传过资料
                userStatus.setIsAuthInfo("1");
                //判断是否付款
                String isPay = authentication.getIsPay( );
                if (StringUtils.isNotBlank(isPay)) {
                    // 是否已付款
                    userStatus.setIsPay(isPay);
                }
                // 判断审核状态
                String authStatus = authentication.getStatus( );
                if (StringUtils.isNotBlank(authStatus)) {
                    //判断审核状态
                    userStatus.setIsAuthStatus(authStatus);
                }
            }
        } catch (Exception e) {
            log.info(e);
        }
        return userStatus;
    }


    public Ret provider(String s, String s1) {
        Shop  shops = Shop.dao.template("homepage.getProvider").findFirst( );
        return Ret.ok("ok",shops);
    }

    public UserInfo getByUserId(int userId) {
        try {
            return UserInfo.dao.findFirst("select * from user_info where userId = ?", userId);
        } catch (Exception e) {
            log.info(e);
        }
        return null;
    }


}
