package com.fs.web.controller.system;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import com.fs.common.core.domain.R;
import com.fs.core.security.LoginUser;

import com.fs.system.param.SysUserExcelParam;
import com.fs.system.service.ISysConfigService;
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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.fs.common.annotation.Log;
import com.fs.common.constant.UserConstants;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.entity.SysRole;
import com.fs.common.core.domain.entity.SysUser;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.core.security.SecurityUtils;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.core.web.service.TokenService;
import com.fs.system.service.ISysPostService;
import com.fs.system.service.ISysRoleService;
import com.fs.system.service.ISysUserService;

/**
 * 用户信息
 *

 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{

    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private TokenService tokenService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }
    @GetMapping("/getList")
    public TableDataInfo getList(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }
    @GetMapping("/getMyList")
    public TableDataInfo getMyList(SysUser user)
    {
//        startPage();
//        List<SysUserBO> list = userService.selectMyUserList(user);
//        return getDataTable(list);
        return null;
    }
    @Log(title = "导出", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @GetMapping("/export")
    public AjaxResult export(SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        List<SysUserExcelParam> sysUserExcelBOList=new ArrayList<>();
        if(list!=null){
            for(SysUser u:list){

                SysUserExcelParam bo=new SysUserExcelParam();
                BeanUtil.copyProperties(u,bo);
                if(u.getDept()!=null){
                    bo.setDeptName(u.getDept().getDeptName());
                }
                if(u.getSex().equals("0")){
                    bo.setSex("男");
                }
                else if(u.getSex().equals("1")){
                    bo.setSex("女");
                }
                else {
                    bo.setSex("未知");
                }
                //岗位 角色
                List<String> posts= postService.selectPostNameListByUserId(u.getUserId());
                List<String> roles=roleService.selectRoleNameByUserId(u.getUserId());
                if(posts!=null){
                    String postNames = String.join(",", posts);
                    bo.setPostName(postNames);
                }
                if(roles!=null){
                    String roleNames = String.join(",", roles);
                    bo.setRoleName(roleNames);
                }
                sysUserExcelBOList.add(bo);
            }
            ExcelUtil<SysUserExcelParam> util = new ExcelUtil<SysUserExcelParam>(SysUserExcelParam.class);
            return util.exportExcel(sysUserExcelBOList, "用户数据");
        }
        return new AjaxResult().error("没有可导出的数据");

    }


    @Log(title = "导入用户", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUserExcelParam> util = new ExcelUtil<SysUserExcelParam>(SysUserExcelParam.class);
        List<SysUserExcelParam> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        String pwd=SecurityUtils.encryptPassword(password);
        String message = userService.importUser(userList, updateSupport, operName,pwd);
        return AjaxResult.success(message);
    }

    //下载模板
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<SysUserExcelParam> util = new ExcelUtil<SysUserExcelParam>(SysUserExcelParam.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId))
        {
            ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

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

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

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        return toAjax(userService.deleteUserByIds(userIds));
    }

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

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

    @GetMapping("/getAllList")
    public TableDataInfo getAllList(SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @GetMapping("/getUserListByDeptId")
    public R getUserListByDeptId(SysUser user)
    {
        List<SysUser> list = userService.getUserListByDeptId(user);
        return R.ok().put("data",list);
    }


    @GetMapping("/getSelectUserList")
    public R getSelectUserList()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser map=new SysUser();
//        map.setDeptId(loginUser.getUser().getDeptId());
        List<SysUser> list = userService.selectUserList(map);
        return R.ok().put("data",list);
    }


    @GetMapping("/isAdmin")
    public R isAdminUser()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Boolean isAdmin= SecurityUtils.isAdmin(loginUser.getUser().getUserId());
        return R.ok().put("data",isAdmin);
    }

}
