package com.yccrc.kede.controller.ent;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yccrc.common.annotation.Log;
import com.yccrc.common.constant.Constants;
import com.yccrc.common.constant.UserConstants;
import com.yccrc.common.core.controller.BaseController;
import com.yccrc.common.core.domain.entity.SysUser;
import com.yccrc.common.core.domain.model.RegisterBody;
import com.yccrc.common.enums.BusinessType;
import com.yccrc.common.exception.ServiceException;
import com.yccrc.common.utils.MessageUtils;
import com.yccrc.common.utils.PageUtils;
import com.yccrc.common.utils.SecurityUtils;
import com.yccrc.common.utils.StringUtils;
import com.yccrc.common.vo.Result;
import com.yccrc.framework.manager.AsyncManager;
import com.yccrc.framework.manager.factory.AsyncFactory;
import com.yccrc.framework.web.service.SysRegisterService;
import com.yccrc.kede.domain.Enterprise;
import com.yccrc.kede.enums.UserTypeEnum;
import com.yccrc.kede.service.IEnterpriseService;
import com.yccrc.kede.service.IRegionService;
import com.yccrc.kede.vo.EnterpriseAdminVO;
import com.yccrc.kede.vo.EnterpriseDetailVO;
import com.yccrc.system.service.ISysConfigService;
import com.yccrc.system.service.ISysRoleService;
import com.yccrc.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

