package cn.iocoder.yudao.module.system.controller.admin.rental;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.bpm.api.oa.BpmOARefundApi;
import cn.iocoder.yudao.module.bpm.api.oa.vo.refund.BpmOARefundDTO;
import cn.iocoder.yudao.module.system.controller.admin.rental.vo.order.RentalOrderPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.rental.vo.order.RentalOrderRespVO;
import cn.iocoder.yudao.module.system.controller.admin.rental.vo.order.RentalOrderSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.rental.vo.rentaldepositrecord.RentalDepositAmountReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.rental.RentalCustomerDO;
import cn.iocoder.yudao.module.system.dal.dataobject.rental.RentalOrderDO;
import cn.iocoder.yudao.module.system.service.rental.RentalCustomerService;
import cn.iocoder.yudao.module.system.service.rental.RentalDepositRecordService;
import cn.iocoder.yudao.module.system.service.rental.RentalOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;


@Tag(name = "管理后台 - 租赁订单")
@RestController
@RequestMapping("/system/rental-order")
@Validated
public class RentalOrderController {

    @Resource
    private RentalOrderService rentalOrderService;

    @Resource
    private RentalCustomerService rentalCustomerService;

    @Resource
    private RentalDepositRecordService rentalDepositRecordService;

    @Resource
    private BpmOARefundApi refundApi;

    @PostMapping("/create")
    @Operation(summary = "创建租赁订单")
    @PreAuthorize("@ss.hasPermission('system:rental-order:create')")
    public CommonResult<Long> createRentalOrder(@Valid @RequestBody RentalOrderSaveReqVO createReqVO) {
        return success(rentalOrderService.createRentalOrder(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新租赁订单")
    @PreAuthorize("@ss.hasPermission('system:rental-order:update')")
    public CommonResult<BigDecimal> updateRentalOrder(@Valid @RequestBody RentalOrderSaveReqVO updateReqVO) {
        return success(rentalOrderService.updateRentalOrder(updateReqVO));
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除租赁订单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('system:rental-order:delete')")
    public CommonResult<Boolean> deleteRentalOrder(@RequestParam("id") Long id) {
        rentalOrderService.deleteRentalOrder(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得租赁订单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:rental-order:query')")
    public CommonResult<RentalOrderRespVO> getRentalOrder(@RequestParam("id") Long id) {
        RentalOrderDO rentalOrder = rentalOrderService.getRentalOrder(id);
        RentalOrderRespVO respVO = BeanUtils.toBean(rentalOrder, RentalOrderRespVO.class);

        // 获取客户详情
        RentalCustomerDO customerDO = rentalCustomerService.getRentalCustomer(rentalOrder.getCustomerId());
        if (customerDO != null) {
            // 设置客户信息
            respVO.setCustomerName(customerDO.getName());
            respVO.setCustomerBankName(customerDO.getBankName());
            respVO.setCustomerBankNo(customerDO.getBankNo());
        }

        // 获取已收金额
        RentalDepositAmountReqVO amountReqVO = rentalDepositRecordService.getRentalDepositRecordAmount(rentalOrder.getOrderNo(), false);
        // 设置已收金额
        respVO.setReceivedAmount(amountReqVO.getReceivedAmount());
        // 设置已退金额
        respVO.setRefundAmount(amountReqVO.getRefundAmount());

        return success(respVO);
    }

    @GetMapping("/getByOrderNo")
    @Operation(summary = "获得租赁订单")
    @Parameter(name = "orderNo", description = "订单编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:rental-order:query')")
    public CommonResult<RentalOrderRespVO> getRentalOrder(@RequestParam("orderNo") String orderNo) {
        RentalOrderDO rentalOrder = rentalOrderService.getRentalOrder(orderNo);
        RentalOrderRespVO respVO = BeanUtils.toBean(rentalOrder, RentalOrderRespVO.class);

        // 获取已收金额
        RentalDepositAmountReqVO amountReqVO = rentalDepositRecordService.getRentalDepositRecordAmount(rentalOrder.getOrderNo(), false);
        // 设置剩余金额 = 已收金额 - 已退金额
        respVO.setRemainingDeposit(amountReqVO.getReceivedAmount().subtract(amountReqVO.getRefundAmount()));

        return success(respVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得租赁订单分页")
    @PreAuthorize("@ss.hasPermission('system:rental-order:query')")
    public CommonResult<PageResult<RentalOrderRespVO>> getRentalOrderPage(@Valid RentalOrderPageReqVO pageReqVO) {

        // 获取当前登陆用户的 所属工厂的客户信息
        List<RentalCustomerDO> rentalCustomerDOList = rentalCustomerService.getListByFactory(getLoginUserId());
        if (CollUtil.isNotEmpty(rentalCustomerDOList)) {
            pageReqVO.setCustomerIds(convertList(rentalCustomerDOList, RentalCustomerDO::getId));
        }

        PageResult<RentalOrderRespVO> pageResult = rentalOrderService.getRentalOrderPage(pageReqVO);
        // 获取等待退款的订单号
        List<String> orderNos = pageResult.getList().stream()
                .filter(item -> Objects.equals(item.getStatus(), RentalOrderDO.WAITING_FOR_REFUND))
                .map(RentalOrderRespVO::getOrderNo)
                .collect(Collectors.toList());

        // 获取订单号对应的退款申请
        Map<String, BpmOARefundDTO> refundMap = refundApi.getListByOrderNo(orderNos).getCheckedData();

        // 设置对应的订单号中的 申请退款和扣款金额
        pageResult.getList().forEach(item -> {

            // 设置剩余押金
            item.setRemainingDeposit(item.getReceivedAmount().subtract(item.getRefundAmount().add(item.getChargebacksAmount())));

            if (CollectionUtil.isNotEmpty(refundMap) && refundMap.get(item.getOrderNo()) != null) {
                item.setApplyRefundAmount(refundMap.get(item.getOrderNo()).getRefundAmount());
                item.setApplyChargebacksAmount(refundMap.get(item.getOrderNo()).getChargebacksAmount());
            }
        });

        return success(pageResult);
    }
}