package com.yifu.cloud.plus.v1.yifu.insurances.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.ErrorMessage;
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.log.annotation.SysLog;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.insurances.entity.TInsurancePolicy;
import com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.TInsurancePolicyService;
import com.yifu.cloud.plus.v1.yifu.insurances.vo.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * @author licancan
 * @description 保单维护 controller
 * @date 2022-12-07 16:56:53
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/insurancePolicy")
@Tag(name = "保单维护相关")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class TInsurancePolicyController {
	@Resource
	private TInsurancePolicyService tInsurancePolicyService;

	/**
	 * 保单号对应起止保时间分页查询
	 *
	 * @author licancan
	 * @param page 分页对象
	 * @param param 查询参数
	 * @return {@link R<IPage<TInsurancePolicy>>}
	 */
	@Operation(summary = "保单号对应起止保时间分页查询", description = "保单号对应起止保时间分页查询")
	@GetMapping("/page" )
	public R<IPage<TInsurancePolicy>> getInsurancePolicyPage(Page page, InsurancePolicyListParam param) {
		return R.ok(tInsurancePolicyService.pageDiy(page, param));
	}

	/**
	 * 保单号对应起止保时间列表（不分页）
	 *
	 * @author licancan
	 * @param param
	 * @return {@link R<List<TInsurancePolicy>>}
	 */
	@Operation(summary = "保单号对应起止保时间列表（不分页）", description = "保单号对应起止保时间（不分页）")
	@GetMapping("/list")
	@PreAuthorize("@pms.hasPermission('insurancePolicy_list')")
	public R<List<TInsurancePolicy>> getInsurancePolicyList(InsurancePolicyListParam param) {
		return R.ok(tInsurancePolicyService.getInsurancePolicyList(param));
	}

	/**
	 * 通过id查询详情
	 *
	 * @author licancan
	 * @param id
	 * @return {@link R<TInsurancePolicyDetailVO>}
	 */
	@GetMapping("/{id}")
	@Operation(summary = "通过id查询详情", description = "通过id查询详情")
	@PreAuthorize("@pms.hasPermission('insurancePolicy_getById')")
	public R<TInsurancePolicyDetailVO> getDetailById(@PathVariable("id" ) String id) {
		return tInsurancePolicyService.getDetailById(id);
	}

	/**
	 * 修改保单号对应起止保时间
	 *
	 * @author licancan
	 * @param param 修改参数
	 * @return {@link R}
	 */
	@Operation(summary = "修改保单号对应起止保时间", description = "修改保单号对应起止保时间)")
	@PostMapping("/update")
	@PreAuthorize("@pms.hasPermission('insurancePolicy_update')")
	public R update(@RequestBody @Valid InsurancePolicyListEditParam param) {
		return tInsurancePolicyService.updateInsurancePolicy(param);
	}

	/**
	 * 删除保单号对应起止保时间
	 *
	 * @author licancan
	 * @param id 主键
	 * @return {@link R}
	 */
	@Operation(summary = "删除保单号对应起止保时间", description = "删除保单号对应起止保时间")
	@DeleteMapping("/{id}" )
	@PreAuthorize("@pms.hasPermission('insurancePolicy_delete')")
	public R deleteById(@PathVariable("id") String id) {
		return tInsurancePolicyService.deleteInsurancePolicy(id);
	}


	@SneakyThrows
	@Operation(description = "批量新增保单号维护")
	@SysLog("批量新增保单号维护")
	@PostMapping("/importListAdd")
	public R<List<ErrorMessage>> importListAdd(@RequestBody MultipartFile file) {
		YifuUser user = SecurityUtils.getUser();
		if (Common.isEmpty(user)){
			return R.failed(CommonConstants.USER_FAIL);
		}
		// 获取redis分布式事务锁
		String key = CacheConstants.INSURANCE_POLICY_IMPORT + CommonConstants.DOWN_LINE_STRING + user.getId();
		String requestId;
		try {
			requestId = RedisDistributedLock.getLock(key,"10");
		} catch (Exception e) {
			throw new RuntimeException(ResultConstants.NO_GETLOCK_DATA+CommonConstants.DOWN_LINE_STRING+e.getMessage());
		}
		try {
			if (Common.isNotNull(requestId)) {
				return tInsurancePolicyService.importInsurancePolicy(file.getInputStream());
			} else {
				return R.failed(ResultConstants.NO_GETLOCK_DATA);
			}
		}finally {
			//主动释放锁
			RedisDistributedLock.unlock(key, requestId);
		}
	}

	/**
	 * 商险自动化-针对批增的查询保单号的分页接口
	 * 根据保单号去重,未过期的保单
	 * MVP1.7.15 取值从保单维护表获取
	 *
	 * @author fxj
	 * @param page 分页对象
	 * @param param 查询参数
	 * @return {@link R<IPage< InsuredListVo >>}
	 * @since 1.7.15
	 * @date 2025/9/1
	 */
	@Operation(summary = "商险自动化-针对批增的查询保单号的分页接口")
	@PostMapping("/policyPageToAutoSelect" )
	public R<IPage<PolicyListVo>> policyPageToAutoSelect(Page<PolicyListVo> page, @RequestBody InsuredParam param,
														  @RequestParam(required = false) String mId) {
		return R.ok(tInsurancePolicyService.policyPageToAutoSelect(page, param, mId));
	}
}
