package com.njyunzhi.pet_identity.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njyunzhi.pet_identity.common.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.njyunzhi.pet_identity.service.ISysUserService;
import com.njyunzhi.pet_identity.entity.SysUser;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
    * 用户 前端控制器
    * </p>
 *
 * @author yansen
 * @since 2022-05-24
 */

@Api(tags = "用户")
@RestController
@RequestMapping("/admin")
public class SysUserController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(SysUserController.class);

    @Autowired
    public ISysUserService iSysUserService;


    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/user",method= RequestMethod.GET)
    @ApiOperation(value="列表", notes = "列表", httpMethod = "GET", response = ResponseBean.class)
    public ResponseBean sysUserList(@ApiParam("页码") @RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                    @ApiParam("单页数据量") @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                    @ApiParam("用户名") @RequestParam(value ="userName", required = false) String userName,
                                    @ApiParam("手机号") @RequestParam(value ="phone", required = false) String phone) throws Exception{

        IPage<SysUser> pg = new Page<>(pageNum, pageSize);

        IPage<SysUser> result = iSysUserService.getPagedBy(pg, userName, phone);
        return ResponseBean.success(result);
    }

    /**
     * 保存对象
     * @param sysUser 实体对象
     * @return
     */
    @RequestMapping(value="/user",method= RequestMethod.POST)
    @ApiOperation(value="保存", notes = "保存", httpMethod = "POST", response = ResponseBean.class)
    public ResponseBean sysUserAdd(@ApiParam("保存内容") @RequestBody SysUser sysUser) throws Exception{

        SysUser exists = null;
        sysUser.setUserId(StringUtils.uuid());

        if (StringUtils.isEmpty(sysUser.getUserName())) {
            return ResponseBean.error("用户姓名不能为空");
        }
        if (StringUtils.isEmpty(sysUser.getPhone())) {
            return ResponseBean.error("用户手机不能为空");
        } else {
            exists = iSysUserService.getExistBy("phone", sysUser.getPhone(), false, true);
            if (exists != null) {
                return ResponseBean.error("用户手机号重复");
            }
        }
        if (StringUtils.isEmpty(sysUser.getRoleName())) {
            return ResponseBean.error("用户角色不能为空");
        }

        if (!StringUtils.isEmpty(sysUser.getLoginName())) {
            exists = iSysUserService.getExistBy("login_name", sysUser.getLoginName(), false, true);
            if (exists != null) {
                return ResponseBean.error("用户登录名重复");
            }

            if (StringUtils.isEmpty(sysUser.getPassword())) {
                return ResponseBean.error("登录密码不能为空");
            } else {
                sysUser.setPassword(EncryptUtils.md5(sysUser.getPassword(), sysUser.getUserId()));
            }
        }

        if (iSysUserService.save(sysUser)){
            sysUser.setPassword(null);
            return ResponseBean.success(sysUser);
        } else {
            return ResponseBean.error("保存失败, 请重试", ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @RequestMapping(value="/user/{id}", method= RequestMethod.DELETE)
    @ApiOperation(value="删除", notes = "删除", httpMethod = "DELETE", response = ResponseBean.class)
    public ResponseBean sysUserDelete(@ApiParam("对象ID") @PathVariable String id) throws Exception{
        SysUser sysUser = iSysUserService.getById(id);
        if (null == sysUser || Constants.STATUS_DELETE == sysUser.getStatus()) {
            return ResponseBean.error("未找到用户");
        }

        if (Constants.USER_ADMIN.equals(sysUser.getRoleName())) {
            return ResponseBean.error("暂无权限");
        }

        if(iSysUserService.removeLogicById(id)){
            return ResponseBean.success("success");
        }else {
            return ResponseBean.error("删除失败, 请重试", ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param sysUser 实体对象
     * @return
     */
    @RequestMapping(value="/user/{id}",method= RequestMethod.PUT)
    @ApiOperation(value="更新", notes = "更新", httpMethod = "PUT", response = ResponseBean.class)
    public ResponseBean sysUserUpdate(@ApiParam("对象ID") @PathVariable String id,
                                        @ApiParam("更新内容") @RequestBody SysUser sysUser) throws Exception{
        SysUser origin = iSysUserService.getById(id);
        if (null == origin || Constants.STATUS_DELETE == origin.getStatus()) {
            return ResponseBean.error("未找到用户");
        }

        SysUser exists = null;
        sysUser.setUserId(id);
        if (StringUtils.isEmpty(sysUser.getUserName())) {
            return ResponseBean.error("用户姓名不能为空");
        }
        if (StringUtils.isEmpty(sysUser.getPhone())) {
            return ResponseBean.error("用户手机不能为空");
        } else {
            exists = iSysUserService.getExistBy("phone", sysUser.getPhone(), false, true);
            if (exists != null && !id.equals(exists.getUserId())) {
                return ResponseBean.error("用户手机号重复");
            }
        }
        if (StringUtils.isEmpty(sysUser.getRoleName())) {
            return ResponseBean.error("用户角色不能为空");
        }

        if (!StringUtils.isEmpty(sysUser.getLoginName())) {
            exists = iSysUserService.getExistBy("login_name", sysUser.getLoginName(), false, true);
            if (exists != null && !id.equals(exists.getUserId())) {
                return ResponseBean.error("用户登录名重复");
            }

            if (!StringUtils.isEmpty(sysUser.getPassword())) {
                sysUser.setPassword(EncryptUtils.md5(sysUser.getPassword(), sysUser.getUserId()));
            }
        }

        if (iSysUserService.updateById(sysUser)){
            sysUser.setPassword(null);
            return ResponseBean.success(sysUser);
        }else {
            return ResponseBean.error("修改失败, 请重试", ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/user/{id}",method= RequestMethod.GET)
    @ApiOperation(value="详情", notes = "详情", httpMethod = "GET", response = ResponseBean.class)
    public ResponseBean sysUserGet(@ApiParam("对象ID") @PathVariable String id) throws Exception{
        SysUser origin = iSysUserService.getById(id);
        if (null == origin || Constants.STATUS_DELETE == origin.getStatus()) {
            return ResponseBean.error("未找到用户");
        }

        origin.setPassword(null);
        return ResponseBean.success(origin);
    }
}
