package com.ruoyi.mall.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.crypto.SmUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.mall.domain.MallCompany;
import com.ruoyi.mall.service.IMallCompanyService;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.mall.domain.MallCompanyUser;
import com.ruoyi.mall.service.IMallCompanyUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 公司基站管理员Controller
 *
 * @author LCL
 * @date 2024-03-12
 */
@RestController
@RequestMapping("/mall/mallCompanyUser")
public class MallCompanyUserController extends BaseController
{
    @Resource
    private IMallCompanyUserService mallCompanyUserService;
    @Resource
    private IMallCompanyService mallCompanyService;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysUserService userService;

    /**
     * 查询公司基站管理员列表
     */
    @PreAuthorize("@ss.hasPermi('mall:mallCompanyUser:list')")
    @GetMapping("/list")
    public TableDataInfo list(MallCompanyUser mallCompanyUser)
    {
        // 获取登陆用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUserRole sysUserRole = sysUserRoleMapper.selectSysUserRoleByUserId(loginUser.getUserId());
        if (sysUserRole != null) {
            // 公司角色
            if (sysUserRole.getRoleId() == 100) {
                MallCompany company = mallCompanyService.selectMallCompanyByCompanySysUserId(loginUser.getUserId());
                if (company != null) {
                    mallCompanyUser.setCompanyId(company.getCompanyId());
                }
            }
        }

        startPage();
        List<MallCompanyUser> list = mallCompanyUserService.selectMallCompanyUserList(mallCompanyUser);
        return getDataTable(list);
    }

    /**
     * 导出公司基站管理员列表
     */
    @PreAuthorize("@ss.hasPermi('mall:mallCompanyUser:export')")
    @Log(title = "公司基站管理员", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MallCompanyUser mallCompanyUser)
    {
        List<MallCompanyUser> list = mallCompanyUserService.selectMallCompanyUserList(mallCompanyUser);
        ExcelUtil<MallCompanyUser> util = new ExcelUtil<MallCompanyUser>(MallCompanyUser.class);
        util.exportExcel(response, list, "公司基站管理员数据");
    }

    /**
     * 获取公司基站管理员详细信息
     */
    @PreAuthorize("@ss.hasPermi('mall:mallCompanyUser:query')")
    @GetMapping(value = "/{companyUserId}")
    public AjaxResult getInfo(@PathVariable("companyUserId") Long companyUserId)
    {
        return AjaxResult.success(mallCompanyUserService.selectMallCompanyUserByCompanyUserId(companyUserId));
    }

    /**
     * 新增公司基站管理员
     */
    @PreAuthorize("@ss.hasPermi('mall:mallCompanyUser:add')")
    @Log(title = "公司基站管理员", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MallCompanyUser mallCompanyUser)
    {
        if (mallCompanyUser.getCompanyUserHead() == null) {
            mallCompanyUser.setCompanyUserHead("https://image.xnszz.com/IMG_300_300@Fs-3FIRog9kVRp3Zn7F6R5SIpE3U.png");
        }
        MallCompanyUser companyUser = mallCompanyUserService.selectMallCompanyUserByCompanyUserAccount(mallCompanyUser.getCompanyUserAccount());
        if (companyUser != null) {
            return AjaxResult.error("公司基站管理员账号已存在");
        } else {
            mallCompanyUserService.insertMallCompanyUser(mallCompanyUser);
        }
        return AjaxResult.success();
    }

