package com.ruoyi.web.controller.dxp.system.base;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.dxp.constant.DxpConstants;
import com.ruoyi.dxp.dto.UserCompanyDto;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
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.dxp.domain.UserCompany;
import com.ruoyi.dxp.service.IUserCompanyService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 外部用户Controller
 * 
 * @author jy
 * @date 2022-11-08
 */
@RestController
@RequestMapping("/system/base/company")
public class UserCompanyController extends BaseController
{
    @Autowired
    private IUserCompanyService userCompanyService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysRoleService sysRoleService;

    /**
     * 查询外部用户列表
     */
    @PreAuthorize("@ss.hasPermi('system/base:company:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserCompanyDto userCompany)
    {
        startPage();
        List<UserCompanyDto> list = userCompanyService.selectUserCompanyList(userCompany);
        return getDataTable(list);
    }

    /**
     * 导出外部用户列表
     */
    @PreAuthorize("@ss.hasPermi('system/base:company:export')")
    @Log(title = "外部用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UserCompanyDto userCompany)
    {
        List<UserCompanyDto> list = userCompanyService.selectUserCompanyList(userCompany);
        ExcelUtil<UserCompanyDto> util = new ExcelUtil<UserCompanyDto>(UserCompanyDto.class);
        util.exportExcel(response, list, "外部用户数据");
    }

    /**
     * 获取外部用户详细信息
     */
    @PreAuthorize("@ss.hasPermi('system/base:company:query')")
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId)
    {
        return success(userCompanyService.selectUserCompanyByUserId(userId));
    }

    /**
     * 新增外部用户
     */
    @PreAuthorize("@ss.hasPermi('system/base:company:add')")
    @Log(title = "外部用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserCompanyDto userCompany)
    {
        try {
            // 新增用户
            SysUser sysUser = new SysUser();
            BeanUtils.copyProperties(userCompany, sysUser);
            sysUser.setNickName(userCompany.getLinkMan());
            sysUser.setUserType(DxpConstants.USER_TYPE_COMPANY); // 企业用户
            sysUser.setCreateBy(getUsername());
            sysUser.setPassword(SecurityUtils.encryptPassword(userCompany.getPassword()));
            sysUser.setRemark("后台添加");

            // 查询企业用户角色
            SysRole sysRole = new SysRole();
            sysRole.setRoleKey("company");
            List<SysRole> sysRoles = sysRoleService.selectRoleList(sysRole);
            if (sysRoles == null || sysRoles.size() == 0) {
                return error("还未配置外部企业用户角色");
            }
            Long[] roleIds = new Long[1];
            roleIds[0] = sysRoles.get(0).getRoleId();
            sysUser.setRoleIds(roleIds);
            sysUserService.insertUser(sysUser);

            // 新增userCompany
            UserCompany userCompany1 = new UserCompany();
            BeanUtils.copyProperties(userCompany, userCompany1);
            userCompany1.setUserId(sysUser.getUserId());
            userCompanyService.insertUserCompany(userCompany1);
            return success();
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 修改外部用户
     */
    @PreAuthorize("@ss.hasPermi('system/base:company:edit')")
    @Log(title = "外部用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UserCompanyDto userCompany)
    {
        if (userCompany == null || userCompany.getUserId() == null) {
            return error("用户id不能为空");
        }

        try {
            userCompany.setPassword(null);

            // 编辑用户
            SysUser sysUser = sysUserService.selectUserById(userCompany.getUserId());
            if (sysUser == null) {
                return error("用户不存在");
            }

            BeanUtils.copyProperties(userCompany, sysUser);
            sysUserService.updateUser(sysUser);

            // 编辑userCompany
            UserCompany userCompany1 = new UserCompany();
            BeanUtils.copyProperties(userCompany, userCompany1);
            userCompanyService.updateUserCompany(userCompany1);
            return success();
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 删除外部用户
     */
    @PreAuthorize("@ss.hasPermi('system/base:company:remove')")
    @Log(title = "外部用户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        try {
            // 删除用户
            sysUserService.deleteUserByIds(userIds);

            // 删除userCompany
            userCompanyService.deleteUserCompanyByUserIds(userIds);

            return success();
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }
}
