package org.jeecg.modules.alUser.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.hibernate.cache.spi.support.CollectionNonStrictReadWriteAccess;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.alUser.service.UserService;
import org.jeecg.modules.hanHaiMember.entity.HanHaiMember;
import org.jeecg.modules.hanHaiMember.service.IHanHaiMemberService;
import org.jeecg.modules.postBean.ReqUserRole;
import org.jeecg.modules.postBean.UserLoginModel;
import org.jeecg.modules.userRole.entity.TbUserRole;
import org.jeecg.modules.userRole.service.ITbUserRoleService;
import org.jeecg.modules.utils.ValidateTool;
import org.jeecg.modules.webBanner.entity.WebBanner;
import org.jeecg.modules.webBanner.service.IWebBannerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class UserServiceImpl implements UserService {

    @Resource
    private IWebBannerService webBannerService;
    @Autowired
    private IHanHaiMemberService iHanHaiMemberService;
    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private ITbUserRoleService tbUserRoleService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<JSONObject> login(UserLoginModel userLoginModel) {


        Result<JSONObject> result = new Result<JSONObject>();
        String username = userLoginModel.getUsername();
        String password = userLoginModel.getPassword();
        //1. 校验用户是否有效
        LambdaQueryWrapper<HanHaiMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HanHaiMember::getAccount, username);
        HanHaiMember one = iHanHaiMemberService.getOne(queryWrapper);
        if (ValidateTool.isNull(one)) {
            result.error500("用户不存在");
        }
        if (userLoginModel.getLoginModel() == 0) {
//            账号密码登陆
            //2. 校验用户名或密码是否正确
            String userpassword = PasswordUtil.encrypt(username, password, one.getPasswordSalt());
            String syspassword = one.getPassword();
            if (!syspassword.equals(userpassword)) {
                result.error500("用户名或密码错误");
                return result;
            }

        } else {
            if (ValidateTool.isNull(userLoginModel.getCaptcha())) {
                return Result.error("请填写验证码");
            }
            String smscode = userLoginModel.getCaptcha();
            //手机验证码登陆
            Object code = redisUtil.get(CommonConstant.PHONE_CODE + username);
            if (ValidateTool.isNull(code)) {
                result.error500("手机验证码错误");
            }
            if (!smscode.equals(code)) {
                result.error500("手机验证码错误");
                return result;
            }
            redisUtil.del(CommonConstant.PHONE_CODE + username);
        }
        //用户登录信息
        // 生成token
        String token = JwtUtil.sign(username, one.getPassword());
        //不返回关键信息
        one.setPasswordSalt(null);
        one.setPassword(null);
        // 设置token缓存有效时间
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
        JSONObject obj = new JSONObject();
        obj.put("token", token);
        obj.put("userInfo", one);
        LambdaQueryWrapper<TbUserRole> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        objectLambdaQueryWrapper.eq(TbUserRole::getUserId,one.getId()).
                eq(TbUserRole::getRole,0).eq(TbUserRole::getAuditStatus,1);
        TbUserRole cg= tbUserRoleService.getOne(objectLambdaQueryWrapper);
        LambdaQueryWrapper<TbUserRole> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(TbUserRole::getUserId,one.getId()).
                eq(TbUserRole::getRole,1).eq(TbUserRole::getAuditStatus,1);
        TbUserRole shop= tbUserRoleService.getOne(queryWrapper1);
//        返回采购商身份信息
        obj.put("buy", cg);
//          返回供应商身份信息
        obj.put("shop", shop);
        result.setResult(obj);
        result.setCode(CommonConstant.SC_OK_200);
        result.success("登录成功");
        return result;
    }



    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<JSONObject> reg(UserLoginModel userLoginModel) {
        Result<JSONObject> result = new Result<JSONObject>();

        LambdaQueryWrapper<HanHaiMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HanHaiMember::getAccount, userLoginModel.getUsername());
        HanHaiMember user = iHanHaiMemberService.getOne(queryWrapper);
        if (ValidateTool.isNotNull(user)) {
            return result.error500("用户已注册");
        }
        HanHaiMember newUser = new HanHaiMember();
        newUser.setAccount(userLoginModel.getUsername());
        newUser.setPhone(userLoginModel.getUsername());
        String salt = oConvertUtils.randomGen(8);
        newUser.setPasswordSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(newUser.getAccount(), userLoginModel.getPassword(), salt);
        newUser.setPassword(passwordEncode);
        iHanHaiMemberService.save(newUser);
        //用户登录信息
        // 生成token
        String token = JwtUtil.sign(userLoginModel.getUsername(), passwordEncode);
        // 设置token缓存有效时间
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
        JSONObject obj = new JSONObject();
        obj.put("token", token);
        obj.put("userInfo", newUser);
        result.setResult(obj);
        result.setCode(CommonConstant.SC_OK_200);
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<JSONObject> role(ReqUserRole reqUserRole) {
        Result<JSONObject> result = new Result<JSONObject>();

        //1. 校验用户是否有效
        LambdaQueryWrapper<HanHaiMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HanHaiMember::getAccount, reqUserRole.getUserName());
        HanHaiMember one = iHanHaiMemberService.getOne(queryWrapper);
        if (ValidateTool.isNull(one)) {
            return result.error500("用户不存在");
        }
        //2. 校验用户名或密码是否正确
        String userpassword = PasswordUtil.encrypt(reqUserRole.getUserName(), reqUserRole.getPassword(), one.getPasswordSalt());
        String syspassword = one.getPassword();
        if (!syspassword.equals(userpassword)) {
            result.error500("用户名或密码错误");
            return result;
        }
        //getAuditStatus 0审核中 1 审核通过 2审核未通过

        LambdaQueryWrapper<TbUserRole> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        objectLambdaQueryWrapper.eq(TbUserRole::getUserName,reqUserRole.getUserName()).
                eq(TbUserRole::getRole,reqUserRole.getRole()).in(TbUserRole::getAuditStatus,1,0);
        TbUserRole one1 = tbUserRoleService.getOne(objectLambdaQueryWrapper);
        if (ValidateTool.isNotNull(one1) && one1.getAuditStatus()==0){
            return result.error500("已提交审核，请耐心等候或联系管理员");
        }
        if (ValidateTool.isNotNull(one1) && one1.getAuditStatus()==1){
           return result.error500("已提交审核，请勿重复提交");
        }
        TbUserRole tbUserRole = new TbUserRole();
        BeanUtils.copyProperties(reqUserRole, tbUserRole);
        tbUserRole.setUserId(one.getId());
        tbUserRole.setAuditStatus(0);
        tbUserRoleService.save(tbUserRole);
        JSONObject obj = new JSONObject();
        obj.put("role", tbUserRole);
        result.setResult(obj);
        result.setCode(CommonConstant.SC_OK_200);
        return result;
    }

    //获取首页基础信息
    @Override
    public Result<?> getIndexInfo(){
        Map<String,Object> map=new HashMap<>();
        map.put("title","高端网站定制");

        List list=new ArrayList();
        list.add("企业官网");
        list.add("电商官网");
        list.add("H5官网");
        list.add("小程序");
        map.put("list",list);
        map.put("details","网站定制介绍");
        //获取banner
        List<WebBanner> bannerList = webBannerService.list();
        map.put("bannerList",bannerList);

        return Result.OK(map);
    }









}
