package com.unis.crk.basic.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.unis.crk.basic.entity.*;
import com.unis.crk.basic.entity.vo.QueryOrgInfoVo;
import com.unis.crk.basic.service.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.unis.crk.utils.ResultUtil;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 组织机构信息表 前端控制器
 * </p>
 *
 * @author ghh
 * @since 2021-09-29
 */
@Api(value = "组织机构信息表",tags = {"组织机构信息表"})
@RestController
@RequestMapping("orgInfo")
@CrossOrigin
public class OrgInfoController {

    private final static Logger LOGGER = LoggerFactory.getLogger(OrgInfoController.class);
    @Autowired
    private IRoleInfoService roleInfoService;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IOrgInfoService orgInfoService;
    @Autowired
    private IFuncInfoService funcInfoService;
    @Autowired
    private IRoleFuncService roleFuncService;
    @Autowired
    private IButtonInfoService buttonInfoService;
    @Autowired
    private IRoleButtonService roleButtonService;
    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IBasicEnumService basicEnumService;
    /**
     * 查找组织信息

     * @return
     */
    @RequestMapping(value="/getOrg", method = RequestMethod.POST)
    @ApiOperation(value="查询组织机构信息", notes = "查询组织机构信息列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query"),
            @ApiImplicitParam(name = "orgName", value = "组织机构名", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "上级组织机构编号", paramType = "query")
    })
    public IPage<OrgInfo> getOrgInfo(@RequestBody QueryOrgInfoVo queryOrgInfoVo) {
        ResultUtil<IPage<OrgInfo>> data = new ResultUtil<>();
        QueryWrapper<OrgInfo> orgInfoQueryWrapper = new QueryWrapper<>();
//        if (queryOrgInfoVo.getParentId() != null) {
        if (StrUtil.isNotBlank(queryOrgInfoVo.getParentId())) {
            orgInfoQueryWrapper.eq("parent_id",queryOrgInfoVo.getParentId());
        }
        if (StrUtil.isNotBlank(queryOrgInfoVo.getOrgName())) {
            orgInfoQueryWrapper.like("org_name",ResultUtil.getQueryWrapperformat(queryOrgInfoVo.getOrgName()));
        }
        Page<OrgInfo> objectPage = new Page<>(queryOrgInfoVo.getPageNum(), queryOrgInfoVo.getPageSize());

        IPage<OrgInfo> page = orgInfoService.page(objectPage, orgInfoQueryWrapper);
        return page;
    }
    /**
     * 获取组织树
     * @return
     */
    @RequestMapping(value="/getTree", method=RequestMethod.POST)
    @ApiOperation(value="获取组织树", notes = "获取组织树")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgName", value = "单位名称", paramType = "query")
    })
    public List<OrgInfo> getTree(@RequestBody QueryOrgInfoVo queryOrgInfoVo) {
        //根节点
        List<OrgInfo> rootMenu = new ArrayList<>();
        List<OrgInfo> list = orgInfoService.getallOrgInfo();
        for(Iterator<OrgInfo> it = list.iterator(); it.hasNext();){
            OrgInfo nav = it.next();
            QueryWrapper<BasicEnum> basicEnumQueryWrapper = new QueryWrapper<>();
            basicEnumQueryWrapper.select("enumName");
            basicEnumQueryWrapper.eq("enumId",nav.getOrgClassId());
            BasicEnum one = basicEnumService.getOne(basicEnumQueryWrapper);
            if(one!=null){
                nav.setOrgClassIdName(one.getEnumName());
            }
            if(nav !=null&& nav.getParentId()!=null){
                //父节点是0的，为根节点。
                if (StrUtil.isBlank(nav.getParentId()) || StrUtil.equals(nav.getParentId(),"0")) {
                    rootMenu.add(nav);
                }
            }else{
                it.remove();
            }
        }

        /* 根据Menu类的order排序 */
        Collections.sort(rootMenu, order());
        for (OrgInfo nav : rootMenu) {
            /* 获取根节点下的所有子节点 使用getChild方法*/
            List<OrgInfo> childList = getChild(nav.getOrgId(), list);
            nav.setChildren(childList);//给根节点设置子节点
        }
        return rootMenu;
    }
    /**
     * 查询全部数据
     * @return
     */
    @ApiOperation(value="查询全部父单位", notes="查询全部父单位")
    @GetMapping("getAllParen")
    public ResultUtil getAllParen(){
        ResultUtil<List<OrgInfo>> data = new ResultUtil<>();
        QueryWrapper<OrgInfo> orgInfoQueryWrapper = new QueryWrapper<>();
        QueryWrapper<OrgInfo> parent_id = orgInfoQueryWrapper.eq("parent_id", "0");
        List<OrgInfo> list = orgInfoService.list(parent_id);


        for(Iterator<OrgInfo> it = list.iterator(); it.hasNext();){
            OrgInfo next = it.next();
            int i=orgInfoService.getCountChildren(next.getOrgId().toString());
            if(i>0){
                next.setSubset(true);

            }else{
                next.setSubset(false);
            }
        }
        data.success(list);
        return data;
    }
    @ApiOperation(value="根据id获取这个单位下所有子节点", notes="根据id获取这个单位下所有子节点")
    @GetMapping ("getChildren/{orgId}&&{isQueryFristNode}")
    public ResultUtil getChildren(@PathVariable("orgId") String  orgId) {
        ResultUtil<List<OrgInfo>> data = new ResultUtil<>();
        QueryWrapper<OrgInfo> orgInfoQueryWrapper = new QueryWrapper<>();
        QueryWrapper<OrgInfo> parent_id = orgInfoQueryWrapper.eq("parent_id", orgId);
        List<OrgInfo> list = orgInfoService.list(parent_id);

        //添加判断是否有子集
        for(Iterator<OrgInfo> it = list.iterator(); it.hasNext();){
            OrgInfo next = it.next();
            QueryWrapper<BasicEnum> basicEnumQueryWrapper = new QueryWrapper<>();
            basicEnumQueryWrapper.select("enumName");
            basicEnumQueryWrapper.eq("enumId",next.getOrgClassId());
            BasicEnum one = basicEnumService.getOne(basicEnumQueryWrapper);
            if(one!=null){
                next.setOrgClassIdName(one.getEnumName());
            }
            int i=orgInfoService.getCountChildren(next.getOrgId().toString());
            if(i>0){
                next.setSubset(true);

            }else{
                next.setSubset(false);
            }
        }

        return data.success(list);
    }

    /**
     * 根据ID查询数据
     * @return
     */
    @RequestMapping(value="/getOne", method=RequestMethod.POST)
    @ApiOperation(value="根据ID查询数据", notes="根据ID查询数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ID", value = "单位ID", paramType = "query")
    })

    public ResultUtil getOne(@RequestBody QueryOrgInfoVo queryOrgInfoVo){
        LOGGER.info("入参为:{}",queryOrgInfoVo.getId());
        ResultUtil<OrgInfo> data = new ResultUtil<>();
        if (StringUtils.isEmpty(queryOrgInfoVo.getId())){
            data.failed("传入的主键为空");
            return data;
        }
        data.success(this.orgInfoService.getById(queryOrgInfoVo.getId()));
        return data;
    }



    //所属组织
    @ApiOperation(value="查询", notes="查询登录用户单位信息")
    @RequestMapping(value="/getTreeListByOrgId", method = RequestMethod.POST)
    public Map<String, Object> getTreeListByOrgId(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<>();
        try {
            ObjectMapper mapper = new ObjectMapper();
            String orgInfoObject =  org.apache.commons.lang.ObjectUtils.toString(request.getSession().getAttribute("orgInfo"),"");
            OrgInfo depotInfo = mapper.readValue(orgInfoObject, OrgInfo.class);
            String orgId = depotInfo.getOrgId().toString();

            if (org.apache.commons.lang.StringUtils.isBlank(orgId)) {
                return modelMap;
            }
            //List<OrgInfo> list = orgInfoService.getTreeListByOrgId(orgId);
            List<OrgInfo> list = orgInfoService.getAllChildren(orgId,null);
            List<OrgInfo> voList = new ArrayList<OrgInfo>();
            for (OrgInfo orgInfo : list) {
                OrgInfo orgInfoVO = new OrgInfo();
                orgInfoVO.setParentId(orgInfo.getParentId());
               /* orgInfoVO.setId(orgInfo.getOrgId());
                orgInfoVO.setName(orgInfo.getOrgName());*/
                voList.add(orgInfoVO);
            }
            modelMap.put("orgList", voList);
            modelMap.put("orgId", orgId);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return modelMap;
    }


    /**
     * 查询全部数据
     * @return
     */
    @ApiOperation(value="查询", notes="查询全部数据")
    @GetMapping("getAll")
    public ResultUtil getAll(){
        ResultUtil<List<OrgInfo>> data = new ResultUtil<>();
        data.success(this.orgInfoService.list());
        return data;
    }


    /**
     * 保存组织机构信息
     * @param
     * @return
     */
    @ApiOperation(value="保存组织信息", notes="保存组织信息")
    @PostMapping("save")
    public ResultUtil<Map<String, Object>> save(@RequestBody OrgInfo orgInfo){
        ResultUtil<Map<String, Object>> mapResultUtil = new ResultUtil<>();
        Map<String, Object> modelMap = new HashMap<>();
        // JSON字符串转对象
        ObjectMapper mapper = new ObjectMapper();
//        if (orgInfo.getOrgId() == null) {
        if (!StrUtil.isNotBlank(orgInfo.getOrgId().toString())) {
            /* 保存单位数据 */
            orgInfoService.save(orgInfo);
            /* 更新库区标准代码 */
            String zzdm = orgInfo.getCreditCode();
            if (StrUtil.isBlank(zzdm)) {
                zzdm = orgInfo.getCompanyOrgCode();
            }
            //orgInfo.setKqbm(BusinessUtils.setBZkqbm(zzdm, orgInfo.getOrgId()));
            orgInfoService.updateById(orgInfo);
            /*新增机构时，重新配置级别*/
            UpdateWrapper<OrgInfo> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("level_code", "");
            //orgInfoService.update(updateWrapper);//清空所有级别

            QueryWrapper<OrgInfo> objectQueryWrapper = new QueryWrapper<>();
            objectQueryWrapper.eq("parent_id","0");
            List<OrgInfo> list = orgInfoService.list(objectQueryWrapper);//查询最顶级机构
            OrgInfo orgInfo1 = list.get(0);
            orgInfo1.setParentId(orgInfo1.getOrgId().toString());
           // orgInfoService.updateOrgLevel(list.get(0));
            /*新增机构时，重新配置级别*/
            //默认给新建的机构创建一个系统管理员角色
            RoleInfo roleInfo = new RoleInfo();
            roleInfo.setOrgId(orgInfo.getOrgId().toString());
            roleInfo.setParentId("0");
            roleInfo.setRoleName("系统管理员");
            roleInfoService.save(roleInfo);
            List<FuncInfo> funcList = funcInfoService.list();
            roleFuncService.saveForList(roleInfo.getRoleId(), funcList);

            List<ButtonInfo> buttonList = buttonInfoService.list();
            roleButtonService.saveForList(roleInfo.getRoleId(), buttonList);
            //新增单位管理人员
            UserInfo userInfo = new UserInfo();
            userInfo.setOrgId(orgInfo.getOrgId().toString());
            userInfo.setPassword(SecureUtil.md5("123456"));
            //userInfo.setUsername("admin"+orgInfo.getOrgId());
            userInfo.setUsername("admin"+orgInfo.getOrgCode());
            userInfo.setRealName("管理员");
            userInfoService.save(userInfo);
            //给人员绑定角色
            UserRole userRole = new UserRole();
            userRole.setUserId(userInfo.getUserId());
            userRole.setRoleId(roleInfo.getRoleId());
            userRoleService.save(userRole);
        } else {
            orgInfoService.updateById(orgInfo);
        }
        modelMap.put("status", "success");
        modelMap.put("newOrgId", orgInfo.getOrgId());

        return mapResultUtil.success(modelMap);
    }


    /**
     * 修改一条数据
     * @param param
     * @return
     */
    @ApiOperation(value="修改", notes="修改一条数据")
    @PatchMapping("edit")
    public ResultUtil edit(@RequestBody OrgInfo param){
        LOGGER.info("入参为:{}", param);
        ResultUtil<Boolean> data = new ResultUtil<>();
        if (ObjectUtils.isEmpty(param)){
            data.failed("所接收对象为null");
            return data;
        }
        data.success(this.orgInfoService.updateById(param));
        return data;
    }


    /**
     * 根据ID删除数据
     * @param id
     * @return
     */
    @ApiOperation(value="删除", notes="根据ID删除数据")
    @DeleteMapping("delete/{id}")
    public ResultUtil delete(@PathVariable("id") String id){
        LOGGER.info("入参为:{}", id);
        ResultUtil<Boolean> data = new ResultUtil<>();
        if (StringUtils.isEmpty(id)){
            data.failed("所接收id为null");
            return data;
        }
        data.success(this.orgInfoService.removeById(id));
        return data;
    }

    /*
     * 排序,根据order排序
     */
    public Comparator<OrgInfo> order() {
        Comparator<OrgInfo> comparator = new Comparator<OrgInfo>() {
            @Override
            public int compare(OrgInfo o1, OrgInfo o2) {
                if(  !StrUtil.hasBlank(o1.getLevelCode())  && !StrUtil.hasBlank(o2.getLevelCode())){
                    if (o1.getLevelCode() != o2.getLevelCode()) {
                        return Integer.parseInt(o1.getLevelCode()) - Integer.parseInt(o2.getLevelCode());
                    }
                }
                return 0;
            }
        };
        return comparator;
    }


    /**
     * 获取子节点
     *
     * @param id      父节点id
     * @param allMenu 所有菜单列表
     * @return 每个根节点下，所有子菜单列表
     */
    public List<OrgInfo> getChild(String id, List<OrgInfo> allMenu) {
        //子菜单
        List<OrgInfo> childList = new ArrayList<OrgInfo>();
        for (OrgInfo nav : allMenu) {
            // 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
            //相等说明：为该根节点的子节点。
            if (nav.getParentId().equals(id)) {
                childList.add(nav);
            }
        }
        //递归
        for (OrgInfo nav : childList) {
            nav.setChildren(getChild(nav.getOrgId().toString(), allMenu));
        }
        Collections.sort(childList, order());//排序
        //如果节点下没有子节点，返回一个空List（递归退出）
        if (childList.size() == 0) {
            return new ArrayList<OrgInfo>();
        }
        return childList;
    }


}

