package com.fs.company.controller.company;

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.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyPost;
import com.fs.company.domain.CompanyRole;
import com.fs.company.domain.CompanyUser;
import com.fs.company.param.CompanyUserAreaParam;
import com.fs.company.param.CompanyUserQwParam;
import com.fs.company.service.ICompanyPostService;
import com.fs.company.service.ICompanyRoleService;
import com.fs.company.service.ICompanyService;
import com.fs.company.service.ICompanyUserService;
import com.fs.company.vo.CompanyUserQwListVO;
import com.fs.company.vo.CompanyUserVO;
import com.fs.company.vo.OptionVO;
import com.fs.framework.security.LoginUser;
import com.fs.framework.security.SecurityUtils;
import com.fs.framework.service.TokenService;
import com.fs.qw.vo.CompanyUserQwVO;
import com.fs.qw.vo.QwUserVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
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 java.util.*;
import java.util.stream.Collectors;


/**
 * 用户信息
 *

 */
@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;

    /**
     * 获取用户列表
     */
    @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);
    }
    @GetMapping("/qwList")
    public TableDataInfo qwList(CompanyUserQwParam user)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        user.setCompanyId(loginUser.getCompany().getCompanyId());
        startPage();
        List<CompanyUserQwListVO> list = companyUserService.selectCompanyUserQwListVO(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)
    {

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        user.setUpdateBy(SecurityUtils.getUsername());
        logger.info("用户管理-修改用户:"+user.getUserName()+"/登陆人:"+loginUser.getUser().getUserId()+"/名字："+loginUser.getUser().getUserName()+"/修改的角色："+ Arrays.toString(user.getRoleIds()));
        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("不能修改管理员状态");
        }
        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);
    }

    @GetMapping("/getQwAllUserList/{id}")
    public R getQwAllUserList(@PathVariable("id") String corpId)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

        List<QwUserVO> list = companyUserService.selectCompanyQwUserList(corpId,loginUser.getCompany().getCompanyId());
        return  R.ok().put("data",list);
    }

    /**
     * 根据部门的id获取到企业微信的qwuserid
     */
    @GetMapping("/getUserListByDeptIdToQwId")
    public R getUserListByDeptIdToQwId(CompanyUser user)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        user.setCompanyId(loginUser.getCompany().getCompanyId());

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

    /**
    * 获取区域
    */
    @GetMapping("/getCitysAreaList")
    public R getCitysAreaList(){
        return R.ok().put("data",companyUserService.getCitysAreaList());
    }

    /**
    * 批量修改 销售的所属区域(临时的)
    */
    @PostMapping("/updateCompanyUserAreaList")
    public R updateCompanyUserAreaList(@RequestBody CompanyUserAreaParam param)
    {
        return companyUserService.updateCompanyUserAreaList(param);
    }

    /**
     * 根据销售名称模糊查询
     * @param name  名称
     * @return  list
     */
    @GetMapping("/getCompanyUserListLikeName")
    public R getCompanyUserListLikeName(@RequestParam(required = false) String name,
                                        @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                        @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Map<String,Object> params = new HashMap<>();
        params.put("nickName", name);
        params.put("companyId", SecurityUtils.getLoginUser().getCompany().getCompanyId());

        PageHelper.startPage(pageNum, pageSize);
        List<OptionVO> companyUserList = companyUserService.selectCompanyUserListByMap(params);
        return R.ok().put("data", new PageInfo<>(companyUserList));
    }

}
