package com.app.admin.framework.system.administrator.controller;

import cn.hutool.crypto.SecureUtil;
import com.app.admin.framework.system.administrator.model.SysAdministrator;
import com.app.admin.framework.system.administrator.service.SysAdministratorService;
import com.app.admin.framework.system.administrator.view.SysAdministratorView;
import com.app.admin.framework.system.organization.model.SysOrganization;
import com.app.admin.framework.system.organization.service.SysOrganizationService;
import com.app.framework.core.log.annotation.LogOps;
import com.app.framework.core.log.constant.LogOpsType;
import com.app.framework.core.support.auth.LoginUser;
import com.app.framework.core.support.controller.CrudBaseControllerSupport;
import com.app.framework.core.support.enums.BaseEnum;
import com.app.framework.core.support.enums.common.StateEnum;
import com.app.framework.core.support.view.form.AjaxResult;
import com.app.framework.core.support.view.form.ModelEditForm;
import com.app.framework.core.support.view.grid.Paging;
import com.app.framework.core.utils.pwd.PasswordUtil;
import com.app.framework.core.utils.request.SessionUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统用户管理
 */
@Controller
@RequestMapping("/sys/user")
public class SysAdministratorController extends CrudBaseControllerSupport<SysAdministratorView> {

    @Autowired
    SysAdministratorService sysAdministratorService;
    @Autowired
    SysOrganizationService sysOrganizationService;

    /**
     * 查询列表的具体实现
     * 租户管理员在租户管理处,故此处用户管理只需管理类型为2
     *
     * @param request HttpServletRequest
     * @param view    查询条件
     * @param paging  分页条件
     * @return 查询结果
     */
    @Override
    public List<SysAdministratorView> list(HttpServletRequest request, SysAdministratorView view, Paging paging) {
        LoginUser loginUser = SessionUtil.getCurrentUser(request);
        view.setOrganizationId(loginUser.getOrganizationId());
        List<SysAdministrator> list = sysAdministratorService.getPageList(view, paging);
        return list.stream().map(a -> {
            SysAdministratorView aview = new SysAdministratorView();
            BeanUtils.copyProperties(a, aview);
            if (a.getDeptId() != null) {
                SysOrganization dept = sysOrganizationService.getById(a.getDeptId());
                aview.setDeptName(dept.getName());
            }
            return aview;
        }).collect(Collectors.toList());
    }

    /**
     * 保存记录的具体实现
     *
     * @param request HttpServletRequest
     * @param entity  对象
     * @return View对象
     */
    @Override
    public AjaxResult saveEntity(HttpServletRequest request, SysAdministratorView entity) {
        LoginUser loginUser = SessionUtil.getCurrentUser(request);
        entity.setOrganizationId(loginUser.getOrganizationId());
        return sysAdministratorService.saveSysUser(entity, loginUser);
    }

    /**
     * 删除记录,根据Id 具体实现
     *
     * @param request HttpServletRequest
     * @param oids    实体
     */
    @Override
    public AjaxResult batchDelete(HttpServletRequest request, Long oids[]) {
        for (Long oid : oids) {
            sysAdministratorService.updateState(oid, StateEnum.DELETE);
        }
        return AjaxResult.wrap(true);
    }

    /**
     * 跳转到列表页面
     */
    @RequestMapping(value = "/golist")
    public ModelAndView golist(HttpServletRequest request) {
        return new ModelAndView("admin/framework/system/administrator/list.html");
    }

