/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the yifu4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.yifu.cloud.plus.v1.yifu.archives.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yifu.cloud.plus.v1.yifu.admin.api.dto.UserInfo;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysDataAuth;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeInfo;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmployeeInfoService;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.SecurityConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprUpmsProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.HttpDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.log.annotation.SysLog;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;


/**
 * 人员档案表
 *
 * @author hgw
 * @date 2022-06-20 09:55:06
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/temployeeinfo")
@Tag(name = "人员档案表管理")
public class TEmployeeInfoController {

	private final TEmployeeInfoService tEmployeeInfoService;

	// 缓存信息
	private final CacheManager cacheManager;

	private final DaprUpmsProperties daprUpmsProperties;

	/**
	 * 分页查询
	 *
	 * @param page          分页对象
	 * @param tEmployeeInfo 人员档案表
	 * @return
	 */
	@Operation(summary = "分页查询", description = "分页查询")
	@GetMapping("/page")
	//@PreAuthorize("@pms.hasPermission('demo_temployeeinfo_get')")
	@SneakyThrows
	public R<IPage<TEmployeeInfo>> getTEmployeeInfoPage(Page<TEmployeeInfo> page, TEmployeeInfo tEmployeeInfo) {
		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed("请登录！");
		}
		// 普通用户：
		if (CommonConstants.ZERO_STRING.equals(user.getSystemFlag())) {

			// 菜单id
			String menuId = "1536922631616278529";
			String linkId = user.getId();
			int linkType = 1; // 用户
			SysDataAuth sysDataAuth = new SysDataAuth();
			sysDataAuth.setLinkId(linkId);
			sysDataAuth.setLinkType(linkType);
			// 获取缓存菜单权限的步骤：
			Cache cache = cacheManager.getCache(CacheConstants.DATA_AUTH_DETAILS + linkType);
			Object obj = null;
			if (cache != null) {
				obj = cache.get(linkId + CommonConstants.DOWN_LINE_STRING + menuId);
				if (Common.isEmpty(obj)) {
					HttpDaprUtil.invokeMethodPost(daprUpmsProperties.getAppUrl(), daprUpmsProperties.getAppId()
							, "/dataAuth/refreshAuth", sysDataAuth, TEmployeeInfo.class, SecurityConstants.FROM_IN);
					obj = cache.get(linkId + CommonConstants.DOWN_LINE_STRING + menuId);
					if (Common.isEmpty(obj)) {
						linkId = user.getUserGroup();
						linkType = 0; // 用户组
						cache = cacheManager.getCache(CacheConstants.DATA_AUTH_DETAILS + linkType);
						if (cache != null) {
							obj = cache.get(linkId + CommonConstants.DOWN_LINE_STRING + menuId);
							if (Common.isEmpty(obj)) {
								sysDataAuth.setLinkId(linkId);
								sysDataAuth.setLinkType(linkType);
								HttpDaprUtil.invokeMethodPost(daprUpmsProperties.getAppUrl(), daprUpmsProperties.getAppId()
										, "/dataAuth/refreshAuth", sysDataAuth, TEmployeeInfo.class, SecurityConstants.FROM_IN);
								obj = cache.get(linkId + CommonConstants.DOWN_LINE_STRING + menuId);
							}
						}
					}
				}
			}
			if (!Common.isEmpty(obj)) {
				SimpleValueWrapper objs = (SimpleValueWrapper) obj;
				String sql = String.valueOf(objs.get());
				if (sql.contains("#deptId")) {
					// TODO - 需要关联部门表
				}
				if (sql.contains("#create_by")) {
					sql = sql.replace("#create_by", user.getId());
				}
				if (sql.contains("#settleDomainId")) {
					// TODO - 获取人员结算主体权限
					// sql = sql.replace("#settleDomainId", ",'1','2' ")
					sql = sql.replace("or a.settle_domain_id in ('0'#settleDomainId) ", "");
				}
				if (sql.contains("#deptId")) {
					// TODO - 获取人员部门权限
					// sql = sql.replace("#settleDomainId", ",'1','2' ")
					sql = sql.replace(" or dept.dept_id = #deptId ", "");
				}
				return R.ok(tEmployeeInfoService.getPage(page, tEmployeeInfo, sql));
			}
		}
		return R.ok(tEmployeeInfoService.getPage(page, tEmployeeInfo, null));
	}


	/**
	 * 通过id查询人员档案表
	 *
	 * @param id id
	 * @return R
	 */
	@Operation(summary = "通过id查询", description = "通过id查询")
	@GetMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('demo_temployeeinfo_get')")
	public R<TEmployeeInfo> getById(@PathVariable("id") String id) {
		return R.ok(tEmployeeInfoService.getById(id));
	}

	/**
	 * 新增人员档案表
	 *
	 * @param tEmployeeInfo 人员档案表
	 * @return R
	 */
	@Operation(summary = "新增人员档案表", description = "新增人员档案表")
	@SysLog("新增人员档案表")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('demo_temployeeinfo_add')")
	public R<Boolean> save(@RequestBody TEmployeeInfo tEmployeeInfo) {
		return R.ok(tEmployeeInfoService.save(tEmployeeInfo));
	}

	/**
	 * 修改人员档案表
	 *
	 * @param tEmployeeInfo 人员档案表
	 * @return R
	 */
	@Operation(summary = "修改人员档案表", description = "修改人员档案表")
	@SysLog("修改人员档案表")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('demo_temployeeinfo_edit')")
	public R<Boolean> updateById(@RequestBody TEmployeeInfo tEmployeeInfo) {
		return R.ok(tEmployeeInfoService.updateById(tEmployeeInfo));
	}

	/**
	 * 通过id删除人员档案表
	 *
	 * @param id id
	 * @return R
	 */
	@Operation(summary = "通过id删除人员档案表", description = "通过id删除人员档案表")
	@SysLog("通过id删除人员档案表")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('demo_temployeeinfo_del')")
	public R<Boolean> removeById(@PathVariable String id) {
		return R.ok(tEmployeeInfoService.removeById(id));
	}

}
