package com.dgtly.web.controller.grid;

import com.dgtly.common.annotation.Log;
import com.dgtly.common.constant.UserConstants;
import com.dgtly.common.core.controller.BaseController;
import com.dgtly.common.core.domain.AjaxResult;
import com.dgtly.common.core.page.TableDataInfo;
import com.dgtly.common.enums.BusinessType;
import com.dgtly.common.exception.BusinessException;
import com.dgtly.common.utils.poi.ExcelUtil;
import com.dgtly.common.utils.security.EncryptPassWordClass;
import com.dgtly.framework.util.ShiroUtils;
import com.dgtly.system.domain.Community;
import com.dgtly.system.domain.SysUser;
import com.dgtly.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Controller
@RequestMapping("/grid/people")
public class GridController extends BaseController {
    private String prefix = "system/grid";

    @Autowired
    private ISysUserService userService;
    @Autowired
    private ICommunityService communityService;


    @RequiresPermissions("grid:people:view")
    @GetMapping()
    public String user()
    {
        return prefix + "/grid";
    }

    @RequiresPermissions("grid:people:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectGridPeople(user);
        return getDataTable(list);
    }
    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        mmap.put("communitys", communityService.selectCommunityList(new Community()));
        return prefix + "/add";
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("grid:people:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysUser user)
    {
        user.setRoleId(Long.parseLong("2"));
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }


    /**
     * 新增保存用户
     */
    @RequiresPermissions("grid:people:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    @Transactional
    public AjaxResult addSave(@Validated SysUser user)
    {
        Long[] i = {new Long(2)};
        user.setRoleIds(i);
        SysUser localUser = ShiroUtils.getSysUser();
        user.setCompanyId(localUser.getCompanyId());
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(user.getLoginName()))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        }
        else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        else if (user.getPassword().length() < UserConstants.PASSWORD_MIN_LENGTH
                || user.getPassword().length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            return error("密码长度为6-19，请重新设置！！");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(EncryptPassWordClass.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setCreateBy(ShiroUtils.getLoginName());
        int userId = userService.insertUser(user);


        return toAjax(userId);
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, ModelMap mmap)
    {
        mmap.put("communitys", communityService.selectCommunityList(new Community()));
        mmap.put("user", userService.selectUserById(userId));
        return prefix + "/edit";
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("grid:people:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    @Transactional
    public AjaxResult editSave(@Validated SysUser user)
    {

        if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return error("修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        user.setUpdateBy(ShiroUtils.getLoginName());
        int rows = userService.updateUserInfo(user);
        return toAjax(rows);
    }



    @RequiresPermissions("grid:people:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    @Transactional
    public AjaxResult remove(String ids)
    {
        try
        {
            int rows = userService.deleteUserByIds(ids);
            return toAjax(rows);
        }
        catch (BusinessException e)
        {
            return error(e.getMessage());
        }
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(SysUser user)
    {

        return userService.checkLoginNameUnique(user.getLoginName(),ShiroUtils.getSysUser().getCompanyId());
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(SysUser user)
    {
        SysUser localUser = ShiroUtils.getSysUser();
        user.setCompanyId(localUser.getCompanyId());
        return userService.checkPhoneUnique(user);
    }



    /**
     * 用户状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("grid:people:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    @Transactional
    public AjaxResult changeStatus(SysUser user)
    {
        userService.checkUserAllowed(user);


        return toAjax(userService.changeStatus(user));
    }
}
