package com.mosty.common.core.business.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mosty.common.base.constant.enums.ConfigKeyEnum;
import com.mosty.common.base.constant.enums.DeletedEnum;
import com.mosty.common.base.constant.enums.PasswordLevelEnum;
import com.mosty.common.base.domain.ResponseResult;
import com.mosty.common.base.entity.log.BusinessType;
import com.mosty.common.base.entity.log.Log;
import com.mosty.common.base.exception.Asserts;
import com.mosty.common.base.util.IpUtil;
import com.mosty.common.config.entity.SysConfig;
import com.mosty.common.config.entity.vo.DeleteVO;
import com.mosty.common.config.service.SysConfigService;
import com.mosty.common.core.business.entity.*;
import com.mosty.common.core.business.entity.request.SysUserEditPasswordRequest;
import com.mosty.common.core.business.entity.vo.*;
import com.mosty.common.core.business.mapper.SysUserDeptMapper;
import com.mosty.common.core.business.mapper.SysUserRoleMapper;
import com.mosty.common.core.business.mapper.YbmjMapper;
import com.mosty.common.core.business.service.*;
import com.mosty.common.redis.service.RedisService;
import com.mosty.common.token.JwtSysUser;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Objects;


/**
 * 用户控制类
 *
 * @author kevin
 * @date 2022/2/12 10:17 PM
 * @since 1.0.0
 */
@SuppressWarnings("unused")
@RestController
@AllArgsConstructor
@RequestMapping("/sysUser")
@Api(tags = "用户接口")
public class SysUserController {

    private final SysUserService sysUserService;
    private final SysDeptService sysDeptService;
    private final SysPositionService sysPositionService;
    private final SysConfigService sysConfigService;
    private final SysUserDeptService sysUserDeptService;
    private final SysUserRoleService sysUserRoleService;
    private final RedisService redisService;
    private final SysUserRoleMapper sysUserRoleMapper;
    private final SysUserDeptMapper sysUserDeptMapper;
    private final YbmjMapper ybmjMapper;

    @JwtSysUser
    @PostMapping("addUser")
    @Log(title = "添加用户信息", businessType = BusinessType.INSERT)
    @ApiOperation(value = "添加用户信息", httpMethod = "POST", response = Boolean.class)
    public ResponseResult<Boolean> addSysUser(@RequestBody @Valid AddSysUserVO sysUserVo,
                                              HttpServletRequest servletRequest) {

/*        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name", sysUserVo.getLoginName());
        SysUser sysUser = sysUserService.getBaseMapper().selectOne(queryWrapper);
        if (sysUser != null)
            return ResponseResult.fail("登录账号重复！！");*/

        if (sysUserService.getBaseMapper().selectCount(new LambdaQueryWrapper<SysUser>().eq(SysUser::getIdEntityCard, sysUserVo.getIdEntityCard())) > 0)
            return ResponseResult.fail("身份证重复！！");

        if (sysUserService.getBaseMapper().selectCount(new LambdaQueryWrapper<SysUser>().eq(SysUser::getInDustRialId, sysUserVo.getInDustRialId())) > 0)
            return ResponseResult.fail("警号重复！！");


        // 验证岗位信息并且设置岗位名称
        SysPosition sysPosition = sysPositionService.getById(sysUserVo.getPositionId());
//        if (sysPosition == null || sysPosition.getXtZxbz() != 0)
//            return ResponseResult.fail("岗位 %s 不存在！");
        sysUserVo.setPositionName(sysPosition != null ? sysPosition.getPostName() : "");

        UserInfo userInfo = UserInfoManager.get();

        // 获取ip地址
        String ipAddress = IpUtil.getIpAddress(servletRequest);
        sysUserVo.setXtLrip(ipAddress);
        sysUserVo.setXtZhxgrip(ipAddress);

        // 保存用户信息
        sysUserService.saveInfo(sysUserVo);

        return ResponseResult.success(Boolean.TRUE);
    }


