package com.ho.user.controller;


import com.ho.common.tools.annotation.LogAnnotation;
import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.constant.ContextConstant;
import com.ho.common.tools.entity.PageVO;
import com.ho.common.tools.entity.SimpleUser;
import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import com.ho.common.tools.exception.DataResult;
import com.ho.common.tools.service.RedisService;
import com.ho.user.api.entity.SysDept;
import com.ho.user.api.entity.SysUser;
import com.ho.user.api.vo.req.DeptManagerReq;
import com.ho.user.feignclient.FlowFeignClient;
import com.ho.user.service.DeptService;
import com.ho.user.service.PermissionService;
import com.ho.user.vo.req.DeptAddReqVO;
import com.ho.user.vo.req.DeptQuery;
import com.ho.user.vo.req.DeptUpdateReqVO;
import com.ho.user.vo.req.UserPageUserByDeptReqVO;
import com.ho.user.vo.resp.DeptRespNodeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 机构部门实现类
 */
@RequestMapping(ContextConstant.SYS + "dept")
@RestController
@Api(tags = "系统模块-机构管理")
@Slf4j
public class DeptController {


    @Autowired
    private DeptService deptService;

    @Autowired
    PermissionService permissionService;

    @Autowired
    private RedisService redisService;

    @Value("${phone.regexp}")
    String regex;

    @PostMapping("users")
    @ApiOperation(value = "分页获取组织下所有用户接口")
    //@LogAnnotation(title = "机构管理",action = "分页获取组织下所有用户")
    //@RequiresPermissions("sys:dept:user:list")
    public DataResult<PageVO<SysUser>> pageDeptUserInfos(@RequestBody @Valid UserPageUserByDeptReqVO vo) {
        //因为查询部门下人员存在越权情况,即子部门的人员无法查询上级公司人员,所以要做个控制

        return DataResult.success(deptService.pageDeptUserInfo(vo));
    }

    @GetMapping("{id}")
    @ApiOperation(value = "查询组织详情接口")
    // @LogAnnotation(title = "机构管理",action = "查询组织详情")
    //@RequiresPermissions("sys:dept:detail")
    public DataResult<SysDept> detailInfo(@PathVariable("id") Integer id) {
        DataResult<SysDept> result = DataResult.success();
        result.setData(deptService.detailInfo(id));
        return result;
    }

/*    @PostMapping("deptpage")
    @ApiOperation(value = "分页获取组织信息接口")
    //@LogAnnotation(title = "机构管理",action = "分页获取组织信息")
    //@RequiresPermissions("sys:dept:list")
    public DataResult<PageVO<SysDept>> pageInfo(@RequestBody DeptPageReqVO vo) {
        DataResult<PageVO<SysDept>> result = DataResult.success();
        result.setData(deptService.pageInfo(vo));
        return result;
    }*/

    @PostMapping("tree")
    @ApiOperation(value = "树型组织列表接口")
    //@RequiresPermissions(value = {"sys:user:update","sys:user:add","sys:dept:add","sys:dept:update"},logical = Logical.OR)
    public DataResult<List<DeptRespNodeVO>> getTree(@RequestBody(required = false) @Valid DeptQuery query) {
        DataResult<List<DeptRespNodeVO>> result = DataResult.success();
        result.setData(deptService.deptTreeList(query, null));
        return result;
    }

    @PostMapping("tree/enabled")
    @ApiOperation(value = "获取所有启用的部门接口")
    public DataResult<List<DeptRespNodeVO>> getSelectAllByStatus(@RequestBody(required = false) @Valid DeptQuery query) {
        DataResult<List<DeptRespNodeVO>> result = DataResult.success();
        result.setData(deptService.deptTreeList(query, "enableStatus"));
        return result;
    }