    /**
     * 修改公司基站管理员
     */
    @PreAuthorize("@ss.hasPermi('mall:mallCompanyUser:edit')")
    @Log(title = "公司基站管理员", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MallCompanyUser mallCompanyUser)
    {
        MallCompanyUser companyUser = mallCompanyUserService.selectMallCompanyUserByCompanyUserAccount(mallCompanyUser.getCompanyUserAccount());
        if (companyUser != null && !companyUser.getCompanyUserId().equals(mallCompanyUser.getCompanyUserId())) {
            return AjaxResult.error("公司基站管理员账号已存在");
        } else {
            //账号
            String account = mallCompanyUser.getCompanyUserAccount();
            //密码
            // String password = mallCompanyUser.getCompanyUserPassword();

            // mallCompanyUser.setCompanyUserPassword(SecurityUtils.encryptPassword(password));

            // 修改系统用户
            SysUser sysUser = new SysUser();
            sysUser.setUserId(mallCompanyUser.getSysUserId());
            sysUser.setUserName(account);
            sysUser.setNickName(mallCompanyUser.getCompanyUserName());
            sysUser.setStatus(mallCompanyUser.getCompanyUserStatus());
            // sysUser.setPassword(SecurityUtils.encryptPassword(password));
            sysUserService.updateUser(sysUser);

            // 新增用户与角色管理
            SysUserRole ur = new SysUserRole();
            ur.setUserId(sysUser.getUserId());
            ur.setRoleId(101L);// 账号类型 101-基站管理员
            sysUserRoleMapper.insertUserRole(ur);

            mallCompanyUserService.updateMallCompanyUser(mallCompanyUser);
        }
        return AjaxResult.success();
    }

    /**
     * 删除公司基站管理员
     */
    @PreAuthorize("@ss.hasPermi('mall:mallCompanyUser:remove')")
    @Log(title = "公司基站管理员", businessType = BusinessType.DELETE)
	@DeleteMapping("/{companyUserIds}")
    public AjaxResult remove(@PathVariable Long[] companyUserIds)
    {
        List<Long> list = new ArrayList<>();
        for (Long userId : companyUserIds) {
            MallCompanyUser companyUser = mallCompanyUserService.selectMallCompanyUserByCompanyUserId(userId);
            if (companyUser != null && companyUser.getSysUserId() != null) {
                list.add(companyUser.getSysUserId());
            }
        }
        Long[] longs = list.toArray(new Long[0]);
        sysUserService.deleteUserByIds(longs);
        return toAjax(mallCompanyUserService.deleteMallCompanyUserByCompanyUserIds(companyUserIds));
    }

    /**
     * 获取公司基站管理员列表
     *
     * @return 获取公司基站管理员集合
     */
    @GetMapping("/getCompanyUser")
    public AjaxResult getCompanyUser() {
        HashMap<String,Object> map = new HashMap<>();
        MallCompanyUser mallCompanyUser = new MallCompanyUser();
        // 获取登陆用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUserRole sysUserRole = sysUserRoleMapper.selectSysUserRoleByUserId(loginUser.getUserId());
        if (sysUserRole != null) {
            // 公司角色
            if (sysUserRole.getRoleId() == 100) {
                MallCompany company = mallCompanyService.selectMallCompanyByCompanySysUserId(loginUser.getUserId());
                if (company != null) {
                    mallCompanyUser.setCompanyId(company.getCompanyId());
                }
            }
        }
        List<MallCompanyUser> list = mallCompanyUserService.selectMallCompanyUserList(mallCompanyUser);
        map.put("data",list);
        return AjaxResult.success(map);
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('mall:mallCompanyUser:edit')")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody MallCompanyUser mallCompanyUser)
    {
        MallCompanyUser companyUser = mallCompanyUserService.selectMallCompanyUserByCompanyUserId(mallCompanyUser.getCompanyUserId());
        if (companyUser != null && companyUser.getSysUserId() != null) {
            SysUser user = new SysUser();
            user.setUserId(companyUser.getSysUserId());
            userService.checkUserAllowed(user);
            userService.checkUserDataScope(user.getUserId());
            user.setPassword(SecurityUtils.encryptPassword(mallCompanyUser.getCompanyUserPassword()));
            user.setUpdateBy(getUsername());
            userService.resetPwd(user);

            mallCompanyUser.setCompanyUserPassword(SecurityUtils.encryptPassword(mallCompanyUser.getCompanyUserPassword()));
            mallCompanyUserService.updateMallCompanyUser(mallCompanyUser);
        }
        return AjaxResult.success();
    }
}
