package com.yd.csf.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yd.common.enums.ResultCode;
import com.yd.common.result.Result;
import com.yd.csf.service.dto.*;

import com.yd.csf.service.model.CommissionExpected;
import com.yd.csf.service.model.Policy;
import com.yd.csf.service.service.*;
import com.yd.csf.service.vo.CommissionExpectedVO;
import com.yd.csf.service.vo.PolicyVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * policy接口
 *
 * @author jianan
 * @since 2025-09-20
 */
@RestController
@RequestMapping("/policy")
@Tag(name = "保单(产品计划)接口")
public class ApiPolicyController {

    @Resource
    private PolicyService policyService;
    @Resource
    private CommissionExpectedService commissionExpectedService;
    @Resource
    private PolicyPolicyholderService policyPolicyholderService;
    @Resource
    private PolicyInsurantService policyInsurantService;
    @Resource
    private PolicySecondHolderService policySecondHolderService;

    /**
     * 创建保单
     *
     * @param customerAddRequest
     * @param request
     * @return
     */
//    @Operation(summary = "创建保单")
//    @PostMapping("/add")
//    @Transactional(rollbackFor = Exception.class)
//    public Result<Map<String, Object>> addCustomer(@RequestBody CustomerAddRequest customerAddRequest, HttpServletRequest request) {
//        if (customerAddRequest == null) {
//            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMessage());
//        }
//        return Result.success(PolicyService.addCustomer(customerAddRequest));
//    }

    /**
     * 删除fna
     *
     * @param deleteRequest
     * @param request
     * @return
     */
//    @PostMapping("/delete")
//    public Result<Boolean> deleteFna(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
//        if (deleteRequest == null || deleteRequest.getId() <= 0) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        User user = userService.getLoginUser(request);
//        long id = deleteRequest.getId();
//        // 判断是否存在
//        Customer oldFna = PolicyService.getById(id);
//        ThrowUtils.throwIf(oldFna == null, ErrorCode.NOT_FOUND_ERROR);
//        // 仅本人或管理员可删除
//        if (!oldFna.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
//            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
//        }
//        // 操作数据库
//        boolean result = PolicyService.removeById(id);
//        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
//        return Result.success(true);
//    }

    /**
     * 更新保单（产品计划）
     *
     * @param policyUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @Operation(summary = "更新保单信息")
    public Result<Boolean> updatePolicy(@RequestBody PolicyUpdateRequest policyUpdateRequest) {
        if (policyUpdateRequest == null || policyUpdateRequest.getPolicyBizId() == null) {
            return Result.fail(ResultCode.PARAMS_ERROR.getCode(), ResultCode.PARAMS_ERROR.getMessage());
        }
        return Result.success(policyService.updatePolicy(policyUpdateRequest));
    }

    /**
     * 更新投保人信息
     *
     * @param policyPolicyholderUpdateRequest
     * @return
     */
    @PostMapping("/update_policyholder")
    @Operation(summary = "更新保单投保人信息")
    public Result<Boolean> updatePolicyholder(@RequestBody PolicyPolicyholderUpdateRequest policyPolicyholderUpdateRequest) {
        if (policyPolicyholderUpdateRequest == null || policyPolicyholderUpdateRequest.getPolicyPolicyholderBizId() == null) {
            return Result.fail(ResultCode.PARAMS_ERROR.getCode(), ResultCode.PARAMS_ERROR.getMessage());
        }
        return Result.success(policyPolicyholderService.update(policyPolicyholderUpdateRequest));
    }

    /**
     * 更新受保人信息
     *
     * @param policyInsurantUpdateRequest
     * @return
     */
    @PostMapping("/update_policy_insurant")
    @Operation(summary = "更新保单受保人信息")
    public Result<Boolean> updatePolicyInsurant(@RequestBody PolicyInsurantUpdateRequest policyInsurantUpdateRequest) {
        if (policyInsurantUpdateRequest == null || policyInsurantUpdateRequest.getPolicyInsurantBizId() == null) {
            return Result.fail(ResultCode.PARAMS_ERROR.getCode(), "policyInsurantBizId不能为空");
        }
        return Result.success(policyInsurantService.update(policyInsurantUpdateRequest));
    }

