package com.testor.module.ZLOA.sysUserOA.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.testor.biz.file.FileEnumCode;
import com.testor.biz.file.model.domain.TSysFileBiz;
import com.testor.biz.file.service.TSysFileBizService;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.biz.sys.post.model.domain.TSysPost;
import com.testor.biz.sys.post.service.TSysPostService;
import com.testor.biz.sys.user.UserEnumCode;
import com.testor.biz.sys.user.UserHelper;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.model.dto.SysUserChangePwdRequest;
import com.testor.biz.sys.user.model.dto.SysUserCreateAndUpdateRequest;
import com.testor.biz.sys.user.model.dto.SysUserResponse;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.module.sys.service.AccountLockService;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.exceptions.ApiException;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @title SysUserControllerS
 * @description <TODO description class purpose>
 * @Author: qiao
 * @version:1.0.0
 * @create：8/1/23 10:02 AM
 */
@RestController
@Api(value = "Login ControllerS", tags = {"用户模块"})
@RequestMapping({"/sys/user"})
@Slf4j
public class SysUserControllerS extends SuperController {

    @Autowired
    private TSysFileBizService tSysFileBizService;

    @Autowired
    private SysOrgService sysOrgService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private TSysPostService tSysPostService;

    @Autowired
    private AccountLockService accountLockService;


    @ApiOperation(
            value = "根据用户ID查询用户信息",
            notes = "根据用户ID查询用户信息 get User By Id"
    )
    @GetMapping({"/get"})
    public BaseResponse<SysUserResponse> getEntity() {
        BaseResponse<SysUserResponse> baseResponse = new BaseResponse();
        UserInfo loginUser = ContextUtils.getLoginUser();

        if (StringHelper.isEmpty(loginUser.getUserId())) {
            throw new ApiException(UserEnumCode.USER_ID_ERROR.transform());
        } else {
            SysUser user = (SysUser) this.sysUserService.getById(loginUser.getUserId());
            if (ObjectHelper.isEmpty(user)) {
                throw new ApiException(UserEnumCode.USER_ID_ERROR.transform());
            } else {
                SysUserResponse sysUserResponse = (SysUserResponse) BeanHelper.beanToBean(user, SysUserResponse.class);
                SysOrg org = (SysOrg) this.sysOrgService.getById(user.getOrgId());
                if (!ObjectHelper.isEmpty(org)) {
                    sysUserResponse.setOrgName(org.getOrgName());
                }

                baseResponse.setData(sysUserResponse);
                return baseResponse;
            }
        }
    }

    @ApiOperation(
            value = "【新增用户基本信息】",
            notes = "新增用户基本信息 Add user"
    )
    @PostMapping({"/add"})
    public BaseResponse<SysUser> addEntity(@Valid @RequestBody SysUserCreateAndUpdateRequest addRequest) {
        BaseResponse<SysUser> baseResponse = new BaseResponse();
        if (ObjectHelper.isEmpty(addRequest)) {
            throw new ApiException(UserEnumCode.USER_PARAM_IS_NULL.transform());
        } else if (StringHelper.isEmpty(addRequest.getLoginPwd())) {
            throw new ApiException(UserEnumCode.REQUIRED_ITEMS_MISSING.transform());
        } else if (!StringHelper.isEmpty(addRequest.getOrgId()) && !ObjectHelper.isEmpty(this.sysOrgService.getById(addRequest.getOrgId()))) {
            SysUser existsSysUser = (SysUser) this.sysUserService.getOne((Wrapper) ((QueryWrapper) ((QueryWrapper) (new QueryWrapper()).eq("login_name", addRequest.getLoginName())).ne("status", "1")).last("LIMIT 1"));
            if (ObjectHelper.isNotEmpty(existsSysUser)) {
                throw new ApiException(UserEnumCode.LOGIN_NAME_ALREADY_EXISTS.transform());
            } else {
                String userId = IdHelper.getId32bit();
                if (ObjectHelper.isNotEmpty(addRequest.getFiles()) && !addRequest.getFiles().isEmpty()) {
                    List<TSysFileBiz> fileBizList = addRequest.getFiles();
                    boolean fileBizResult = this.tSysFileBizService.saveFileBizs(fileBizList, userId, this.getUserId());
                    if (!fileBizList.isEmpty() && !fileBizResult) {
                        throw new ApiException(FileEnumCode.FILE_BIZ_SAVE_FAILED.transform());
                    }
                }

                SysUser data = (SysUser) BeanHelper.beanToBean(addRequest, SysUser.class);
                SysOrg one = (SysOrg) this.sysOrgService.getOne((Wrapper) ((QueryWrapper) (new QueryWrapper()).eq("org_id", data.getOrgId())).ne("status", "1"));
                data.setOrgName(one.getOrgName());
                data.setOrgId(one.getParentId());
                data.setDeptId(addRequest.getOrgId());
                TSysPost tSysPost = (TSysPost) this.tSysPostService.getOne((Wrapper) ((QueryWrapper) (new QueryWrapper()).eq("id", data.getPostId())).ne("status", "1"));
                if (ObjectHelper.isNotEmpty(tSysPost)) {
                    data.setPostName(tSysPost.getPostName());
                }

                if (StringHelper.isEmpty(data.getLoginPwd())) {
                    data.setLoginPwd("ZLmy1110!@#$%^&*");
                }

                data.setLoginPwd(UserHelper.userPassword(data.getLoginPwd()));
                data.setUserId(userId);
                this.sysUserService.save(data);
                return baseResponse;
            }
        } else {
            throw new ApiException(UserEnumCode.USER_ORG_ID_ERROR.transform());
        }
    }

    @ApiOperation(
            value = "重置用户密码",
            notes = "重置用户密码 reset password"
    )
    @PutMapping({"/password/reset"})
    public BaseResponse<BizGeneralResponse> passwordResetEntity(@RequestBody SysUserChangePwdRequest pwdRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse();
        SysUser user = (SysUser) this.sysUserService.getById(pwdRequest.getUserId());
        boolean result = false;
        if (ObjectHelper.isNotEmpty(user)) {
            user.setLoginPwd(UserHelper.userPassword("ZLmy1110!@#$%^&*"));
            result = this.sysUserService.updateById(user);
            accountLockService.resetAttempts(user.getLoginName());
            accountLockService.resetLocked(user.getLoginName());
        }

        baseResponse.setData(BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        return baseResponse;
    }
}
