package com.system.oauth.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.system.framework.core.constant.CacheConstant;
import com.system.framework.core.response.StarBosResult;
import com.system.framework.core.utils.AuthUtils;
import com.system.framework.core.utils.oConvertUtils;
import com.system.oauth.system.entity.SysDepart;
import com.system.oauth.system.entity.UserMessage;
import com.system.oauth.system.model.DepartIdModel;
import com.system.oauth.system.model.SysDepartTreeModel;
import com.system.oauth.system.service.ISysDepartService;
import com.system.oauth.system.service.ISysUserDepartService;
import com.system.oauth.system.service.IUserMessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 部门2 前端控制器
 *
 * @Author:
 */
@Api(tags = "部门")
@RestController
@RequestMapping("/sys/sysDepart")
@Slf4j
public class SysDepartController {

    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    public RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private IUserMessageService sysUserService;
    @Autowired
    private ISysUserDepartService sysUserDepartService;
    /**
     * 查询数据 查出我的部门,并以树结构数据格式响应给前端
     *
     * @return
     */
//	@RequestMapping(value = "/queryMyDeptTreeList", method = RequestMethod.GET)
//	public StarBosResult<List<SysDepartTreeModel>> queryMyDeptTreeList() {
//		StarBosResult<List<SysDepartTreeModel>> result = new StarBosResult<>();
//		String accountId = AuthUtils.getAccountId();
//		try {
//			if(oConvertUtils.isNotEmpty(user.getUserIdentity()) && user.getUserIdentity().equals( CommonConstant.USER_IDENTITY_2 )){
//				List<SysDepartTreeModel> list = sysDepartService.queryMyDeptTreeList(user.getDepartIds());
//				result.setData(list);
//				result.setCode(CommonConstant.USER_IDENTITY_2);
//				result.setMsg("true");
//			}else{
//				result.setCode(CommonConstant.USER_IDENTITY_1);
//				result.setMsg("true");
//			}
//		} catch (Exception e) {
//			log.error(e.getMessage(),e);
//		}
//		return result;
//	}

