package com.ruoyi.web.controller.system;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.service.DictService;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.pay.domain.bo.PaySubInfoBo;
import com.ruoyi.pay.domain.bo.PaySubPlanBo;
import com.ruoyi.pay.domain.bo.PayTenantBo;
import com.ruoyi.pay.domain.vo.PaySubPlanVo;
import com.ruoyi.pay.domain.vo.PayTenantVo;
import com.ruoyi.pay.service.IPaySubInfoService;
import com.ruoyi.pay.service.IPaySubPlanService;
import com.ruoyi.pay.service.IPayTenantService;
import com.ruoyi.system.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 注册验证
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
public class SysRegisterController extends BaseController {

    private final SysRegisterService registerService;
    private final ISysConfigService configService;
    private final ISysRoleService roleService;
    private final ISysUserService userService;
    private final SysLoginService loginService;
    private final IPaySubInfoService iPaySubInfoService;
    private final IPaySubPlanService iPaySubPlanService;
    private final IPayTenantService iPayTenantService;

    private final DictService dictService;
    /**
     * 用户注册
     */
    @SaIgnore
    @PostMapping("/register")
    public R<Void> register(@Validated @RequestBody RegisterBody user) {
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
            return R.fail("当前系统没有开启注册功能！");
        }
        registerService.register(user);
        return R.ok();
    }
    //用户注册修改为3步：公司注册——》2添加默认角色（公司注册成功后，系统自动添加）——》3添加用户
    /**
     * 公司注册并添加默认角色
     */
    @SaIgnore
    @PostMapping("/registerGs")
    public R<Map<String, Object>> register1(@Validated(AddGroup.class) @RequestBody PayTenantBo bo) {
        //添加验证  手机号相同或者公司名相同不允许注册
        PayTenantBo queryBo = new PayTenantBo();
        queryBo.setPhone(bo.getPhone());
        List<PayTenantVo> asCompanyVos = iPayTenantService.queryList(queryBo);
        if(asCompanyVos!=null&&asCompanyVos.size()>0){
            return  new R().fail("手机号已注册");
        }
        queryBo.setName(bo.getName());
        queryBo.setPhone(null);
        List<PayTenantVo> asCompanyVos2 = iPayTenantService.queryList(queryBo);
        if(asCompanyVos2!=null&&asCompanyVos2.size()>0){
            return  new R().fail("公司名已注册");
        }
        if(iPayTenantService.insertByBo(bo)){
            //公司注册成功后自动添加角色：管理员   todo
            Long[] adids={1L, 1921833283434213378L, 1921827581902888962L, 1921827581902888963L, 1921827581902888964L, 1921827581902888965L, 1921827581902888966L, 1921827581902888967L, 1921833488053334018L, 1921827579365335041L, 1921827579365335042L, 1921827579365335043L, 1921827579365335044L, 1921827579365335045L, 1921827579365335046L, 1921827582745944066L, 1921827582745944067L, 1921827582745944068L, 1921827582745944069L, 1921827582745944070L, 1921827582745944071L, 1921827581055639553L, 1921827581055639554L, 1921827581055639555L, 1921827581055639556L, 1921827581055639557L, 1921827581055639558L, 1921827581252771841L, 1921827581252771842L, 1921827581252771843L, 1921827581252771844L, 1921827581252771845L, 1921827581252771846L, 1921834138757656577L, 1921827582162935809L, 1921827582162935810L, 1921827582162935811L, 1921827582162935812L, 1921827582162935813L, 1921827582162935814L, 1921827582490091522L, 1921827582490091523L, 1921827582490091524L, 1921827582490091525L, 1921827582490091526L, 1921827582490091527L, 1921827583140208641L, 1921827583140208642L, 1921827583140208643L, 1921827583140208644L, 1921827583140208645L, 1921827583140208646L, 1921827581449904130L, 1921827581449904131L, 1921827581449904132L, 1921827581449904133L, 1921827581449904134L, 1921827581449904135L, 1921827583601582082L, 1921827583601582083L, 1921827583601582084L, 1921827583601582085L, 1921827583601582086L, 1921827583601582087L, 1921835117498494977L, 1921827582880161794L, 1921827582880161795L, 1921827582880161796L, 1921827582880161797L, 1921827582880161798L, 1921827582880161799L, 100L, 1001L, 1002L, 1003L, 1004L, 1005L, 1006L, 1007L, 101L, 1010L, 1011L, 1012L, 1013L, 1014L};
            Long[] ygids={1921835117498494977L, 1921827582880161794L, 1921827582880161795L};
            SysRole role1 = new SysRole();
            role1.setRoleKey("companyAdmin");
            role1.setRoleName("公司管理员");
            role1.setTenantId(bo.getId());
            role1.setStatus("0");
            role1.setRoleSort(0);
            role1.setMenuCheckStrictly(false);
            role1.setDeptCheckStrictly(true);
            role1.setFlag(false);
            role1.setMenuIds(adids);

            SysRole role2 = new SysRole();
            role2.setRoleKey("yg");
            role2.setRoleName("普通员工");
            role2.setTenantId(bo.getId());
            role2.setStatus("0");
            role2.setRoleSort(0);
            role2.setMenuCheckStrictly(false);
            role2.setDeptCheckStrictly(true);
            role2.setFlag(false);
            role2.setMenuIds(ygids);

            roleService.insertRole(role1);
            roleService.insertRole(role2);

            Map<String ,Object> data = new HashMap<>();
            List<SysRole> roles = new ArrayList<>();
            roles.add(role1);
            roles.add(role2);
            data.put("id",bo.getId());
            data.put("roles",roles);
          return  new R().ok(data);
        }else{
          return  new R().fail("注册失败，请重试");
        }
    }
    /**
     * 添加公司管理员用户
     */
    @SaIgnore
    @Transactional
    @PostMapping("/registerUser")
        public R<Void> register2(@Validated @RequestBody SysUser user) {
            if (!userService.checkUserNameUnique(user)) {
                return R.fail("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
            } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
                return R.fail("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
            } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
                return R.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
            } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkNickNameUnique(user)) {
                return R.fail("新增用户'" + user.getUserName() + "'失败，用户已存在");
            }
            user.setPassword(BCrypt.hashpw(user.getPassword()));
            //1.查询试用的订阅计划信息   2.注册管理员用户同时添加公司的订阅计划——免费试用3月
            PaySubInfoBo bo = new PaySubInfoBo();
            PaySubPlanBo planBo= new PaySubPlanBo();
            planBo.setName(dictService.getDictValue("trial_plan","trial_name"));  //试用  对应字典的试用名称查询试用计划
            List<PaySubPlanVo> planVos = iPaySubPlanService.queryList(planBo);
            if(planVos!=null&&planVos.size()>0){
                Date date = new Date();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date); // 设置当前日期
                calendar.add(Calendar.MONTH, 3); // 增加三个月
                Date endDate = calendar.getTime(); // 获取新的日期
                bo.setActive("0");
                bo.setTenantId(user.getTenantId());
                bo.setCompanyName(user.getTenantName());
                bo.setSubplanId(planVos.get(0).getId());
                bo.setSubplanName(planVos.get(0).getName());
                bo.setStartTime(date);
                bo.setEndTime(endDate);
                bo.setRemark("用户注册默认试用");
            }else{
                bo.setActive("1");
                bo.setTenantId(user.getTenantId());
                bo.setCompanyName(user.getTenantName());
                bo.setEndTime(null);
                bo.setStartTime(null);
                bo.setRemark("用户注册时未找到试用计划");
            }
            iPaySubInfoService.insertByBo(bo);
            user.setTenantName(null);
            return toAjax(userService.insertUser(user));
        }
    //忘记密码功能分3步：1、发送短信验证码 2、查找是否有该用户并验证短信验证码是否正确  3、验证码通过后修改密码
    //发送手机短信调用CaptchaController的 captchaSms接口发送短信     当前测试用的自己的阿里云账号，先不真正发送短信设置code=1234
    /**
     * 验证短信验证码——2分钟  验证码有效期（分钟）Constants接口CAPTCHA_EXPIRATION
     * @param phonenumber
     * @param smsCode
     * @return
     */
    @SaIgnore
    @PostMapping("/validateSmsCode")
    public R<SysUser> validateSmsCode(String phonenumber, String smsCode) {
        // 通过手机号查找用户
        SysUser user = loginService.loadUserByPhonenumber(phonenumber);
        //验证短信验证码
        if(loginService.validateSmsCode(phonenumber, smsCode)){
            return R.ok(user);
        }else{
            return R.fail("验证码错误");
        }
    }

    /**
     * 密码修改
     * @return
     */
    @SaIgnore
    @PostMapping("/modifyPass")
    public R<Void> modifyPass(@RequestBody SysUser user) {
        if (ObjectUtil.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
      //注释掉数据权限验证  userService.checkUserDataScope(user.getUserId());
        user.setPassword(BCrypt.hashpw(user.getPassword()));
        System.out.println("用户——"+user.getUserId()+"——通过短信重置密码");
        return toAjax(userService.resetPwd(user));
    }
}
