package com.ruoyi.web.controller.buyerapi;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.buyerapi.domain.BuyerCompanyInfo;
import com.ruoyi.buyerapi.service.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.buyerapi.service.IBuyerDeptService;
import com.ruoyi.buyerapi.service.IBuyerPostService;
import com.ruoyi.buyerapi.service.IBuyerRoleService;
import com.ruoyi.buyerapi.service.IBuyerUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@Api(tags = "用户信息")
@RestController
@RequestMapping("/buyer/user")
public class BuyerUserController extends BaseController {
    @Autowired
    private IBuyerUserService buyerUserService;

    @Autowired
    private IBuyerRoleService buyerRoleService;

    @Autowired
    private IBuyerDeptService buyerDeptService;

    @Autowired
    private IBuyerPostService buyerPostService;

    @Autowired
    private IBuyerCompanyInfoService buyerCompanyInfoService;

    /**
     * 获取用户列表
     */
    @ApiOperation(value = "获取用户列表")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = buyerUserService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 获取超级管理员用户列表
     */
    @ApiOperation(value = "获取超级管理员用户列表")
    @PreAuthorize("@ss.hasPermi('system:user:adminList')")
    @GetMapping("/adminList")
    public List adminList() {
        List<BuyerCompanyInfo> adminList = buyerCompanyInfoService.selectBuyerCompanyInfoList(new BuyerCompanyInfo());
        return adminList;
    }

    @ApiOperation(value = "导出")
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = buyerUserService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

//    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('system:user:import')")
//    @PostMapping("/importData")
//    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
//    {
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        List<SysUser> userList = util.importExcel(file.getInputStream());
//        String operName = getUsername();
//        String message = buyerUserService.importUser(userList, updateSupport, operName);
//        return AjaxResult.success(message);
//    }

    @ApiOperation(value = "导入模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @ApiOperation(value = "根据用户编号获取详细信息")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        if (userId == null) {
            userId = SecurityUtils.getUserId();
        }
        buyerUserService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = buyerRoleService.selectRoleAll();
        BuyerCompanyInfo buyerCompanyInfo = buyerCompanyInfoService.selectBuyerCompanyInfoByUserId(userId);
        if(null != buyerCompanyInfo && StrUtil.isNotEmpty(buyerCompanyInfo.getId())){
            ajax.put("roles", roles);
        }else{
            ajax.put("roles", roles.stream().filter(r -> !"admin".equals(r.getRoleKey())).collect(Collectors.toList()));
        }
        ajax.put("posts", buyerPostService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = buyerUserService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", buyerPostService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

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

        // 处理部门为空的情况
        if(null == user.getDeptId()){
            SysDept dept = new SysDept();
            dept.setCompanyId(SecurityUtils.getCompanyId());
            List<SysDept> depts = buyerDeptService.selectDeptList(dept);
            if(null != depts && depts.size() > 0){
                user.setDeptId(depts.get(0).getDeptId());
            }
        }
        return toAjax(buyerUserService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @ApiOperation(value = "修改用户")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        buyerUserService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(buyerUserService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(buyerUserService.checkEmailUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());

        // 处理部门为空的情况
        if(null == user.getDeptId()){
            SysDept dept = new SysDept();
            dept.setCompanyId(SecurityUtils.getCompanyId());
            List<SysDept> depts = buyerDeptService.selectDeptList(dept);
            if(null != depts && depts.size() > 0){
                user.setDeptId(depts.get(0).getDeptId());
            }
        }
        return toAjax(buyerUserService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @ApiOperation(value = "删除用户")
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(buyerUserService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @ApiOperation(value = "重置密码")
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        buyerUserService.checkUserAllowed(user);
        buyerUserService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(buyerUserService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @ApiOperation(value = "状态修改")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        buyerUserService.checkUserAllowed(user);
        buyerUserService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(buyerUserService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @ApiOperation(value = "根据用户编号获取授权角色")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = buyerUserService.selectUserById(userId);
        List<SysRole> roles = buyerRoleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        BuyerCompanyInfo buyerCompanyInfo = buyerCompanyInfoService.selectBuyerCompanyInfoByUserId(userId);
        if(null != buyerCompanyInfo && StrUtil.isNotEmpty(buyerCompanyInfo.getId())){
            ajax.put("roles", roles);
        }else{
            ajax.put("roles", roles.stream().filter(r -> !"admin".equals(r.getRoleKey())).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @ApiOperation(value = "用户授权角色")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        buyerUserService.checkUserDataScope(userId);
        buyerUserService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @ApiOperation(value = "获取部门树列表")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept) {
        return AjaxResult.success(buyerDeptService.selectDeptTreeList(dept));
    }
}
