package com.yd.csf.api.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yd.common.constant.RedisConstants;
import com.yd.common.result.Result;
import com.yd.common.utils.RedisUtil;
import com.yd.csf.api.dto.ApiExpectedFortuneLogDto;
import com.yd.csf.api.dto.ApiExpectedFortunePageResponseVO;
import com.yd.csf.api.dto.PayableReportResponse;
import com.yd.csf.api.service.ApiExpectedFortuneLogService;
import com.yd.csf.api.service.ApiExpectedFortuneService;
import com.yd.csf.feign.client.expectedfortune.ApiExpectedFortuneFeignClient;
import com.yd.csf.feign.request.expectedfortune.*;
import com.yd.csf.feign.response.expectedfortune.ApiExpectedFortunePageResponse;
import com.yd.csf.feign.response.expectedfortune.ApiGenerateExpectedFortuneResponse;
import com.yd.csf.service.common.ErrorCode;
import com.yd.csf.service.vo.ExpectedFortuneStatisticsVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 预计发佣信息
 *
 * @author zxm
 * @since 2025-11-17
 */
@RestController
@RequestMapping("/expectedFortune")
@Tag(name = "预计发佣接口")
@Validated
public class ApiExpectedFortuneController implements ApiExpectedFortuneFeignClient {

    @Autowired
    private ApiExpectedFortuneService apiExpectedFortuneService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ApiExpectedFortuneLogService apiExpectedFortuneLogService;

    /**
     * 生成预计发佣
     * @param request
     * @return
     */
    @Override
    public Result<ApiGenerateExpectedFortuneResponse> generate(ApiGenerateExpectedFortuneRequest request) {
        try {
            Result<ApiGenerateExpectedFortuneResponse> result = apiExpectedFortuneService.generate(request);
            //保存预计发佣日志记录
            apiExpectedFortuneLogService.saveExpectedFortuneLog(ApiExpectedFortuneLogDto.builder()
                    .errorMsg(result.getMsg())
                    .policyNo(request.getPolicyNo())
                    .status(2)
                    .build());
            return result;
        }catch (Exception e) {
            //抛出异常，销毁redis缓存
            redisUtil.deleteObject(RedisConstants.EXPECTED_FORTUNE + request.getPolicyNo());
            //保存预计发佣日志记录
            apiExpectedFortuneLogService.saveExpectedFortuneLog(ApiExpectedFortuneLogDto.builder()
                    .errorMsg(e.getMessage())
                    .policyNo(request.getPolicyNo())
                    .status(1)
                    .build());
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 分页查询 - 预计发佣
     * @param request
     * @return
     */
    @Override
    @Operation(summary = "分页查询 - 预计发佣")
    public Result<IPage<ApiExpectedFortunePageResponse>> page(ApiExpectedFortunePageRequest request) {
        return apiExpectedFortuneService.page(request);
    }

    /**
     * 分页查询 - 应付款管理列表（预计发佣列表）
     * @param request
     * @return
     */
    @PostMapping("/list")
    @Operation(summary = "分页查询 - 应付款管理列表（预计发佣列表）")
    public Result<ApiExpectedFortunePageResponseVO> list(@RequestBody ApiExpectedFortunePageRequest request) {
        return apiExpectedFortuneService.list(request);
    }

    /**
     * 应付款报表
     * @param request
     * @return
     */
    @PostMapping("/payable_report")
    @Operation(summary = "应付款报表")
    public Result<PayableReportResponse> payableReport(@RequestBody ApiExpectedFortunePageRequest request) {
        return apiExpectedFortuneService.payableReport(request);
    }

    /**
     * 计算统计数据 预计发佣金额 HKD、已出账金额 HKD、待出账金额 HKD、总保单数、总保费 HKD
     */
    @PostMapping("/statistics")
    @Operation(summary = "计算统计数据 预计发佣金额 HKD、已出账金额 HKD、待出账金额 HKD、总保单数、总保费 HKD")
    public Result<ExpectedFortuneStatisticsVO> getStatistics(@RequestBody ExpectedFortuneStatisticsRequest commissionExpectedStatisticsRequest) {
        if (commissionExpectedStatisticsRequest == null) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMessage());
        }
        return Result.success(apiExpectedFortuneService.getStatistics(commissionExpectedStatisticsRequest.getExpectedFortuneIds()));
    }

    /**
     * 新增应付账款，可批量
     *
     * @param fortuneAddRequestList
     * @return
     */
    @PostMapping("/add")
    @Operation(summary = "新增应付账款，可批量")
    public Result<Boolean> add(@RequestBody List<ExpectedFortuneAddRequest> fortuneAddRequestList) {
        if (fortuneAddRequestList == null || CollectionUtils.isEmpty(fortuneAddRequestList)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), "新增应付账款列表不能为空");
        }
        return Result.success(apiExpectedFortuneService.add(fortuneAddRequestList));
    }

    /**
     * 修改出账
     *
     * @param request
     * @return
     */
    @PostMapping("/update")
    @Operation(summary = "修改出账信息")
    public Result<Boolean> update(@RequestBody ExpectedFortuneUpdateRequest request) {
        if (request == null || request.getExpectedFortuneBizId() == null) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMessage());
        }
        return Result.success(apiExpectedFortuneService.update(request));
    }

    /**
     * 应付款导出
     *
     * @param request
     * @return
     */
    @PostMapping("/export")
    @Operation(summary = "应付款导出")
    public void exportExpectedFortune(@RequestBody ApiExpectedFortunePageRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        if (request == null) {
            throw new RuntimeException("查询参数不能为空");
        }

        // 设置响应头
        String fileName = URLEncoder.encode("应付款管理数据", "UTF-8").replaceAll("\\+", "%20");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        apiExpectedFortuneService.exportExpectedFortune(request, response);
    }

    /**
     * 查询保单是否生成过预计发佣
     * @param policyNo
     * @return
     */
    @Override
    public Result<Boolean> isGenerate(String policyNo) {
        return apiExpectedFortuneService.isGenerate(policyNo);
    }

    /**
     * 根据保单号批量删除预计发佣数据
     * @param policyNo
     * @return
     */
    @Override
    public Result batchDelByPolicyNo(String policyNo) {
        return apiExpectedFortuneService.batchDelByPolicyNo(policyNo);
    }
}