    @JwtSysUser
    @PostMapping("addUserTbYb")
    @Log(title = "同步宜宾人员", businessType = BusinessType.INSERT)
    @ApiOperation(value = "同步宜宾人员", httpMethod = "POST", response = Boolean.class)
    public ResponseResult<Boolean> addUserTbYb() {

        List<Ybmj> ybmjs = ybmjMapper.selectList(new QueryWrapper<>());
        if (!CollectionUtils.isEmpty(ybmjs)) {
            for (Ybmj ybmj : ybmjs) {
                SysUser sysUser = sysUserService.getBaseMapper().selectOne(new QueryWrapper<SysUser>().eq("id_entity_card", ybmj.getSfzh()));
                if (sysUser == null) {
                    AddSysUserVO sysUserVo = new AddSysUserVO();
                    sysUserVo.setSsbmdm(ybmj.getSsbmdm());
                    sysUserVo.setLoginName(ybmj.getXm());
                    sysUserVo.setPassword("E10ADC3949BA59ABBEcm9OiHRC56E057F20F883E");
                    sysUserVo.setUserName(ybmj.getXm());
                    sysUserVo.setUserType("00");
                    sysUserVo.setMobile(ybmj.getDh());
                    sysUserVo.setTelePhone(ybmj.getDh());
                    sysUserVo.setIdEntityCard(ybmj.getSfzh());
                    sysUserVo.setInDustRialId(ybmj.getJh());
                    //计算男女
                    int gender = Integer.parseInt(ybmj.getSfzh().substring(16, 17));
                    if (gender % 2 == 1) {
                        sysUserVo.setSex("0");
                    } else {
                        sysUserVo.setSex("1");
                    }
                    sysUserVo.setNation("01");
                    sysUserVo.setType("01");
                    sysUserVo.setIsVirtualUser("2");
                    sysUserVo.setSfrh("0");
                    UserInfo userInfo = UserInfoManager.get();
                    // 获取ip地址
//                    String ipAddress = IpUtil.getIpAddress(servletRequest);
//                    sysUserVo.setXtLrip(ipAddress);
//                    sysUserVo.setXtZhxgrip(ipAddress);
                    // 保存用户信息
                    sysUserService.saveInfo(sysUserVo);
                    ybmjMapper.deleteById(ybmj);
                } else {
                    if (DeletedEnum.DELETED.code.equals(sysUser.getXtZxbz()))
                        return ResponseResult.fail("用户不存在！");
                    SysUserEditVO sysUserEditVo = new SysUserEditVO();
                    sysUserEditVo.setSsbmdm(ybmj.getSsbmdm());
                    sysUserEditVo.setLoginName(ybmj.getXm());
//                    sysUserEditVo.setPassword("E10ADC3949BA59ABBEcm9OiHRC56E057F20F883E");
                    sysUserEditVo.setUserName(ybmj.getXm());
                    sysUserEditVo.setUserType("01");
                    sysUserEditVo.setMobile(ybmj.getDh());
                    sysUserEditVo.setTelePhone(ybmj.getDh());
                    sysUserEditVo.setIdEntityCard(ybmj.getSfzh());
                    sysUserEditVo.setInDustRialId(ybmj.getJh());
                    //计算男女
                    int gender = Integer.parseInt(ybmj.getSfzh().substring(16, 17));
                    if (gender % 2 == 1) {
                        sysUserEditVo.setSex("1");
                    } else {
                        sysUserEditVo.setSex("2");
                    }
                    sysUserEditVo.setNation("01");
                    sysUserEditVo.setType("01");
                    sysUserEditVo.setIsVirtualUser("2");
                    sysUserEditVo.setSfrh("0");
                    sysUserEditVo.setId(sysUser.getId());
                    UserInfo userInfo = UserInfoManager.get();
                    sysUserService.editInfo(sysUserEditVo, sysUser);
                    ybmjMapper.deleteById(ybmj);
                }
            }
            return ResponseResult.success(Boolean.TRUE);
        }
        return null;
    }


    @JwtSysUser
    @PostMapping("editSysUser")
    @Log(title = "用户功能--编辑用户信息", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "编辑用户信息", httpMethod = "POST", response = Boolean.class)
    public ResponseResult<Boolean> editSysUser(@RequestBody @Valid SysUserEditVO sysUserEditVo) {

        Long id = sysUserEditVo.getId();
        SysUser sysUser = sysUserService.getUserInfo(id);
        if (sysUser == null || DeletedEnum.DELETED.code.equals(sysUser.getXtZxbz()))
            return ResponseResult.fail("用户不存在！");
        sysUserService.editInfo(sysUserEditVo, sysUser);
        return ResponseResult.success(Boolean.TRUE);
    }

    @JwtSysUser
    @PostMapping("editPassword")
    @Log(title = "用户功能--编辑密码", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "编辑密码", httpMethod = "POST", response = Boolean.class)
    public ResponseResult<Boolean> editPassword(@RequestBody @Valid SysUserEditPasswordRequest sysUserEditPasswordRequest) {
        sysUserService.editPassword(sysUserEditPasswordRequest);
        return ResponseResult.success(Boolean.TRUE);
    }

    @GetMapping("resetPassword")
    @Log(title = "用户功能--重置密码", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "重置密码", httpMethod = "POST", response = Boolean.class)
    public ResponseResult<Boolean> resetPassword(@RequestParam("userId") Long userId) {
        SysUser user = sysUserService.getUserInfo(userId);

        Asserts.check(user == null || DeletedEnum.DELETED.code.equals(user.getXtZxbz()),
                "用户不存在或已删除");

        sysUserService.resetPassword(user);
        return ResponseResult.success(Boolean.TRUE);
    }