     /**
     * 更新第二持有人信息
     *
     * @param policySecondHolderUpdateRequest
     * @return
     */
    @PostMapping("/update_policy_second_holder")
    @Operation(summary = "更新第二持有人信息")
    public Result<Boolean> updatePolicySecondHolder(@RequestBody PolicySecondHolderUpdateRequest policySecondHolderUpdateRequest) {
        if (policySecondHolderUpdateRequest == null || policySecondHolderUpdateRequest.getPolicySecondHolderBizId() == null) {
            return Result.fail(ResultCode.PARAMS_ERROR.getCode(), "policySecondHolderBizId不能为空");
        }
        return Result.success(policySecondHolderService.updatePolicySecondHolder(policySecondHolderUpdateRequest));
    }

    /**
     * 根据 policyBizId 获取保单（封装类）
     *
     * @param policyBizId
     * @return
     */
//    @GetMapping("/get/vo")
//    @Operation(summary = "根据 policyBizId 获取保单详情")
//    public Result<PolicyVO> getPolicyByPolicyBizId(@RequestParam("policyBizId") String policyBizId, HttpServletRequest request) {
//        if (policyBizId == null) {
//            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMessage());
//        }
//        // 查询数据库
//        Policy Policy = PolicyService.getByPolicyBizId(policyBizId);
//        if (Policy == null) {
//            return Result.fail(ErrorCode.NOT_FOUND_ERROR.getCode(), ErrorCode.NOT_FOUND_ERROR.getMessage());
//        }
//
//        // 获取封装类
//        return Result.success(PolicyService.getPolicyVO(Policy));
//    }
    
    /**
     * 分页获取保单列表（VO）
     *
     * @param PolicyQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    @Operation(summary = "分页获取保单列表")
    public Result<Page<PolicyVO>> listPolicyByPage(@RequestBody PolicyQueryRequest PolicyQueryRequest,
                                                               HttpServletRequest request) {
        long current = PolicyQueryRequest.getPageNo();
        long size = PolicyQueryRequest.getPageSize();

        // 查询数据库
        Page<Policy> policyPage = policyService.page(new Page<>(current, size),
                policyService.getQueryWrapper(PolicyQueryRequest));
        // 获取封装类
        return Result.success(policyService.getPolicyVOPage(policyPage));
    }

    /**
     * 分页获取预计来佣列表（VO）
     *
     * @param commissionExpectedQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/commission_expected")
    @Operation(summary = "分页获取预计来佣列表")
    public Result<Page<CommissionExpectedVO>> listCommissionExpectedByPage(@RequestBody CommissionExpectedQueryRequest commissionExpectedQueryRequest,
                                                                           HttpServletRequest request) {
        long current = commissionExpectedQueryRequest.getPageNo();
        long size = commissionExpectedQueryRequest.getPageSize();
        // 查询数据库
        QueryWrapper<CommissionExpected> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("policy_no", commissionExpectedQueryRequest.getPolicyNo());
        queryWrapper.orderByAsc("commission_period");

        Page<CommissionExpected> commissionExpectedPage = commissionExpectedService.page(new Page<>(current, size),
                queryWrapper);
        // 获取封装类
        return Result.success(commissionExpectedService.getCommissionExpectedVOPage(commissionExpectedPage));
    }

    /**
     * 获取保单产品信息
     *
     * @param productLaunchBizId
     * @return
     */
    @GetMapping("/get_policy_product_info")
    @Operation(summary = "获取保单产品信息")
    public Result<List<PolicyProductInfo>> getPolicyProductInfo(@RequestParam("productLaunchBizId") List<String> productLaunchBizId) {
        if (productLaunchBizId == null) {
            return Result.fail(ResultCode.PARAMS_ERROR.getCode(), ResultCode.PARAMS_ERROR.getMessage());
        }
        // 查询
        List<PolicyProductInfo> productLaunchPageResponse = policyService.getPolicyProductInfo(productLaunchBizId);

        // 获取封装类
        return Result.success(productLaunchPageResponse);
    }

}
