package com.gxwebsoft.oa.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.oa.entity.Company;
import com.gxwebsoft.oa.entity.CompanyUser;
import com.gxwebsoft.oa.param.CompanyParam;
import com.gxwebsoft.oa.service.CompanyService;
import com.gxwebsoft.oa.service.CompanyUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.gxwebsoft.common.core.constants.AppUserConstants.ADMINISTRATOR;

/**
 * 企业信息控制器
 *
 * @author 科技小王子
 * @since 2023-10-23 19:18:58
 */
@Api(tags = "企业信息管理")
@RestController
@RequestMapping("/api/oa/company")
public class CompanyController extends BaseController {
    @Resource
    private CompanyService companyService;
    @Resource
    private CompanyUserService companyUserService;

    @ApiOperation("分页查询企业信息")
    @GetMapping("/page")
    public ApiResult<PageResult<Company>> page(CompanyParam param) {
      final User loginUser = getLoginUser();
      final Integer userId = loginUser.getUserId();
      loginUser.getRoles().forEach(d -> {
        if(!StrUtil.equals(d.getRoleCode(),"superAdmin") && !StrUtil.equals(d.getRoleCode(),"admin")){
          // 非管理员按项目成员权限显示
          final List<CompanyUser> list = companyUserService.list(new LambdaQueryWrapper<CompanyUser>().eq(CompanyUser::getUserId, userId));
          System.out.println("list = " + list);
          final Set<Integer> collect = list.stream().map(CompanyUser::getCompanyId).collect(Collectors.toSet());
          param.setCompanyIds(collect);
        }
      });
      // 使用关联查询
      return success(companyService.pageRel(param));
    }

    @ApiOperation("查询全部企业信息")
    @GetMapping()
    public ApiResult<List<Company>> list(CompanyParam param) {
        PageParam<Company, CompanyParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        return success(companyService.list(page.getOrderWrapper()));
        // 使用关联查询
        //return success(companyService.listRel(param));
    }

    @ApiOperation("根据id查询企业信息")
    @GetMapping("/{id}")
    public ApiResult<Company> get(@PathVariable("id") Integer id) {
        return success(companyService.getById(id));
        // 使用关联查询
        //return success(companyService.getByIdRel(id));
    }

    @ApiOperation("添加企业信息")
    @PostMapping()
    public ApiResult<?> save(@RequestBody Company company) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        CompanyUser companyUser = new CompanyUser();
        if (loginUser != null) {
            company.setUserId(loginUser.getUserId());
            company.setTenantId(loginUser.getTenantId());
          }
          if (companyService.save(company)) {
              // 添加客户所有者
              companyUser.setUserId(loginUser.getUserId());
              companyUser.setNickname(loginUser.getNickname());
              companyUser.setCompanyId(company.getCompanyId());
              companyUser.setRole(ADMINISTRATOR);
              companyUserService.save(companyUser);
              return success("添加成功");
          }
        return fail("添加失败");
    }

    @ApiOperation("修改企业信息")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Company company) {
        if (companyService.updateById(company)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @ApiOperation("删除企业信息")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (companyService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @ApiOperation("批量添加企业信息")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<Company> list) {
        if (companyService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @ApiOperation("批量修改企业信息")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<Company> batchParam) {
        if (batchParam.update(companyService, "company_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @ApiOperation("批量删除企业信息")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (companyService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
