package com.muyu.openbusiness.controller;

import com.muyu.cloud.common.many.datasource.holder.DynamicDataSourceHolder;
import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.StringUtils;
import com.muyu.common.core.web.controller.BaseController;
import com.muyu.common.core.web.page.TableDataInfo;
import com.muyu.common.log.annotation.Log;
import com.muyu.common.log.enums.BusinessType;
import com.muyu.common.security.annotation.InnerAuth;
import com.muyu.common.security.annotation.RequiresPermissions;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.SysDept;
import com.muyu.common.system.domain.SysUser;
import com.muyu.common.system.remote.RemoteUserService;

import com.muyu.openbusiness.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


/**
 * @Author: 胡杨
 * @Name: SysUser
 * @Description:
 * @CreatedDate: 2024/9/23 下午8:55
 * @FilePath: com.muyu.system.saas.controller
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {
    @Resource
    private RemoteUserService remoteUserService;
    @Resource
    private SysUserService userService;


    /**
     * 查询用户列表
     * @param user 条件
     * @return 集合
     */
    @GetMapping("/list")
    public Result<TableDataInfo<SysUser>> list(SysUser user){
        startPage();
        return getDataTable(userService.selectUserList(user));
    }


    @InnerAuth
    @GetMapping("/info")
    public Result<SysUser> info (
            @RequestParam("firmCode") String firmCode,
            @RequestParam("userName") String userName) {
        DynamicDataSourceHolder.setDynamicDataSourceKey(firmCode);
        SysUser sysUser = userService.selectUserByUserName(userName);
        if (StringUtils.isNull(sysUser)) {
            return error("用户名或密码错误");
        }
        return Result.success(sysUser);
    }


    /**
     * 新增用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public Result add (@Validated @RequestBody SysUser user) {
        SysUser checked = userService.checkUserNameUnique(user);
        if (ObjectUtils.isNotEmpty(checked)) {
            if (checked.getUserName().equals(user.getUserName())) {
                return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
            } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && checked.getPhonenumber().equals(user.getPhonenumber())) {
                return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
            } else if (StringUtils.isNotEmpty(user.getEmail()) && checked.getEmail().equals(user.getEmail())) {
                return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
            }
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));

        String saasKey = SecurityUtils.getSaasKey();
        if ("FIRM".equals(saasKey)) {
            SysDept sysDept = remoteUserService.selectDeptById(user.getDeptId()).getData();
            if (ObjectUtils.isEmpty(sysDept)){
                return error("部门不存在!");
            }
            user.setFirmCode(sysDept.getFirmCode());
        }else {
            user.setFirmCode(saasKey);
        }
        userService.save(user);
        userService.insertUserPost(user);
        userService.insertUserRole(user);
        return remoteUserService.addUser(user);
    }


}
