package com.willalp.web.controller.system;

import com.willalp.common.annotation.Log;
import com.willalp.common.core.controller.BaseController;
import com.willalp.common.core.domain.AjaxResult;
import com.willalp.common.core.domain.entity.SysDept;
import com.willalp.common.core.page.TableDataInfo;
import com.willalp.common.enums.BusinessType;
import com.willalp.common.exception.base.BaseException;
import com.willalp.common.utils.StringUtils;
import com.willalp.system.domain.SysUserOrganization;
import com.willalp.system.service.ISysDeptService;
import com.willalp.system.service.ISysUserOrganizationService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/system/bindUO")
public class SysUserOrganizationController extends BaseController {

    @Resource
    private ISysUserOrganizationService uoService;

    @Resource
    private ISysDeptService deptService;


    /**
     * 获取用户机构绑定列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SysUserOrganization userOrganization) {
        startPage();
        List<SysUserOrganization> list = uoService.selectSysUserOrganizationList(userOrganization);
        return getDataTable(list);
    }

    @RequestMapping("/orgDateList")
    public AjaxResult getOrgData() {
        List<SysDept> sysDepts = deptService.selectAllParentDeptList();
        return AjaxResult.success(sysDepts);
    }

    /**
     * 获取机构绑定详细信息
     */
    @GetMapping(value = "/{uoId}")
    public AjaxResult getInfo(@PathVariable("uoId") String uoId) {
        return AjaxResult.success(uoService.getById(uoId));
    }


    /**
     * 新增机构绑定
     */
    @Log(title = "机构绑定", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUserOrganization uo) {
        String organizationCode = uo.getOrganizationCode();
        String loginName = uo.getLoginName();
        String userType = uo.getUserType();
        if (StringUtils.isNotBlank(organizationCode) && StringUtils.isNotBlank(loginName) && StringUtils.isNotBlank(userType)) {
            return toAjax(uoService.save(uo));
        }
        throw new BaseException("信息不完整请选择正确的数据");
    }

    /**
     * 修改绑定信息
     */
    @Log(title = "修改绑定信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUserOrganization uo) {
        return toAjax(uoService.updateById(uo));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{uoIds}")
    public AjaxResult remove(@PathVariable Long[] uoIds) {
        return toAjax(uoService.removeByIds(Arrays.asList(uoIds)));
    }
}