    /**
     * 跳转到编辑页面
     */
    @RequestMapping(value = "/edit")
    public ModelAndView edit(HttpServletRequest request, SysAdministrator entity, ModelEditForm modelEditForm) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        if (entity.getOid() != null) {
            entity = sysAdministratorService.getById(entity.getOid());
        }
        if (entity.getDeptId() != null) {
            SysOrganization dept = sysOrganizationService.getById(entity.getDeptId());
            map.put("dept", dept);
        } else {
            LoginUser loginUser = SessionUtil.getCurrentUser(request);
            SysOrganization dept = sysOrganizationService.getById(loginUser.getOrganizationId());
            map.put("dept", dept);
        }
        map.put("entity", entity);
        map.put("editForm", modelEditForm);
        return new ModelAndView("admin/framework/system/administrator/edit.html", map);
    }

    @RequestMapping(value = "/updateStatus")
    @LogOps(type = LogOpsType.UPDATE)
    public @ResponseBody AjaxResult updateStatus(Long oid, Integer state) {
        sysAdministratorService.updateState(oid, BaseEnum.getByValue(StateEnum.class, state));
        return AjaxResult.wrap(true);
    }

    /**
     * 跳转到修改密码页面
     */
    @RequestMapping(value = "/password")
    public ModelAndView password(HttpServletRequest request) {

        return new ModelAndView("admin/framework/system/administrator/password.html");
    }

    /**
     * 修改密码
     *
     * @param userPwd  旧密码
     * @param password 新密码
     */
    @RequestMapping(value = "/updatePwd")
    @LogOps(type = LogOpsType.UPDATE)
    public @ResponseBody AjaxResult updatePwd(HttpServletRequest request, String userPwd, String password) {
        LoginUser loginUser = SessionUtil.getCurrentUser(request);
        SysAdministrator sysUser = sysAdministratorService.getById(loginUser.getId());
        if (userPwd.length() <= 16) {
            userPwd = SecureUtil.md5(userPwd);
        }
        if (password.length() <= 16) {
            password = SecureUtil.md5(password);
        }
        if (PasswordUtil.equalsPwd(userPwd, sysUser.getPassword())) {//旧密码正确
            return sysAdministratorService.updateUserPwd(sysUser.getOid(), password);
        } else {
            return AjaxResult.wrapError("旧密码输入有误");
        }
    }

    /**
     * 重置密码
     */
    @RequestMapping(value = "/resetPwd")
    @LogOps(type = LogOpsType.UPDATE)
    public @ResponseBody AjaxResult resetPwd(Long oid) {
        sysAdministratorService.updateUserPwd(oid, LoginUser.DEFAULT_PWD);
        return AjaxResult.wrap(true);
    }

    /**
     * 跳转到修改头像页面
     */
    @RequestMapping(value = "/editHeadImgUrl")
    public ModelAndView editHeadImgUrl(HttpServletRequest request) {
        LoginUser loginUser = SessionUtil.getCurrentUser(request);
        HashMap<String, Object> map = new HashMap<String, Object>();
        SysAdministrator entity = sysAdministratorService.getById(loginUser.getId());
        map.put("entity", entity);
        return new ModelAndView("admin/framework/system/administrator/headImg.html", map);
    }

    /**
     * 修改头像
     */
    @RequestMapping(value = "/saveHeadImgUrl")
    public @ResponseBody AjaxResult updateHeadImgUrl(HttpServletRequest request, String headImgUrl) {
        LoginUser loginUser = SessionUtil.getCurrentUser(request);
        boolean result = sysAdministratorService.updateHeadImgUrl(loginUser.getId(), headImgUrl);
        return AjaxResult.wrap(result);
    }

    /**
     * 跳转到个人信息页面
     */
    @RequestMapping(value = "/info")
    public ModelAndView info(HttpServletRequest request) {
        LoginUser loginUser = SessionUtil.getCurrentUser(request);
        SysAdministrator entity = sysAdministratorService.getById(loginUser.getId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("entity", entity);
        return new ModelAndView("admin/framework/system/administrator/info.html", map);
    }

    /**
     * 保存个人信息
     *
     * @return
     */
    @RequestMapping(value = "/saveInfo")
    @ResponseBody
    public AjaxResult saveInfo(HttpServletRequest request, SysAdministrator view) {
        LoginUser loginUser = SessionUtil.getCurrentUser(request);
        SysAdministrator entity = sysAdministratorService.getById(loginUser.getId());
        entity.setOid(loginUser.getId());
        entity.setRealName(view.getRealName());
        entity.setMobileTel(view.getMobileTel());
        entity.setEmail(view.getEmail());
        entity.setAppStyle(view.getAppStyle());
        sysAdministratorService.updateById(entity);
        return AjaxResult.wrap(true);
    }

    /**
     * 跳转到选择用户页面
     */
    @RequestMapping(value = "/select")
    public ModelAndView select(HttpServletRequest request) {
        LoginUser loginUser = SessionUtil.getCurrentUser(request);
        HashMap<String, Object> map = new HashMap<>();
        return new ModelAndView("admin/framework/system/administrator/select.html", map);
    }
}