    /**
     * 查询数据 查出所有部门,并以树结构数据格式响应给前端
     *
     * @return
     */
    @ApiOperation(value = "部门-查询数据", httpMethod = "GET", produces = "", notes = "查出所有部门,并以树结构数据格式响应给前端")
    @RequestMapping(value = "/queryTreeList", method = RequestMethod.GET)
    public StarBosResult<List<SysDepartTreeModel>> queryTreeList() {
        StarBosResult<List<SysDepartTreeModel>> result = new StarBosResult<>();
        try {
            // 从内存中读取
//			List<SysDepartTreeModel> list =FindsDepartsChildrenUtil.getSysDepartTreeList();
//			if (CollectionUtils.isEmpty(list)) {
//				list = sysDepartService.queryTreeList();
//			}
            List<SysDepartTreeModel> list = sysDepartService.queryTreeList();
            result.setData(list);
            result.setCode(200);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 添加新数据 添加用户新建的部门对象数据,并保存到数据库
     *
     * @param sysDepart
     * @return
     */
    //
    @ApiOperation(value = "部门-添加新数据", httpMethod = "POST", produces = "", notes = "添加用户新建的部门对象数据,并保存到数据库")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public StarBosResult<SysDepart> add(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
        StarBosResult<SysDepart> result = new StarBosResult<SysDepart>();
        String username = AuthUtils.getUsername();
        try {
            sysDepart.setCreateBy(username);
            sysDepartService.saveDepartData(sysDepart, username);
            //清除部门树内存
            // FindsDepartsChildrenUtil.clearSysDepartTreeList();
            // FindsDepartsChildrenUtil.clearDepartIdModel();
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑数据 编辑部门的部分数据,并保存到数据库
     *
     * @param sysDepart
     * @return
     */
    //
    @ApiOperation(value = "部门-编辑数据", httpMethod = "PUT", produces = "", notes = "编辑部门的部分数据,并保存到数据库")
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public StarBosResult<SysDepart> edit(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
        String username = AuthUtils.getUsername();
        sysDepart.setUpdateBy(username);
        StarBosResult<SysDepart> result = new StarBosResult<SysDepart>();
        SysDepart sysDepartEntity = sysDepartService.getById(sysDepart.getId());
        if (sysDepartEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = sysDepartService.updateDepartDataById(sysDepart, username);
            // TODO 返回false说明什么？
            if (ok) {
                //清除部门树内存
                //FindsDepartsChildrenUtil.clearSysDepartTreeList();
                //FindsDepartsChildrenUtil.clearDepartIdModel();
                result.success("修改成功!");
            }
        }
        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    //
    @ApiOperation(value = "部门-通过id删除", httpMethod = "DELETE", produces = "")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public StarBosResult<SysDepart> delete(@RequestParam(name = "id", required = true) String id) {

        StarBosResult<SysDepart> result = new StarBosResult<SysDepart>();
        SysDepart sysDepart = sysDepartService.getById(id);
        if (sysDepart == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = sysDepartService.delete(id);
            if (ok) {
                //清除部门树内存
                //FindsDepartsChildrenUtil.clearSysDepartTreeList();
                // FindsDepartsChildrenUtil.clearDepartIdModel();
                result.success("删除成功!");
            }
        }
        return result;
    }


    /**
     * 批量删除 根据前端请求的多个ID,对数据库执行删除相关部门数据的操作
     *
     * @param ids
     * @return
     */
    //
    @ApiOperation(value = "部门-批量删除", httpMethod = "DELETE", produces = "", notes = "根据前端请求的多个ID,对数据库执行删除相关部门数据的操作")
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public StarBosResult<SysDepart> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {

        StarBosResult<SysDepart> result = new StarBosResult<SysDepart>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.sysDepartService.deleteBatchWithChildren(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 查询数据 添加或编辑页面对该方法发起请求,以树结构形式加载所有部门的名称,方便用户的操作
     *
     * @return
     */
    @ApiOperation(value = "部门-查询数据", httpMethod = "GET", produces = "", notes = "添加或编辑页面对该方法发起请求,以树结构形式加载所有部门的名称,方便用户的操作")
    @RequestMapping(value = "/queryIdTree", method = RequestMethod.GET)
    public StarBosResult<List<DepartIdModel>> queryIdTree() {
//		Result<List<DepartIdModel>> result = new Result<List<DepartIdModel>>();
//		List<DepartIdModel> idList;
//		try {
//			idList = FindsDepartsChildrenUtil.wrapDepartIdModel();
//			if (idList != null && idList.size() > 0) {
//				result.setResult(idList);
//				result.setSuccess(true);
//			} else {
//				sysDepartService.queryTreeList();
//				idList = FindsDepartsChildrenUtil.wrapDepartIdModel();
//				result.setResult(idList);
//				result.setSuccess(true);
//			}
//			return result;
//		} catch (Exception e) {
//			log.error(e.getMessage(),e);
//			result.setSuccess(false);
//			return result;
//		}
        StarBosResult<List<DepartIdModel>> result = new StarBosResult<>();
        try {
            List<DepartIdModel> list = sysDepartService.queryDepartIdTreeList();
            result.setData(list);
            result.setCode(200);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * <p>
     * 部门搜索功能方法,根据关键字模糊搜索相关部门
     * </p>
     *
     * @param keyWord
     * @return
     */
//	@RequestMapping(value = "/searchBy", method = RequestMethod.GET)
//	public StarBosResult<List<SysDepartTreeModel>> searchBy(@RequestParam(name = "keyWord", required = true) String keyWord, @RequestParam(name = "myDeptSearch", required = false) String myDeptSearch) {
//		StarBosResult<List<SysDepartTreeModel>> result = new StarBosResult<List<SysDepartTreeModel>>();
//		//部门查询，myDeptSearch为1时为我的部门查询，登录用户为上级时查只查负责部门下数据
//		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//		String departIds = null;
//		if(oConvertUtils.isNotEmpty(user.getUserIdentity()) && user.getUserIdentity().equals( CommonConstant.USER_IDENTITY_2 )){
//			departIds = user.getDepartIds();
//		}
//		List<SysDepartTreeModel> treeList = this.sysDepartService.searhBy(keyWord,myDeptSearch,departIds);
//		if (treeList == null || treeList.size() == 0) {
//			result.setCode(201);
//			result.setMsg("未查询匹配数据！");
//			return result;
//		}
//		result.setData(treeList);
//		return result;
//	}


    /**
     * 查询所有部门信息
     *
     * @return
     */
    @GetMapping("listAll")
    @ApiOperation(value = "部门-查询所有部门信息", httpMethod = "GET", produces = "", notes = "查询所有部门信息")
    public StarBosResult<List<SysDepart>> listAll(@RequestParam(name = "id", required = false) String id) {
        StarBosResult<List<SysDepart>> result = new StarBosResult<>();
        LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<SysDepart>();
        query.orderByAsc(SysDepart::getOrgCode);
        if (oConvertUtils.isNotEmpty(id)) {
            String arr[] = id.split(",");
            query.in(SysDepart::getId, arr);
        }
        List<SysDepart> ls = this.sysDepartService.list(query);
        result.setCode(200);
        result.setData(ls);
        return result;
    }

    /**
     * 查询数据 查出所有部门,并以树结构数据格式响应给前端
     *
     * @return
     */
    @ApiOperation(value = "部门-查询数据", httpMethod = "GET", produces = "", notes = "查出所有部门,并以树结构数据格式响应给前端")
    @RequestMapping(value = "/queryTreeByKeyWord", method = RequestMethod.GET)
    public StarBosResult<Map<String, Object>> queryTreeByKeyWord(@RequestParam(name = "keyWord", required = false) String keyWord) {
        StarBosResult<Map<String, Object>> result = new StarBosResult<>();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            List<SysDepartTreeModel> list = sysDepartService.queryTreeByKeyWord(keyWord);
            //根据keyWord获取用户信息
            LambdaQueryWrapper<UserMessage> queryUser = new LambdaQueryWrapper<UserMessage>();
//			queryUser.eq(UserMessage::getDelFlag,CommonConstant.DEL_FLAG_0);
            queryUser.and(i -> i.like(UserMessage::getName, keyWord).or().like(UserMessage::getFauthAccount, keyWord));
            List<UserMessage> sysUsers = this.sysUserService.list(queryUser);
            map.put("userList", sysUsers);
            map.put("departList", list);
            result.setData(map);
            result.setCode(200);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 根据部门编码获取部门信息
     *
     * @param orgCode
     * @return
     */
    @ApiOperation(value = "部门-根据部门编码获取部门信息", httpMethod = "GET", produces = "", notes = "根据部门编码获取部门信息")
    @GetMapping("/getDepartName")
    public StarBosResult<SysDepart> getDepartName(@RequestParam(name = "orgCode") String orgCode) {
        StarBosResult<SysDepart> result = new StarBosResult<>();
        LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<>();
        query.eq(SysDepart::getOrgCode, orgCode);
        SysDepart sysDepart = sysDepartService.getOne(query);
        result.setCode(200);
        result.setData(sysDepart);
        return result;
    }

    /**
     * 根据部门id获取用户信息
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "部门-根据部门id获取用户信息", httpMethod = "GET", produces = "", notes = "根据部门id获取用户信息")
    @GetMapping("/getUsersByDepartId")
    public StarBosResult<List<UserMessage>> getUsersByDepartId(@RequestParam(name = "id") String id) {
        StarBosResult<List<UserMessage>> result = new StarBosResult<>();
        List<UserMessage> sysUsers = sysUserDepartService.queryUserByDepId(id);
        result.setCode(200);
        result.setData(sysUsers);
        return result;
    }
}