/**
 * 注册验证
 *
 * @author ruoyi
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/ent/user")
public class EntUserController extends BaseController {
    @Autowired
    private SysRegisterService registerService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IEnterpriseService enterpriseService;
    @Autowired
    private IRegionService regionService;
    @Autowired
    ISysConfigService configService;

    @Autowired
    ISysRoleService sysRoleService;

    @ApiOperation(value = "用户注册(手机注册)")
    @PostMapping("/register")
    public Result<Boolean> register(@RequestBody RegisterBody user) {

        String msg = "",

                username = user.getUsername(), password = user.getPassword();

        //	registerService.validateCaptcha(username, user.getCode(), user.getUuid());

        if (StringUtils.isEmpty(username)) {
            msg = "用户名不能为空";
        } else if (StringUtils.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            msg = "账户长度必须在2到20个字符之间";
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在5到20个字符之间";
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(username))) {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        } else {
            SysUser sysUser = new SysUser();
            sysUser.setUserName(username);
            sysUser.setNickName(username);
            sysUser.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            sysUser.setUserType(UserTypeEnum.ENT_ADMIN);
            boolean regFlag = userService.registerUser(sysUser);
            if (!regFlag) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER,
                        MessageUtils.message("user.register.success")));
            }
        }

        if (StrUtil.isEmpty(msg)) return new Result<Boolean>().ok(Boolean.TRUE);
        return new Result<Boolean>().error(msg);
    }

    @ApiOperation(value = "用户注册(带企业信息)")
    @PostMapping("/regEnt")
    public Result<Boolean> registerEnt(@RequestBody EnterpriseAdminVO enterprise) {

        enterprise.setEntState(1);
        enterprise.setAuthState(1);
        return new Result<Boolean>().ok(enterpriseService.saveAdminEnterprise(enterprise));
    }

    @ApiOperation(value = "新增用户信息")
    @Log(title = "企业用户", businessType = BusinessType.INSERT)
    @PostMapping
    public Result<Boolean> add(@RequestBody SysUser user) {
        if (super.getLoginUser().getUser().getScopeId() == null) throw new ServiceException("请先提交企业信息");

        if (user.getUserType() == null) throw new ServiceException("请选择用户类型");
        if (StrUtil.isEmpty(user.getPassword())) throw new ServiceException("请输入登录密码");
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            throw new ServiceException("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
//		 if (StringUtils.isNotEmpty(user.getPhonenumber())){
//	    	 throw new ServiceException("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
//	     }

        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setScopeId(super.getLoginUser().getUser().getScopeId());
        //绑定角色(企业用户)
        user.setRoleIds(new Long[]{5l});
        userService.insertUser(user);
        //sysRoleService.insertAuthUsers(5l, new Long[]{user.getUserId()});

        return new Result<Boolean>().ok(true);
    }

    @ApiOperation(value = "查询用户列表")
    @GetMapping("/list")
    public Result<Page<SysUser>> list(
            @RequestParam(value = "userName", required = false) String userName,
            @RequestParam(value = "nickName", required = false) String nickName,
            @RequestParam(value = "mobile", required = false) String mobile,
            @RequestParam(value = "userType", required = false) UserTypeEnum userType,
            @RequestParam(value = "flag", required = false) Boolean flag) {

        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>()
                .eq("scope_id", getLoginUser().getUser().getScopeId())
                .eq("del_flag", "0")
                .eq(userType != null, "user_type", userType)
                .like(StrUtil.isNotEmpty(userName), "user_name", userName)
                .like(StrUtil.isNotEmpty(nickName), "nick_name", nickName)
                .like(StrUtil.isNotEmpty(mobile), "phonenumber", mobile);
        Page<SysUser> page = userService.page(PageUtils.initPage(), queryWrapper);
        if (flag != null && flag) {
            // 过滤企业管理员账户,只展示企业子账户
            if (page.getRecords() != null && !page.getRecords().isEmpty()) {
                page.getRecords().remove(0);
                page.setTotal(page.getTotal() - 1);
            }
        }
        return new Result<Page<SysUser>>().ok(page);

    }

    @ApiOperation(value = "修改用户信息")
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public Result<Boolean> edit(@RequestBody SysUser sysUser) {
        return new Result<Boolean>().ok(userService.updateById(sysUser));
    }

    @ApiOperation(value = "删除用户信息")
    @Log(title = "用户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public Result<Boolean> remove(@PathVariable Integer[] ids) {
        return new Result<Boolean>().ok(userService.removeBatchByIds(Arrays.asList(ids)));
    }

//    @ApiOperation(value = "重置用户密码")
//    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
//    @PutMapping("/resetPwd")
//    public Result<Integer> resetPwd(@RequestBody SysUser user)
//    {
//        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
//        user.setUpdateBy(getUsername());
//        return new Result<Integer>().ok(userService.resetPwd(user));
//    }

    @ApiOperation(value = "重置用户密码")
    @PutMapping("/resetPwd/{userId}")
    public Result<Boolean> resetPwd(@PathVariable("userId") Integer userId) {
        SysUser user = userService.getById(userId);
        //  userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(configService.selectConfigByKey("sys.user.initPassword")));
        user.setUpdateBy(getUsername());
        userService.resetPwd(user);
        return new Result<Boolean>().ok(true);
    }

    @ApiOperation(value = "获取用户信息")
    @GetMapping("/userInfo/{userId}")
    public Result<SysUser> userInfo(@PathVariable("userId") Integer userId) {
        return new Result<SysUser>().ok(userService.getById(userId));
    }

    @ApiOperation(value = "新增企业信息")
    @Log(title = "企业信息", businessType = BusinessType.INSERT)
    @PostMapping("/ent")
    public Result<Boolean> add(@RequestBody EnterpriseDetailVO entity) {
        return new Result<Boolean>().ok(enterpriseService.saveEnterprise(entity));
    }

    @ApiOperation(value = "修改企业信息")
    @Log(title = "企业信息", businessType = BusinessType.UPDATE)
    @PutMapping("/ent")
    public Result<Boolean> edit(@RequestBody Enterprise entity) {
        return new Result<Boolean>().ok(enterpriseService.saveOrUpdate(entity));
    }

    @ApiOperation(value = "提交审核")
    @PutMapping("/auth")
    public Result<Boolean> auth(@RequestBody Enterprise entity) {
        entity.setEntState(1);
        entity.setAuthState(1);
        return new Result<Boolean>().ok(enterpriseService.saveOrUpdate(entity));
    }

    @ApiOperation(value = "读取企业信息")
    @GetMapping("/ent")
    public Result<Enterprise> entIfno() {
        Enterprise e = enterpriseService.getById(super.getLoginUser().getUser().getScopeId());
//    	e.setProvinceName(regionService.getNameById(e.getProvinceId()));
//		e.setCityName(regionService.getNameById(e.getCityId()));
//		e.setDistrictName(regionService.getNameById(e.getDistrictId()));
        return new Result<Enterprise>().ok(e);
    }
}
