package com.hys.app.controller.erp.use;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hys.app.converter.system.DeptConverter;
import com.hys.app.framework.context.user.AdminUserContext;
import com.hys.app.framework.exception.ServiceException;
import com.hys.app.framework.util.BeanUtils;
import com.hys.app.framework.util.JsonUtil;
import com.hys.app.mapper.system.AdminUserMapper;
import com.hys.app.model.base.context.Region;
import com.hys.app.model.base.context.RegionFormat;
import com.hys.app.model.support.LogClient;
import com.hys.app.model.support.validator.annotation.Log;
import com.hys.app.model.system.dos.AdminUser;
import com.hys.app.model.system.dos.DeptDO;
import com.hys.app.model.system.dto.DataPermissionDTO;
import com.hys.app.model.system.dto.DeptCreateDTO;
import com.hys.app.model.system.dto.DeptQueryParams;
import com.hys.app.model.system.dto.DeptUpdateDTO;
import com.hys.app.model.system.vo.DeptBaseVO;
import com.hys.app.model.system.vo.DeptRespVO;
import com.hys.app.model.system.vo.DeptSimpleRespVO;
import com.hys.app.model.system.vo.Menus;
import com.hys.app.service.system.AdminUserManager;
import com.hys.app.service.system.DeptManager;
import com.hys.app.service.system.RoleManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.Comparator;
import java.util.List;

@Api(tags = "管理后台 - 部门")
@RestController
@RequestMapping("/admin/systems/dept")
@Validated
public class DeptController {

    @Resource
    private DeptManager deptManager;

    @Resource
    private RoleManager roleManager;

    @Autowired
    private DeptConverter converter;

    @Autowired
    private AdminUserMapper adminUserMapper;

    @PostMapping("create")
    @ApiOperation(value = "创建部门")
    @ApiImplicitParam(name = "region", value = "地区", required = true, example = "1024")
    @Log(client = LogClient.admin, detail = "创建名称为[${reqVO.name}]的部门信息")
    public void createDept(@Valid @RequestBody DeptCreateDTO reqVO) {
        AdminUserContext.hasAdmin();
        deptManager.createDept(reqVO);
    }

    @PutMapping("update/{id}")
    @ApiOperation(value = "更新部门")
    @Log(client = LogClient.admin, detail = "修改id为[${id}]的部门信息")
    public void updateDept(@Valid @RequestBody DeptBaseVO reqVO, @PathVariable Long id) {
        AdminUserContext.hasAdmin();
        deptManager.updateDept(reqVO,id);
    }

    @DeleteMapping("delete")
    @ApiOperation(value = "删除部门")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024")
    @Log(client = LogClient.admin, detail = "删除ID为[${id}]的部门信息")
    public void deleteDept(@RequestParam("id") Long id) {
        AdminUserContext.hasAdmin();
        deptManager.deleteDept(id);
    }

    @GetMapping("/list")
    @ApiOperation(value = "获取部门列表")
    public List<DeptRespVO> getDeptList(DeptQueryParams reqVO) {
        AdminUserContext.hasSuperAdminQuery(reqVO.getCompanyId());
        List<DeptDO> list = deptManager.getDeptList(reqVO);
        list.sort(Comparator.comparing(DeptDO::getSort));
        return BeanUtils.toBean(list,DeptRespVO.class);
    }

    @GetMapping("/list-all-simple")
    @ApiOperation(value = "获取部门精简信息列表")
    public List<DeptSimpleRespVO> getSimpleDeptList(DeptQueryParams reqVO) {
        // 只查询当前用户有权限的部门
        if (Boolean.TRUE.equals(reqVO.getOnlyPermission())) {
            DataPermissionDTO dataPermissionDTO = roleManager.getDataPermission(AdminUserContext.getAdminUserId());
            if (!dataPermissionDTO.getAll()) {
                reqVO.setDeptIds(dataPermissionDTO.getDeptIds());
            }
        }

        List<DeptDO> list = deptManager.getDeptList(reqVO);
        // 排序后，返回给前端
        list.sort(Comparator.comparing(DeptDO::getSort));
        return converter.convertList02(list);
    }

    @GetMapping("/get")
    @ApiOperation(value = "获得部门信息")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024")
    public DeptRespVO getDept(@RequestParam("id") Long id) {
        return converter.convert(deptManager.getDept(id));
    }

//    @GetMapping("/getMenusByDept/{deptId}")
//    @ApiOperation(value = "获取这个部门所有的菜单")
//    public List<Menus> getMenusByDept(@PathVariable Long deptId) {
//        AdminUserContext.hasCompany();
//        if ("admin".equals(AdminUserContext.getAdminUserName()) && deptId == 0) {
//            AdminUser user = adminUserMapper.selectById(AdminUserContext.getAdminUserId());
//            return JsonUtil.jsonToList(user.getAuthIds(), Menus.class);
//        }
//        DeptDO dept = deptManager.getDept(deptId);
//        if (ObjectUtil.isNull(dept) || StrUtil.isBlank(dept.getAuthIds())) {
//            throw new ServiceException("未获取到相关信息");
//        }
//        return JsonUtil.jsonToList(dept.getAuthIds(), Menus.class);
//    }

//    @GetMapping("/getAllSubDept")
//    @ApiOperation(value = "获取所有的子部门")
//    public List<DeptDO> getAllSubDept(@PathVariable String type) {
//        if ("admin".equals(AdminUserContext.getAdminUserName())) {
//            List<DeptDO> list = deptManager.list(new LambdaQueryWrapper<DeptDO>().eq(DeptDO::getCompanyId, AdminUserContext.getCompanyId()));
//                DeptDO deptDO = new DeptDO();
//                deptDO.setName("公司管理员");
//                deptDO.setId(0L);
//                list.add(deptDO);
//            return list;
//        }
//        return deptManager.getAllSubDept(AdminUserContext.getDeptId());
//    }
}