    @GetMapping("list")
    @ApiOperation(value = "组织机构列表(根据id)")
    //@RequiresPermissions(value = {"sys:user:update","sys:user:add","sys:dept:add","sys:dept:update"},logical = Logical.OR)
    public DataResult<List<SysDept>> getSubDepts(@RequestParam Integer deptId) {
        DataResult<List<SysDept>> result = DataResult.success();
        result.setData(deptService.depListByDeptId(deptId));
        return result;
    }

/*    @GetMapping("get")
    @ApiOperation(value = "获取机构列表接口")
    //@LogAnnotation(title = "机构管理",action = "获取所有组织机构")
    //@RequiresPermissions("sys:dept:list")
    public DataResult<List<SysDept>> getDeptAll() {
        DataResult<List<SysDept>> result = DataResult.success();
        result.setData(deptService.selectAll());
        return result;
    }*/

    @PostMapping("add")
    @ApiOperation(value = "新增组织接口")
    @LogAnnotation(title = "机构管理", action = "新增组织")
    @RequiresPermissions("sys:dept:add")
    public DataResult<SysDept> addDept(@RequestBody @Valid DeptAddReqVO vo, HttpServletRequest request) {
        if (StringUtils.hasLength(vo.getPhone()) && StringUtils.isEmpty(vo.getPhone())) {
            String phone = vo.getPhone();
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(phone);
            if (!matcher.matches()) {
                throw new BusinessException(BaseResponseCode.INCORRECT_MOBILE_NUMBER_FORMAT);
            }
        }
        String token = request.getHeader(CommonConstant.ACCESS_TOKEN);
        SimpleUser simpleUser = redisService.getSimpleUserByToken(token);
        if (CommonConstant.TOP_PARENT_ID.equals(vo.getPid())) {
            if (!simpleUser.getPlatSuper()) {
                log.error("非平台管理员无法创建顶级部门", vo.getPid());
                throw new BusinessException(BaseResponseCode.NON_PLATFORM_ADMINISTRATOR);
            }
        }
        DataResult<SysDept> result = DataResult.success();
        result.setData(deptService.addDept(vo));
        return result;
    }

    @PutMapping("update")
    @ApiOperation(value = "更新组织信息接口")
    @LogAnnotation(title = "机构管理", action = "更新组织信息")
    @RequiresPermissions("sys:dept:update")
    public DataResult updateDept(@RequestBody @Valid DeptUpdateReqVO vo) {
        if (StringUtils.hasLength(vo.getPhone()) && StringUtils.isEmpty(vo.getPhone())) {
            String phone = vo.getPhone();
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(phone);
            if (!matcher.matches()) {
                throw new BusinessException(BaseResponseCode.INCORRECT_MOBILE_NUMBER_FORMAT);
            }
        }
        //如果顶级部门是自己,提示
        if (vo.getId().equals(vo.getPid())) {
            throw new BusinessException(BaseResponseCode.PARENT_DEPT_CANNOT_SELF);
        }
        deptService.updateDept(vo);
        return DataResult.success();
    }

    @DeleteMapping("{id}")
    @ApiOperation(value = "删除组织接口")
    @LogAnnotation(title = "机构管理", action = "删除组织")
    @RequiresPermissions("sys:dept:deleted")
    public DataResult deleted(@PathVariable("id") Integer id) {
        deptService.deleted(id);
        return DataResult.success();
    }

    @PostMapping("/detail/getDeptUser")
    @ApiOperation(value = "根据deptId查询部门下的人员")
    public DataResult<List<SysUser>> getDeptUser(@RequestBody DeptManagerReq deptManagerReq) {
        DataResult<List<SysUser>> result = DataResult.success();
        result.setData(deptService.getDeptUser(deptManagerReq));
        return result;
    }

    @PostMapping("getUserInfosPage")
    @ApiOperation(value = "分页获取组织下所有用户接口(短信接口使用)")
    public DataResult<PageVO<SysUser>> getUserInfosPage(@RequestBody UserPageUserByDeptReqVO vo) {
        //因为查询部门下人员存在越权情况,即子部门的人员无法查询上级公司人员,所以要做个控制
        return DataResult.success(deptService.getUserInfosPage(vo));
    }
}
