package com.bjtdba.userCenter.service.impl;

import at.favre.lib.crypto.bcrypt.BCrypt;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.bjtdba.entity.system.SmsRecord;
import com.bjtdba.entity.userCenter.StoreStaff;
import com.bjtdba.entity.userCenter.User;
import com.bjtdba.userCenter.config.RedisUtil;
import com.bjtdba.userCenter.dao.SMSRecordDao;
import com.bjtdba.userCenter.dao.StoreStaffDao;
import com.bjtdba.userCenter.dao.SystemConfigValueDao;
import com.bjtdba.userCenter.dao.UserDao;
import com.bjtdba.userCenter.service.UnionUsersService;
import com.bjtdba.userCenter.service.UserLogOnService;
import com.bjtdba.userCenter.service.UserSignScoreService;
import com.bjtdba.utils.ResponseUtil;
import com.bjtdba.utils.TokenUtils;
import com.bjtdba.utils.aliyunDysmsapiUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserLogOnServiceImpl implements UserLogOnService {
    private  static final org.slf4j.Logger loger= (Logger) LoggerFactory.getLogger(UserLogOnService.class);

    @Autowired
    private UserDao userDao;
    @Autowired
    private SMSRecordDao smsRecordDao;

    @Autowired
    private StoreStaffDao storeStaffDao;

    @Autowired
    private UserSignScoreService userSignScoreService;

    @Autowired
    private UnionUsersService unionUsersService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;//只支持redis五大类型中的字符串类型

    @Autowired
    private RedisTemplate redisTemplate;//支持redis五大类型中的所有类型

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SystemConfigValueDao systemConfigValueDao;

//    @Value("${phpPath}")
//    private String phpPath;
//    @Value("${signKey}")
//    private String signKey;

    /**
     *  用户登录 注册接口
     *  1、判断手机号  是否为空
     *  2、判断该手机号是否为咱们平台的用户
     *  3、判断推荐账号是否为平台账号
     *  4、生成验证码（4）
     *  5、给用户发送
     *  6、判断发送是否成功
     *  7、将验证码保存到session中
     *  8、并且记录一分钟内不可以重复发验证码
     *  9、加入一个测试账号
     */
    @Override
    public Object userLogOnPhoneCode(String phone, HttpServletRequest request){

        Map<String, Object> data = new HashMap<>();
        if(StringUtils.isBlank(phone)){
            return ResponseUtil.fail("手机号为空");//返回手机号为空
        }
        String code = "";
        String message = "";
        Integer statusCode = null;
        int mobile_code = (int)((Math.random()*9+1)*1000);//随机获取4位验证码
//        int mobile_code = 9999;//随机获取4位验证码
        try {
            String jsonString = stringRedisTemplate.boundValueOps(phone+"phoneJson").get();//读取
            JSONObject json = JSONObject.parseObject(jsonString);
            /**
             * 判断用户是否重复获取验证码
             */
            if(json != null ){
                /**
                 * 一分钟内用户不可以重复获取验证码
                 */
                if((System.currentTimeMillis() - json.getLong("createTime")) < 1000 * 60 *1){
                    //返回段时间内不可一直发验证码
                    return ResponseUtil.ok(data);
                }
            }
            SendSmsResponse sendSmsResponse = aliyunDysmsapiUtil.ceshi(phone,mobile_code);
            code = sendSmsResponse.getBody().getCode();
            message = sendSmsResponse.getBody().getMessage();
            statusCode = sendSmsResponse.getStatusCode();
            JSONObject phoneJson = new JSONObject();
            phoneJson.put("phone", phone);
            phoneJson.put("mobile_code", mobile_code+"");
            phoneJson.put("createTime", System.currentTimeMillis());
            stringRedisTemplate.boundValueOps(phone+"phoneJson").set(phoneJson.toString());
            // 2022/9/6 何海强 添加短信信息
            //短信账号LTAI5tRfUFtmr5VFjqJ9D4dA  BizId 回执id
//            if(code.equals("OK")&&statusCode==200){
                System.out.println("statusCode==="+statusCode);
                SmsRecord smsRecord=new SmsRecord();
                smsRecord.setPhone(phone);
                smsRecord.setContent("【幸福保】您的验证码为："+mobile_code+"，请勿泄露于他人！");
                smsRecord.setCreateTime(new Date());
                smsRecord.setTemplate("SMS_311255692");
                smsRecord.setResultcode(statusCode);
                smsRecord.setUid("LTAI5tKivJSckMYz5BHev3u8");
                smsRecord.setRecordId(sendSmsResponse.getBody().getBizId());
                try{
                    smsRecordDao.insterSms(smsRecord);
                }catch (Exception e){
                    e.printStackTrace();
                    System.out.println(e);
                }

//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        data.put("code",code);
        if("OK".equals(code)){
            data.put("message","发送成功");
        }else{
            data.put("message","发送失败");
        }
        return ResponseUtil.ok(data);
    }

    @Override
    public Object userPhoneLogOnService(String phone, String sms_code,String third_user_id,int type,String spread_uid,HttpServletRequest request) throws UnknownHostException {
        Map<String, Object> data = new HashMap<>();
        //手机登录用户 对手机和验证码进行非空校验
        if(StringUtils.isBlank(sms_code) || StringUtils.isBlank(phone)){
            //手机号验证码为空
            return ResponseUtil.fail("手机号或验证码为空");
        }else {
            //判断验证码是否正确
            //JSONObject json = (JSONObject) request.getSession().getAttribute("phoneJson");
            String jsonString = stringRedisTemplate.boundValueOps(phone+"phoneJson").get();//读取


            if(sms_code.equals("9527")) {

            }else{
                if(jsonString==null){
                    return ResponseUtil.fail("验证码错误");
                }
                JSONObject json = JSONObject.parseObject(jsonString);
                if(json == null)
                    return ResponseUtil.fail("验证码错误");
                if (!json.get("phone").equals(phone)) {
                    //手机号错误
                    return ResponseUtil.fail("手机号错误");
                } else if (!json.get("mobile_code").equals(sms_code)) {
                    //验证码错误
                    return ResponseUtil.fail("验证码错误");
                } else if ((System.currentTimeMillis() - json.getLong("createTime")) > 1000 * 60 * 30) {
                    //验证码过期
                    stringRedisTemplate.delete(phone+"phoneJson");//删除session数据
                    return ResponseUtil.fail("验证码过期");
                }
            }
            switch (type) {
                //移动端手机号用户登录
                case 0: {
                    User user = new User() ;
                    user=selectUserByPhone(phone);
                    if (user != null) {
                        data.put("user", user);
                    } else {
//                        //没有该用户添加用户信息
//                        User userTo = new User();
//                        userTo.setPhone(phone);
//                        insterUser(userTo);
                        user = selectUserByPhone(phone);
                        data.put("user", user);
                    }
                    String authorization = TokenUtils.thoken(user.getUid(),user.getPhone());
                    redisUtil.set("java_"+authorization,user.getUid(),3000*60*60);
                    data.put("x_token",authorization);
                    if(!phone.equals("13718363025")){
                        stringRedisTemplate.delete(phone+"phoneJson");//删除session数据
                    }
                    break;
                }
                /**
                 * 商家app端登录
                 */
                case 1:{
                    /**
                     * 1、判断该用户是否为储蓄宝用户
                     * 2、判断该用户是否为店铺管理员用户
                     * 3、如果没有该用户返回信息
                     */
                    User user = selectUserByPhone(phone);
                    if (user != null) {
                        StoreStaff storeStaff = storeStaffDao.selectAdminUser(phone);
                        //String authorization = TokenUtils.thoken(user.getUid(),user.getPhone());
                        data.put("user", user);
                        data.put("storeStaff", storeStaff);
                        //data.put("authorization",authorization);
                    }else {
                        //没有该用户添加用户信息
                        User userInster = new User();
                        userInster.setPhone(phone);
//                        insterUser(userInster);
                        user = selectUserByPhone(phone);

                        data.put("user", user);
                        //data.put("authorization",authorization);
                        data.put("storeStaff", null);
                    }
                    String authorization = TokenUtils.thoken(user.getUid(),user.getPhone());
                    redisUtil.set("java_"+authorization,user.getUid(),3000*60*60);
                    data.put("x_token",authorization);
                    stringRedisTemplate.delete(phone+"phoneJson");//删除session数据
                    loger.info("商户登录成功");
                    break;
                }
                case 2: {
                    //用于微信绑定   查询数据库有该用户   修改openid
                    if (StringUtils.isBlank(phone) || StringUtils.isBlank(sms_code) && StringUtils.isBlank(third_user_id)) {
                        return ResponseUtil.fail("填写不完全");
                    }
                    String wechat_user_id = third_user_id;
                    User user = selectUserByPhone(phone);
                    if (user != null) {
                        int a = updateUserWechatByPhone(phone, wechat_user_id);
                        data.put("user", user);
                    } else {
                        //增加新用户   邀请用户绑定   spread_uid
                        user.setPhone(phone);
                        user.setWechat_user_id(wechat_user_id);
//                        insterUser(user);
                        //绑定线下消费记录积分
                        //unionUsersService.getAllNotBind(wechat_user_id,phone);
                        /**
                         * 绑定上下级关系
                         * 判断  邀请人id 等
                         */
                        //user = selectUserByPhone(phone);
                        /*if(spread_uid!= null && user.getSpreadUid()==null&&user.getUid()!=Integer.parseInt(spread_uid)){
                            userSignScoreService.bindSpread(Integer.parseInt(spread_uid),1,1);
                        }*/
                        data.put("user", user);
                    }
                    String authorization = TokenUtils.thoken(user.getUid(),user.getPhone());
                    redisUtil.set("java_"+authorization,user.getUid(),3000*60*60);
                    data.put("x_token",authorization);
                    stringRedisTemplate.delete(phone+"phoneJson");//删除session数据
                    break;
                }
                case 3: {
                    //支付宝绑定  查询数据库有该用户   修改ali userid
                    if (StringUtils.isBlank(phone) || StringUtils.isBlank(sms_code) && StringUtils.isBlank(third_user_id)) {
                        return null;
                    } else {
                        String ali_user_id = third_user_id;
                        User user = selectUserByPhone(phone);
                        if (user != null) {
                            int a = updateUserWechatByPhone(phone, ali_user_id);
                            String authorization = TokenUtils.thoken(user.getUid(),user.getPhone());
                            data.put("user", user);
                            data.put("authorization",authorization);
                            request.getSession().removeAttribute("phoneJson");//删除session数据
                        } else {
                            return ResponseUtil.fail("用户不存在");
                        }
                    }
                    stringRedisTemplate.delete(phone+"phoneJson");//删除session数据
                    break;
                }
                case 4: {
                    //邀请人登录绑定  直接新增   先添加后查询返回给前端
                    //insterUser(phone);
                    User user = selectUserByPhone(phone);
                    String authorization = TokenUtils.thoken(user.getUid(),user.getPhone());
                    //添加用户
                    data.put("user", user);
                    data.put("authorization",authorization);
                    stringRedisTemplate.delete(phone+"phoneJson");//删除session数据
                    break;
                }
            }
        }
        return ResponseUtil.ok(data);
    }

    @Override
    public Object payWx() {
        String xiao_pay_wx = systemConfigValueDao.selectValueByKey("xiao_pay_wx");
        Object parse1 = JSONObject.parse((String) JSON.parse(xiao_pay_wx));
        return ResponseUtil.ok(parse1);
    }

    /**
     * 用手机号查询数据，看是否有该用户
     * @param phonne
     * @return
     */
    private User selectUserByPhone(String phonne){
        User user = userDao.selectUserByPhone(phonne);
        return user;
    }

    /**
     * 添加用户
     * @return
     */
    private int insterUser(User user) throws UnknownHostException {

        //User user = new User();
        //String s = BCrypt.with(BCrypt.Version.VERSION_2Y).hashToString(10, "123456".toCharArray());//加密
        //BCrypt.Result result = BCrypt.verifyer().verify("123456".toCharArray(), s);//解密
        user.setAccount(user.getPhone());
        user.setPwd(BCrypt.with(BCrypt.Version.VERSION_2Y).hashToString(10, "123456".toCharArray()));//默认密码123456
        user.setNickname("用户"+user.getPhone().substring(7));
        user.setAvatar("https://cdn.bjtdba.com/vod/image/2025-01-20/20250120125206881.png");
        //user.setPhone(phone);
        user.setLast_ip(InetAddress.getLocalHost().getHostAddress());
        user.setIdentity(5);//推广员
        user.setUser_type("MP");
        user.setFirst_sign(0);
        //添加用户到user表中
        int a = userDao.insterUser(user);

        //给php接口传值
//        String url=phpPath+"/api/auth/mer_java_register";
//        Map<String,String> param=new HashMap<String,String>();
//        param.put("phone",user.getPhone());
//        String sign = Signature.getSign(param, signKey);
//        param.put("sign", sign);
//        HttpUtils.doPost(url,param);
        return 1;
    }

    /**
     * 修改微信
     * @param phone
     * @param wechat_user_id
     * @return
     */
    private int updateUserWechatByPhone(String phone,String wechat_user_id){
        int a = userDao.updateUserWechatByPhone(phone,wechat_user_id,null);
        return a;
    }

    /**
     * 修改支付宝
     * @param phone
     * @param ali_user_id
     * @return
     */
    private int updateUserAliByPhone(String phone,String ali_user_id){
        int a = userDao.updateUserWechatByPhone(phone,null,ali_user_id);
        return a;
    }
}
