package com.jeequan.jeepay.mgr.ctrl.bill;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.interfaces.bill.IReconciliationService;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.CheckBatch;
import com.jeequan.jeepay.mgr.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.CheckBatchService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 账单批次管理类
 *
 * @author zx
 *
 * @date 2021-06-07 07:15
 */
@RestController
@RequestMapping("/api/check/batch")
public class CheckBatchController extends CommonCtrl {

    @Autowired private CheckBatchService checkBatchService;

    /**
     * @author: zx
     * @describe: 列表
     */
    @PreAuthorize("hasAuthority('ENT_CHECK_BATCH_LIST')")
    @GetMapping
    public ApiRes list() {
        CheckBatch checkBatch = getObject(CheckBatch.class);

        // 时间范围条件
        Date[] dateRange = checkBatch.buildQueryDateRange();

        IPage<CheckBatch> pages = checkBatchService.page(getIPage(true), CheckBatch.gw()
                .eq(StringUtils.isNotBlank(checkBatch.getBatchNo()), CheckBatch::getBatchNo, checkBatch.getBatchNo())
                .eq(StringUtils.isNotBlank(checkBatch.getIfCode()), CheckBatch::getIfCode, checkBatch.getIfCode())
                .eq(checkBatch.getState() != null, CheckBatch::getState, checkBatch.getState())
                .eq(checkBatch.getReleaseState() != null, CheckBatch::getReleaseState, checkBatch.getReleaseState())
                .ge(dateRange[0] != null, CheckBatch::getBillDate, dateRange[0])
                .le(dateRange[1] != null, CheckBatch::getBillDate, dateRange[1])
                .orderByDesc(CheckBatch::getCreatedAt)
        );

        setIfName(pages.getRecords());

        return ApiRes.page(pages);
    }

    /**
     * @author: zx
     * @describe: 详情
     */
    @PreAuthorize("hasAuthority('ENT_CHECK_BATCH_VIEW')")
    @GetMapping("/{batchNo}")
    public ApiRes detail(@PathVariable("batchNo") String batchNo) {
        CheckBatch checkBatch = checkBatchService.getById(batchNo);
        if (checkBatch == null) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }
        return ApiRes.ok(checkBatch);
    }

    /**
     * @author: zx
     * @describe: 重新对账
     */
    @PreAuthorize("hasAuthority('ENT_CHECK_BATCH_RELOAD')")
    @PostMapping("/reload/{batchNo}")
    public ApiRes reload(@PathVariable("batchNo") String batchNo) {
        CheckBatch checkBatch = checkBatchService.getById(batchNo);
        if (checkBatch == null) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }

        String reloadType = getValStringRequired("reloadType"); // 重新执行类型：release-下载解析对账  check-仅对账

        com.jeequan.jeepay.core.entity.CheckBatch coreCheckBatch = new CheckBatch();
        BeanUtil.copyProperties(checkBatch, coreCheckBatch);

        try {
            IReconciliationService reconciliationService = SpringBeansUtil.getBean("reconciliationService", IReconciliationService.class);
            reconciliationService.reloadBill4Batch(coreCheckBatch, reloadType);

            // 处理差异
            reconciliationService.processCheckDiffBills(checkBatch.getBillDate());
            return ApiRes.ok();
        }catch (Exception e) {
            return ApiRes.customFail(e.getMessage());
        }
    }

}