    @GetMapping("getUserInfo/{id}")
    @JwtSysUser
    @ApiOperation(value = "查询用户信息", httpMethod = "GET", response = SysUserInfoVO.class)
    public ResponseResult<SysUserInfoVO> getUserInfo(@PathVariable("id") Long id) {
        UserInfo user1 = UserInfoManager.get();
        SysUser user = sysUserService.getUserInfo(id);
        Asserts.check(user == null || DeletedEnum.DELETED.code.equals(user.getXtZxbz()),
                "用户不存在或已删除");
        List<Long> deptIds = sysUserDeptService.listByUserId(user.getId());
        SysUserInfoVO sysUserInfoVO = BeanUtil.copyProperties(user, SysUserInfoVO.class);
        if (!CollectionUtils.isEmpty(deptIds)) {
            sysUserInfoVO.setDeptIds(deptIds);
            SysDept dept = sysDeptService.getById(deptIds.get(0));
            if (dept != null) {
                sysUserInfoVO.setSsbm(dept.getOrgName());
                sysUserInfoVO.setSsbmdm(dept.getOrgCode());
            }
        }
        return ResponseResult.success(sysUserInfoVO);
    }

    @GetMapping("selectUnAccreditPage")
    @ApiOperation(value = "分页查询未绑定当前角色的用户", httpMethod = "GET", response = SysRole.class)
    public ResponseResult<IPage<SysUserVO>> selectUnAccreditPage(UserPage userPage) {
        IPage<SysUserVO> roleIPage = sysUserService.selectUnAccreditPage(userPage);
        return ResponseResult.success(roleIPage);
    }

    @GetMapping("selectPage")
    @JwtSysUser
    @ApiOperation(value = "分页查询用户信息", httpMethod = "GET", response = SysUserVO.class)
    public ResponseResult<IPage<SysUserVO>> selectPage(UserPage userPage) {
        IPage<SysUserVO> userVoPage = sysUserService.selectByPage(userPage);
        return ResponseResult.success(userVoPage);
    }

    @GetMapping("getUserList")
    @JwtSysUser
    @ApiOperation(value = "根据条件查询用户信息", httpMethod = "GET", response = SysUserVO.class)
    public ResponseResult<List<SysUserVO>> getUserList(GetUserPage dto) {
        return ResponseResult.success(sysUserService.getUserList(dto));
    }


    @PostMapping("selectUserDeptPage")
    @JwtSysUser
    @ApiOperation(value = "查询用户和部门分页", httpMethod = "POST", response = SysRole.class)
    public ResponseResult<IPage<SysUserDeptVO>> selectUserDeptPage(@RequestBody UserDeptPage userDeptPage) {
        IPage<SysUserDeptVO> sysUserDeptVOIPage = sysUserService.selectUserDeptPage(userDeptPage);
        return ResponseResult.success(sysUserDeptVOIPage);
    }

    @JwtSysUser
    @GetMapping("getPasswordLevel")
    @ApiOperation(value = "当前系统的密码等级", httpMethod = "GET", response = Integer.class)
    public ResponseResult<Integer> getPasswordLevel() {
        UserInfo userInfo = UserInfoManager.get();
        SysConfig config = sysConfigService.getOneByKey(ConfigKeyEnum.PASSWORD_LEVEL);
        if (Objects.isNull(config)) {
            return ResponseResult.success(PasswordLevelEnum.PASSWORD_LEVEL_ONE.code);
        }
        return ResponseResult.success(Integer.valueOf(config.getPzz()));
    }

    @JwtSysUser
    @PostMapping("deleteSysUser")
    @Log(title = "删除用户", businessType = BusinessType.DELETE)
    @ApiOperation(value = "删除用户", httpMethod = "POST", response = Boolean.class)
    public ResponseResult<Boolean> deleteSysRole(@RequestBody DeleteVO deleteVO, HttpServletRequest servletRequest) {
        SysUser oldSysUser = sysUserService.getBaseMapper().selectById(deleteVO.getId());
        if (oldSysUser == null)
            return ResponseResult.fail("用户不存在或已删除");
        // 获取ip地址
        String ipAddress = IpUtil.getIpAddress(servletRequest);
        sysUserService.delById(oldSysUser.getId());
        //  删除关联角色
        this.sysUserRoleMapper.delete(
                new LambdaQueryWrapper<SysUserRole>()
                        .eq(SysUserRole::getUserId, oldSysUser.getId())
        );
        // 删除关联部门
        this.sysUserDeptMapper.delete(
                new LambdaQueryWrapper<SysUserDept>()
                        .eq(SysUserDept::getUserId, oldSysUser.getId())
        );
        return ResponseResult.success(Boolean.TRUE);
    }

    @GetMapping("userSys")
    @ApiOperation(value = "用户信息同步", httpMethod = "GET", response = Boolean.class)
    public ResponseResult<Boolean> userSys() {
        Boolean bool = sysUserService.userSys();
        return ResponseResult.success(bool);
    }

}
