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.MallCompanyUser;
import com.ruoyi.set.domain.SetRegion;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
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.MallCompany;
import com.ruoyi.mall.service.IMallCompanyService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 公司Controller
 *
 * @author LCL
 * @date 2024-03-12
 */
@RestController
@RequestMapping("/mall/mallCompany")
public class MallCompanyController extends BaseController
{
    @Resource
    private IMallCompanyService mallCompanyService;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private ISysUserService userService;

    /**
     * 查询公司列表
     */
    @PreAuthorize("@ss.hasPermi('mall:mallCompany:list')")
    @GetMapping("/list")
    public TableDataInfo list(MallCompany mallCompany)
    {
        startPage();
        List<MallCompany> list = mallCompanyService.selectMallCompanyList(mallCompany);
        return getDataTable(list);
    }

    /**
     * 导出公司列表
     */
    @PreAuthorize("@ss.hasPermi('mall:mallCompany:export')")
    @Log(title = "公司", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MallCompany mallCompany)
    {
        List<MallCompany> list = mallCompanyService.selectMallCompanyList(mallCompany);
        ExcelUtil<MallCompany> util = new ExcelUtil<MallCompany>(MallCompany.class);
        util.exportExcel(response, list, "公司数据");
    }

    /**
     * 获取公司详细信息
     */
    @PreAuthorize("@ss.hasPermi('mall:mallCompany:query')")
    @GetMapping(value = "/{companyId}")
    public AjaxResult getInfo(@PathVariable("companyId") Long companyId)
    {
        return AjaxResult.success(mallCompanyService.selectMallCompanyByCompanyId(companyId));
    }

    /**
     * 新增公司
     */
    @PreAuthorize("@ss.hasPermi('mall:mallCompany:add')")
    @Log(title = "公司", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MallCompany mallCompany)
    {
        MallCompany company = mallCompanyService.selectMallCompanyByCompanyAccount(mallCompany.getCompanyAccount());
        if (company != null) {
            return AjaxResult.error("公司账号已存在");
        } else {
            mallCompanyService.insertMallCompany(mallCompany);
        }
        return AjaxResult.success();
    }

    /**
     * 修改公司
     */
    @PreAuthorize("@ss.hasPermi('mall:mallCompany:edit')")
    @Log(title = "公司", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MallCompany mallCompany)
    {
        MallCompany company = mallCompanyService.selectMallCompanyByCompanyAccount(mallCompany.getCompanyAccount());
        if (company != null && !company.getCompanyId().equals(mallCompany.getCompanyId())) {
            return AjaxResult.error("公司账号已存在");
        } else {
            mallCompany.setProvinceName(null);
            mallCompany.setCityName(null);
            mallCompany.setAreaName(null);

            //账号
            String account = mallCompany.getCompanyAccount();
            //密码
            // String password = mallCompany.getCompanyPassword();

            // mallCompany.setCompanyPassword(SecurityUtils.encryptPassword(password));

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

            // 新增用户与角色管理
            SysUserRole ur = new SysUserRole();
            ur.setUserId(sysUser.getUserId());
            ur.setRoleId(100L);// 账号类型（100-公司
            sysUserRoleMapper.insertUserRole(ur);

            mallCompanyService.updateMallCompany(mallCompany);
        }
        return AjaxResult.success();
    }

    /**
     * 删除公司
     */
    @PreAuthorize("@ss.hasPermi('mall:mallCompany:remove')")
    @Log(title = "公司", businessType = BusinessType.DELETE)
	@DeleteMapping("/{companyIds}")
    public AjaxResult remove(@PathVariable Long[] companyIds)
    {
        List<Long> list = new ArrayList<>();
        for (Long companyId : companyIds) {
            MallCompany company = mallCompanyService.selectMallCompanyByCompanyId(companyId);
            if (company != null && company.getSysUserId() != null) {
                list.add(company.getSysUserId());
            }
        }
        Long[] longs = list.toArray(new Long[0]);
        sysUserService.deleteUserByIds(longs);
        return toAjax(mallCompanyService.deleteMallCompanyByCompanyIds(companyIds));
    }

    /**
     * 获取公司列表
     *
     * @param id 行政区域主键ID
     * @return 行政区域集合
     */
    @GetMapping("/getCompany")
    public AjaxResult getCompany() {
        HashMap<String,Object> map = new HashMap<>();
        MallCompany mallCompany = new MallCompany();
        mallCompany.setDelFlag("0");

        // 获取登陆用户
        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) {
                    mallCompany.setCompanyId(company.getCompanyId());
                }
            }
        }
        List<MallCompany> list = mallCompanyService.selectMallCompanyList(mallCompany);
        map.put("data",list);
        return AjaxResult.success(map);
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('mall:mallCompany:edit')")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody MallCompany mallCompany)
    {
        MallCompany company = mallCompanyService.selectMallCompanyByCompanyId(mallCompany.getCompanyId());
        if (company != null && company.getSysUserId() != null) {
            SysUser user = new SysUser();
            user.setUserId(company.getSysUserId());
            userService.checkUserAllowed(user);
            userService.checkUserDataScope(user.getUserId());
            user.setPassword(SecurityUtils.encryptPassword(mallCompany.getCompanyPassword()));
            user.setUpdateBy(getUsername());
            userService.resetPwd(user);

            mallCompany.setCompanyPassword(SecurityUtils.encryptPassword(mallCompany.getCompanyPassword()));
            mallCompanyService.updateMallCompany(mallCompany);
        }
        return AjaxResult.success();
    }
}
