package com.fs.company.controller;

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

import com.fs.common.core.domain.R;

import com.fs.company.domain.*;
import com.fs.company.service.*;
import com.fs.company.vo.CompanyUserVO;
import com.fs.core.security.LoginUser;
import com.fs.core.web.service.TokenService;
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 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.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;


/**
 * 用户信息
 *

 */
@RestController
@RequestMapping("/company/user")
public class CompanyUserController extends BaseController
{

    @Autowired
    private ICompanyRoleService roleService;

    @Autowired
    private ICompanyPostService postService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ICompanyUserService companyUserService;
    @Autowired
    private ICompanyService companyService;

    @Autowired
    private ICompanyVoiceCallerService callerService;

    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CompanyUser user)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        user.setCompanyId(loginUser.getCompany().getCompanyId());
        startPage();
        List<CompanyUser> list = companyUserService.selectCompanyUserList(user);
        return getDataTable(list);
    }
    @GetMapping("/getUserList")
    public R getUserList()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        CompanyUser map=new CompanyUser();
        map.setCompanyId(loginUser.getCompany().getCompanyId());
        List<CompanyUser> list = companyUserService.selectCompanyUserList(map);
        return  R.ok().put("data",list);
    }
    @GetMapping("/getList")
    public TableDataInfo getList(CompanyUser user)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        user.setCompanyId(loginUser.getCompany().getCompanyId());
        startPage();
        List<CompanyUser> list = companyUserService.selectCompanyUserList(user);
        return getDataTable(list);
    }
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('company:user:export')")
    @GetMapping("/export")
    public AjaxResult export(CompanyUser user)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        user.setCompanyId(loginUser.getCompany().getCompanyId());
        List<CompanyUser> list = companyUserService.selectCompanyUserList(user);
        ExcelUtil<CompanyUser> util = new ExcelUtil<CompanyUser>(CompanyUser.class);
        return util.exportExcel(list, "用户数据");
    }



    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('company:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        CompanyRole companyRoleMap=new CompanyRole();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        companyRoleMap.setCompanyId(loginUser.getCompany().getCompanyId());
        List<CompanyRole> roles = roleService.selectCompanyRoleList(companyRoleMap);

        ajax.put("roles", CompanyUser.isAdmin(loginUser.getUser().getUserType()) ? roles : roles.stream().filter(r -> r.getRoleKey()!="admin").collect(Collectors.toList()));

        CompanyPost postMap=new CompanyPost();
        postMap.setCompanyId(loginUser.getCompany().getCompanyId());
        ajax.put("posts", postService.selectCompanyPostList(postMap));
        if (StringUtils.isNotNull(userId))
        {
            CompanyUser companyUser=companyUserService.selectCompanyUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, companyUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));


        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('company:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody CompanyUser user)
    {
        //判断用户数量是否已达到上线
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Integer count=companyUserService.selectCompanyUserCountByCompanyId(loginUser.getCompany().getCompanyId());
        Company company=companyService.selectCompanyById(loginUser.getCompany().getCompanyId());
        if(count>company.getLimitUserCount()){
            return AjaxResult.error("用户数量已达到上限");
        }
        user.setCompanyId(loginUser.getCompany().getCompanyId());
        if (UserConstants.NOT_UNIQUE.equals(String.valueOf(companyUserService.checkUserName(user.getUserName()))))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setCreateTime(new Date());
        user.setUserType("01");//一般用户
        return toAjax(companyUserService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('company:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody CompanyUser user)
    {
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(companyUserService.updateUser(user));
    }

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

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('company:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody CompanyUser user)
    {
        return toAjax(companyUserService.resetUserPwdByUserId(user.getUserId(), SecurityUtils.encryptPassword(user.getPassword())));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('company:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody CompanyUser user)
    {
        //管理员的状态不能修改
        CompanyUser companyUser=companyUserService.selectCompanyUserById(user.getUserId());
        if(companyUser.isAdmin()){
            return AjaxResult.error("不能修改管理员状态");
        }
        if ("1".equals(user.getStatus())){
            CompanyVoiceCaller caller = callerService.selectCompanyVoiceCallerByUserId(companyUser.getCompanyId(),companyUser.getUserId());
            if(caller != null){
                caller.setCompanyId(0l);
                caller.setCompanyUserId(0l);
                caller.setMobile("");
                caller.setStatus(1);
                callerService.updateCompanyVoiceCaller(caller);
            }
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(companyUserService.updateCompanyUser(user));
    }


    /**
     * 获取通讯录
     * @param user
     * @return
     */
    @GetMapping("/getAddressBookList")
    public TableDataInfo getAddressBookList(CompanyUser user)
    {
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        user.setCompanyId(loginUser.getCompany().getCompanyId());
        List<CompanyUserVO> list = companyUserService.selectMyUserList(user);
        return getDataTable(list);
    }

//    @GetMapping("/getAllUserlist")
//    public R getAllUserlist()
//    {
//        CompanyUser map=new CompanyUser();
//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//        map.setCompanyId(loginUser.getCompany().getCompanyId());
//        map.setStatus("1");
//        List<CompanyUser> list = companyUserService.selectCompanyUserList(map);
//        return R.ok().put("data",list);
//    }

    @GetMapping("/getUserListByDeptId")
    public R getUserListByDeptId(CompanyUser user)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        user.setCompanyId(loginUser.getCompany().getCompanyId());

        List<CompanyUser> list = companyUserService.getUserListByDeptId(user);
        return R.ok().put("data",list);
    }

    @GetMapping("/getSelectUserList")
    public TableDataInfo getSelectUserList(CompanyUser map)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        map.setCompanyId(loginUser.getCompany().getCompanyId());
        startPage();
        List<CompanyUserVO> list = companyUserService.selecCompanyAllUsersList(map);
        return getDataTable(list);
    }

}
