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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.ResultConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.redis.RedisDistributedLock;
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.util.MenuUtil;
import com.yifu.cloud.plus.v1.yifu.common.log.annotation.SysLog;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TAuditRecord;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TInsuranceUnpurchaseApply;
import com.yifu.cloud.plus.v1.yifu.salary.service.TInsuranceUnpurchaseApplyService;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TInsuranceUnpurchaseApplySearchVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;


/**
 * 含风险项目不购买申请表
 *
 * @author huych
 * @date 2025-01-10 11:24:38
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/tinsuranceunpurchaseapply")
@Tag(name = "含风险项目不购买申请表管理")
@Slf4j
public class TInsuranceUnpurchaseApplyController {

	private final TInsuranceUnpurchaseApplyService tInsuranceUnpurchaseApplyService;

	private final MenuUtil menuUtil;

	/**
	 * 简单分页查询
	 *
	 * @param page  分页对象
	 * @param searchVo 含风险项目不购买申请表
	 * @return
	 */
	@Operation(description = "简单分页查询")
	@GetMapping("/page")
	public R<IPage<TInsuranceUnpurchaseApply>> getTInsuranceUnpurchaseApplyPage(Page<TInsuranceUnpurchaseApply> page, TInsuranceUnpurchaseApplySearchVo searchVo) {
		YifuUser user = SecurityUtils.getUser();
		menuUtil.setAuthSql(user, searchVo);
		return new R<>(tInsuranceUnpurchaseApplyService.getTInsuranceUnpurchaseApplyPage(page, searchVo));
	}

	/**
	 * 通过id查询含风险项目不购买申请表
	 *
	 * @param id id
	 * @return R
	 */
	@Operation(summary = "移动端通过id查询", description = "移动端通过id查询")
	@GetMapping("/temp/{id}")
	public R<TInsuranceUnpurchaseApply> getTempById(@PathVariable("id") String id) {
		return tInsuranceUnpurchaseApplyService.getDetailInfoById(id);
	}

	/**
	 * 通过id查询含风险项目不购买申请表
	 *
	 * @param id id
	 * @return R
	 */
	@Operation(summary = "通过id查询", description = "通过id查询")
	@GetMapping("/{id}")
	public R<TInsuranceUnpurchaseApply> getById(@PathVariable("id") String id) {
		return tInsuranceUnpurchaseApplyService.getDetailInfoById(id);
	}

	/**
	 * 新增含风险项目不购买申请表
	 *
	 * @param tInsuranceUnpurchaseApply 含风险项目不购买申请表
	 * @return R
	 */
	@Operation(summary = "新增含风险项目不购买申请表", description = "新增含风险项目不购买申请表")
	@SysLog("新增含风险项目不购买申请表")
	@PostMapping("/add")
	public R save(@RequestBody TInsuranceUnpurchaseApply tInsuranceUnpurchaseApply) {
		return new R<>(tInsuranceUnpurchaseApplyService.addApply(tInsuranceUnpurchaseApply));
	}

	/**
	 * 通过id删除含风险项目不购买申请表
	 *
	 * @param id id
	 * @return R
	 */
	@Operation(summary = "通过id删除含风险项目不购买申请表", description = "通过id删除含风险项目不购买申请表：hasPermission('insurances_tinsuranceunpurchaseapply_del')")
	@SysLog("通过id删除含风险项目不购买申请表")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('insurances_tinsuranceunpurchaseapply_del')")
	public R removeById(@PathVariable String id) {
		return tInsuranceUnpurchaseApplyService.deleteById(id);
	}

	/**
	 * 含风险项目不购买申请表 批量导出
	 *
	 * @author huych
	 * @date 2025-01-10 11:24:38
	 **/
	@Operation(description = "导出含风险项目不购买申请表")
	@PostMapping("/export")
	public void export(HttpServletResponse response, @RequestBody TInsuranceUnpurchaseApplySearchVo searchVo) {
		YifuUser user = SecurityUtils.getUser();
		menuUtil.setAuthSql(user, searchVo);
		tInsuranceUnpurchaseApplyService.listExport(response, searchVo);
	}

	/**
	 * 审核分页查询
	 *
	 * @param page           分页对象
	 * @param unpurchaseApplySearchVo 不购买申请查询信息
	 * @param type 0待审核、1已处理、2抄送我
	 *
	 * @return R
	 */
	@Operation(description = "审核分页查询")
	@GetMapping("/getAuditPage")
	public R<IPage<TInsuranceUnpurchaseApply>> getAuditPage(Page<TInsuranceUnpurchaseApply> page,
															TInsuranceUnpurchaseApplySearchVo unpurchaseApplySearchVo,String type) {
		YifuUser user = SecurityUtils.getUser();
		if(null == user){
			return R.failed(ResultConstants.NO_USER);
		}
		String userId = String.valueOf(user.getId());
		return R.ok(tInsuranceUnpurchaseApplyService.getAuditPage(page, unpurchaseApplySearchVo, userId, type));
	}

	/**
	 * 审核数量
	 *
	 * @return R
	 */
	@Operation(description = "审核数量查询")
	@GetMapping("/getAuditCount")
	public R<Map<String,Integer>> getAuditCount() {
		YifuUser user = SecurityUtils.getUser();
		if(null == user){
			return R.failed(ResultConstants.NO_USER);
		}
		String userId = String.valueOf(user.getId());
		return R.ok(tInsuranceUnpurchaseApplyService.getAuditCount(userId));
	}

	/**
	 * 提交审核
	 * @param id  实体id
	 * @return R<String>
	 **/
	@Operation(description = "提交审核")
	@SysLog("提交审核")
	@PostMapping("/commitOne")
	public R<String> commitOne(@RequestParam String id) {
		YifuUser user = SecurityUtils.getUser();
		if (Common.isEmpty(user)){
			return R.failed(CommonConstants.USER_FAIL);
		}
		if (Common.isNotKong(id)) {
			String requestId;
			String redisKey = CacheConstants.INSURANCEUNPURCHASE_PROCESS_CACHE.concat(id);
			try {
				requestId = RedisDistributedLock.getLock(redisKey,"10");
			} catch (Exception e) {
				log.error("含风险项目不购买申请--提交审核--获取锁失败:{0}", e);
				return R.failed(ResultConstants.NO_GETLOCK_DATA_SEARCH);
			}
			if (Common.isNotKong(requestId)) {
				R<String> saveR = tInsuranceUnpurchaseApplyService.commitOne(id, user);
				//主动释放锁
				RedisDistributedLock.unlock(redisKey, requestId);
				return saveR;
			} else {
				return R.failed(ResultConstants.NO_GETLOCK_DATA_SEARCH);
			}
		} else {
			return R.failed("请选择提交的记录！");
		}
	}

	/**
	 * 审核
	 * @param tAuditRecord  审批信息
	 * @return R<String>
	 **/
	@Operation(description = "审核")
	@SysLog("审核")
	@PostMapping("/audit")
	public R<String> audit(@RequestBody TAuditRecord tAuditRecord) {
		if (Common.isEmpty(tAuditRecord.getApprovalResult())) {
			return R.failed("审核结果不能为空!");
		}
		if (Common.isNotNull(tAuditRecord.getApprovalOpinion()) && tAuditRecord.getApprovalOpinion().length()> 100) {
			return R.failed("审核意见不能超过100个字");
		}
		if (Common.isEmpty(tAuditRecord.getDomainId())) {
			return R.failed("id不能为空!");
		}
		YifuUser user = SecurityUtils.getUser();
		if (Common.isEmpty(user)){
			return R.failed(CommonConstants.USER_FAIL);
		}
		TInsuranceUnpurchaseApply insuranceUnpurchaseApply = tInsuranceUnpurchaseApplyService.getById(tAuditRecord.getDomainId());
		if (Common.isEmpty(insuranceUnpurchaseApply)){
			return R.failed("该实体信息不存在！");
		}

		String requestId;
		String redisKey = CacheConstants.INSURANCEUNPURCHASE_PROCESS_CACHE.concat(tAuditRecord.getDomainId());
		try {
			requestId = RedisDistributedLock.tryLockAndTime(redisKey, "10");
		} catch (Exception e) {
			log.error("含风险项目不购买申请--审核操作--获取锁失败:{0}", e);
			return R.failed(ResultConstants.NO_GETLOCK_DATA);
		}
		if (Common.isNotKong(requestId)) {
			return tInsuranceUnpurchaseApplyService.auditAndCommit(insuranceUnpurchaseApply, tAuditRecord.getApprovalResult(),
					tAuditRecord.getApprovalOpinion(), user);
		}
		return R.failed(ResultConstants.NO_GETLOCK_DATA);
	}

}
